dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def getvalue(self, key):
if key == "":
return None
result = self._get(key)
if type(result) == dict:
return None
return result
def getsibling(self, key):
members = self._getmembers(key)
position = members.index(key.split('.')[-1])
try:
... | This code processes incoming messages by checking their type and returning appropriate responses or modifying internal state. It handles queries for values, siblings, children, log levels, deadlock checks, and log specifications, updating attributes like loglevel and deadlockcheck when set commands are received. Each m... | def talk(self, message):
if type(message) == MessageGetValue:
return Response(True, self.getvalue(message.params))
if type(message) == MessageGetSibling:
return Response(True, self.getsibling(message.params))
if type(message) == MessageGetChild:
return Respons... |
def eof(self) -> bool:
return self._off >= len(self._src)
def curr(self) -> str:
if self.eof():
return "\0"
return self._src[self._off]
def next(self) -> str:
if self.eof():
return "\0"
self._off += 1
return self.curr() | This function skips over whitespace characters in a sequence, advancing the current position as long as whitespace is encountered. It returns True if any whitespace was skipped, and False otherwise. | def skipWhitespace(self) -> bool:
result = False
while not self.eof() and self.curr().isspace():
self.next()
result = True
return result |
def save(self) -> None:
self._save.append(self._off)
def skipWhitespace(self) -> bool:
result = False
while not self.eof() and self.curr().isspace():
self.next()
result = True
return result
def skipStr(self, s: str) -> bool:
if self._src[self._off :].start... | This code attempts to skip a specified separator string in a token stream, including surrounding whitespace. It saves the current state, skips whitespace, tries to skip the separator, and if successful, skips additional whitespace and returns True. If the separator isn't found, it restores the previous state and return... | def skipSeparator(self, sep: str) -> bool:
self.save()
self.skipWhitespace()
if self.skipStr(sep):
self.skipWhitespace()
return True
self.restore()
return False |
def save(self) -> None:
self._save.append(self._off)
def skipWhitespace(self) -> bool:
result = False
while not self.eof() and self.curr().isspace():
self.next()
result = True
return result
def skipStr(self, s: str) -> bool:
if self._src[self._off :].start... | This function checks if the current position in a token stream matches a given separator string after skipping whitespace. It temporarily saves the stream state, skips whitespace, attempts to match the separator, and if successful, restores the state and returns True. If the separator isn't found, it restores the origi... | def isSeparator(self, sep: str) -> bool:
self.save()
self.skipWhitespace()
if self.skipStr(sep):
self.skipWhitespace()
self.restore()
return True
self.restore()
return False |
def save(self) -> None:
self._save.append(self._off)
def skipWhitespace(self) -> bool:
result = False
while not self.eof() and self.curr().isspace():
self.next()
result = True
return result
def skipStr(self, s: str) -> bool:
if self._src[self._off :].start... | This function checks if a given keyword can be skipped in the current context. It saves the current state, skips whitespace, attempts to skip the keyword, and verifies that the following character is not alphanumeric. If successful, it skips additional whitespace and returns True; otherwise, it restores the state and r... | def skipKeyword(self, keyword: str) -> bool:
self.save()
self.skipWhitespace()
if self.skipStr(keyword) and not self.curr().isalnum():
self.skipWhitespace()
return True
self.restore()
return False |
def save(self) -> None:
self._save.append(self._off)
def skipWhitespace(self) -> bool:
result = False
while not self.eof() and self.curr().isspace():
self.next()
result = True
return result
def skipStr(self, s: str) -> bool:
if self._src[self._off :].start... | This method checks if a given keyword is present in the input stream, preceded by whitespace and followed by a non-alphanumeric character, confirming it as a valid keyword. It temporarily saves the stream state, skips whitespace, attempts to skip the keyword, and validates the subsequent character. If valid, it restore... | def isKeyword(self, keyword: str) -> bool:
self.save()
self.skipWhitespace()
if self.skipStr(keyword) and not self.curr().isalnum():
self.restore()
return True
self.restore()
return False |
def parseNamespacedIdent(s: Scan) -> Tok:
"""
Exemple:
foo
foo::bar
Foo::Bar::Baz
"""
s.begin()
nextIdent(s)
while skipNamespaceSep(s):
nextIdent(s)
return s.end()
def parseString(s: Scan) -> Tok:
"""
Exemple:
'foo'
'''foo'''
"foo"
""Hello, "World"... | The code parses a module from input, extracting its name, included items, and interfaces. It expects the keyword "module", captures the namespaced identifier as the module name, collects "include" directives, and processes subsequent interfaces until the end of input, storing them in a dictionary. | def parseModule(s: Scan) -> Module:
module = Module()
s.expectKeyword("module")
module.name = parseNamespacedIdent(s).text
module.includes = []
while s.skipKeyword("include"):
module.includes.append(parseString(s).text)
module.ifaces = {}
while not s.eof():
iface = parseIface... |
def parseModule(s: Scan) -> Module:
module = Module()
s.expectKeyword("module")
module.name = parseNamespacedIdent(s).text
module.includes = []
while s.skipKeyword("include"):
module.includes.append(parseString(s).text)
module.ifaces = {}
while not s.eof():
iface = parseIface... | The main task of the code is to generate a C++ header file from an input source. It checks for a version flag, reads input/output file paths, parses module definitions, and writes C++ code including headers, namespaces, interface declarations, and dispatch functions to the output file. | def main() -> int:
if sys.argv[1] == "--version":
print("0.1.0-dev")
return 0
with open(sys.argv[1], "r") as inFile:
with open(sys.argv[2], "w") as outFile:
s = Scan(inFile.read())
module = parseModule(s)
print("#pragma once", file=outFile)
... |
def center(self):
x0_x, y0_x = self.c2t(-self.width/2, 0)
x1_x, y1_x = self.c2t(self.width/2, 0)
line_x = self.canvas.create_line(x0_x, y0_x, x1_x, y1_x, fill="#444", width=1)
x0_y, y0_y = self.c2t(0, self.height/2)
x1_y, y1_y = self.c2t(0, -self.height/2)
line_y = self.... | The function handles a right-click event by stopping ongoing calculations, clearing the canvas, re-centering, rasterizing, and redrawing the vector field, then setting the state to 0. | def bind_btn2(self, event):
self.right_click_stop_event = True
if not self.in_calculation_loop:
self.canvas.delete("all")
self.center()
self.raster()
self.draw_vector_field()
self.state(0) |
def calculate_vector_field(self, x_min, x_max, x_step, y_min, y_max, y_step, zoom):
i = 0
for x in range(x_min, x_max, x_step):
for y in range(y_min, y_max, y_step):
dx, dy = self.vecffunc(x/zoom, y/zoom)
dxy_len = math.sqrt(dx**2 + dy**2)
if i... | The main task of the code is to recalculate and redraw a vector field based on the current width, height, spacing (dxy), and zoom level, then update the display state. It first computes the vector field over a symmetric grid spanning ±width/2 and ±height/2, renders it visually, and triggers a state change to 0, likely ... | def replot(self):
W = self.width
H = self.height
self.calculate_vector_field(int(-W/2), int(W/2), self.dxy, int(-H/2), int(H/2), self.dxy, self.zoom)
self.draw_vector_field()
self.state(0) |
def state(self, state):
#print("State changed")
if state == 1: #in preocess
self.canvas.create_oval(5,5,40,40, fill = "#ffA500")
if state == 0: #ready
self.canvas.create_oval(5,5,40,40, fill = "#00ff00")
def ic2t(self, X, Y, scale_x = 1, scale_y = 1):
# scale 1: o... | This function handles a button click event to either stop an ongoing calculation or initiate a new differential equation solve. It checks the calculation state, updates flags, converts mouse coordinates, runs the solver, and displays results if animation is disabled. | def bind_btn1(self, event):
if self.in_calculation_loop:
self.right_click_stop_event = True
self.state(0)
else:
self.state(1)
self.right_click_stop_event = False
x, y = self.ic2t(event.x, event.y, scale_x = self.zoom, scale_y = self.zoom)
... |
def choose_quadrant():
quadrants = [1,2,3,4,5]
while True:
try:
choice = int(input("Please choose a quadrant (1-5), 5 is the entire whiteboard: "))
if choice in range(1, 6):
return quadrants[choice - 1]
else:
print("Invalid choice. Plea... | The code's main task is to plan and execute a Clear Path Planning (CPP) navigation for a robot within a selected quadrant defined by boundary corners. It calculates coordinates, generates a collision-avoidance path considering the robot's radius, and initiates navigation with specified duration, frequency, and steps, u... | def cpp(boundary_corners, eraser = 1):
chosen_quadrant = choose_quadrant()
print(chosen_quadrant)
#chosen_quadrant = 1
ox, oy = get_quadrant_coordinates(boundary_corners, chosen_quadrant)
print(ox)
print(oy)
resolution = 0.01 # Grid resolution in meters
robot_radius = 0.12 # Robot ra... |
def compute_pi_k(logits, prior=None):
N = logits.shape[0]
# sum for prob for each K (across all points) \sum_{i=1}^{N}P(z_i = k)
r_sum = logits.sum(dim=0)
if len(r_sum.shape) > 1:
# this is sub clusters' pi need another sum
r_sum = r_sum.sum(axis=0)
pi = r_sum / torch.tensor(N, dtype... | The function computes updated means (mus), covariances (covs), and prior probabilities (pi) for subclusters using hard assignment. It handles empty subclusters by reinitializing them, computes soft-assignment-based covariances, and applies Bayesian priors if enabled. The output includes refined subcluster parameters fo... | def compute_mus_covs_pis_subclusters(codes, logits, logits_sub, mus_sub, K, n_sub, hard_assignment=True, use_priors=True, prior=None):
pi_sub = compute_pi_k(logits_sub, prior=prior if use_priors else None)
if hard_assignment:
mus_sub_new, covs_sub_new = [], []
for k in range(K):
indi... |
def get_top_airports(mongoDB_Db, mongoDB_Col):
mycol = createMongo(mongoDB_Db, mongoDB_Col)
airports_list = mycol.distinct("origin")
airports_list += mycol.distinct("destination")
airports_list = list(set(airports_list))
airports_stats = []
#Add counts
for airport in airports_list:
i... | The function retrieves top airports, calculates monthly flight counts for each (origin/destination), formats the data, and exports multiple sheets to an Excel file containing flight statistics, rebased values, and formatted results for analysis. | def get_flights_per_airports(mongoDB_Db, mongoDB_Col):
df = get_top_airports(mongoDB_Db, mongoDB_Col)
df.to_excel("flights_counts_per_airport.xlsx", index = False)
top_airports = list(df["airport"])
criteria_list = {airport: {"$or": [{"origin": airport}, {"destination": airport}]} for airport in top_air... |
def get_top_routes(mongoDB_Db, mongoDB_Col):
mycol = createMongo(mongoDB_Db, mongoDB_Col)
flights_routes = get_multiple_distinct(mycol, ["origin", "destination"])
#Exclude routes where origin or destination is NaN (or both are)
flights_routes = [f for f in flights_routes if str(f["origin"]) != "nan" and... | This code retrieves top flight routes from a MongoDB collection, processes monthly flight counts for these routes, and exports the data into CSV and Excel files. It formats the results into multiple Excel sheets, including raw counts, rebased values, and calculated metrics, while saving the top routes list as a CSV for... | def get_flights_per_routes(mongoDB_Db, mongoDB_Col, top_n = 10000):
df = get_top_routes(mongoDB_Db, mongoDB_Col)
df.to_csv("flights_counts_per_route.csv", index = False) #CSV format as more than 1Mio rows (Excel limit)
top_routes = list(df["route"])[:top_n]
criteria_list = {route: {"origin": route.sp... |
def get_top_models(mongoDB_Db, mongoDB_Col):
mycol = createMongo(mongoDB_Db, mongoDB_Col)
models_list = mycol.distinct("model")
models_stats = []
#Add counts
for model in models_list:
if str(model) == "nan": continue
models_stats.append({"model": model, "count": mycol.count_documents... | The main task of the code is to generate and save flight count reports per aircraft model from MongoDB data. It retrieves top aircraft models, queries flight counts per month, formats the data, and exports it into an Excel file with multiple sheets containing calculated values, formatted data, and raw counts. | def get_flights_per_aircrafts(mongoDB_Db, mongoDB_Col):
df = get_top_models(mongoDB_Db, mongoDB_Col)
df.to_csv("flights_counts_per_aircraft_model.xlsx", index = False)
top_models = list(df["model"])
criteria_list = {model: {"model": model} for model in top_models}
df_counts_top_models, df_counts_top... |
def get_top_manufacturers(mongoDB_Db, mongoDB_Col):
mycol = createMongo(mongoDB_Db, mongoDB_Col)
manufacturers_list = mycol.distinct("manufacturername")
manufacturers_stats = []
#Add counts
for manufacturer in manufacturers_list:
if str(manufacturer) == "nan": continue
manufacturers_... | The function retrieves flight data per aircraft manufacturer from MongoDB, processes it to count flights monthly, and exports the results to an Excel file with multiple sheets containing formatted data, raw counts, and rebased values for the top manufacturers. | def get_flights_per_manufacturers(mongoDB_Db, mongoDB_Col, top_n = 10000):
df = get_top_manufacturers(mongoDB_Db, mongoDB_Col)
df.to_csv("flights_counts_per_aircraft_manufacturer.xlsx", index = False)
top_manufacturers = list(df["manufacturer"])[:top_n]
criteria_list = {manufacturer: {"manufacturername"... |
def cleanLocal(self, dir):
if os.path.exists(dir):
for the_file in os.listdir(dir):
file_path = os.path.join(dir, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
else:
... | This code updates to the latest software version by cleaning temporary files, downloading the latest release, extracting it, and removing the zip file. | def getLatestVersion(self):
logging.info("Cleaning Local Files")
self.cleanLocal(self.temp_dir)
logging.info("Downloading")
self.downloadLatestRelease()
logging.info("Unzipping")
self.unzipLatestRelease()
logging.info("Cleaning temp files")
self.deleteZ... |
def get_data_buffer(self, images, labels):
# Fast loader gives more clean data to the model to stabilize the training.
if self.use_fast_loader:
clean_images_2, clean_labels_2 = next(iter(self.trainloader_fast))
clean_labels_2 = clean_labels_2.to(self.device, non_blocking=True)
... | The main task of this code is to train a machine learning model over an epoch, handling mini-batch processing, gradient accumulation, and periodic evaluation. It initializes training parameters, processes data with buffering, computes gradients, updates the optimizer, tracks loss and accuracy, and saves/evaluates the m... | def train_epoch(self, eval_freq_iter=200, debug=False):
# Set seed here so that we can control the shuffling
utils.seed_all(20221105 + self.cur_ep)
if self.pa_train_data is None:
print("No pre-attacked data specified. Using adaptive attack only.")
total_loss, correct, total ... |
def load_checkpoint(self, load_path, enable_BN=False, reset_scheduler=False):
ep_start, ba, img_inds = utils.load_ckpt(
self.comp_model, self.optimizer, self.scheduler, self.warmup_scheduler, self.grad_scaler,
lr=self.training_settings['lr'], load_path=load_path, batch_per_ep=len(self.tr... | This code trains a model by initializing settings, loading checkpoints if specified, iterating over epochs with training and evaluation, adjusting model parameters, and saving results with TensorBoard logging. It handles pre-attacked data shuffling, periodic model saving, and evaluation based on the provided frequency. | def train(self, save_path, load_path=None, eval_freq={"epoch": 1, "iter": 200}, debug=False):
print(f"Autocast enabled: {self._comp_model.enable_autocast}.")
self.comp_model.train()
self.save_path = save_path # Save folder path
self.writer = SummaryWriter(self.save_path) # TensorBoard... |
def __violation_handler(self, node):
while node:
node.height = max(self.__get_height(node.left), self.__get_height(node.right)) + 1
self.__violation_fix(node)
node = node.parent
def __find_successor(self, node):
if node.left:
return self.__find_successor(n... | This method recursively removes a node with specified data from a binary tree, handling three cases: leaf node deletion, single-child node deletion, and two-child node deletion using a successor swap. It updates parent pointers, adjusts tree structure, and triggers a violation handler to maintain tree balance after del... | def __remove_data(self, data, node):
if data < node.data:
if node.left:
self.__remove_data(data, node.left)
elif data > node.data:
if node.right:
self.__remove_data(data, node.right)
elif data == node.data:
if not node.left and... |
def _process_subs_from_file(self, file_path):
"""Reads and processes subtitles from a file."""
raw_subs = None
with open(file_path, encoding="utf-8") as f:
raw_subs = f.read()
subs = list(srt.parse(raw_subs))
return self._merge_subtitles(subs)
def _merge_subtitles(se... | The code processes an SRT-formatted subtitle file by extracting and merging its content, then indexes the merged subtitles into a Vectara corpus using the provided video title and corpus ID. | def index_file(self, file_path, video_title, corpus_id):
"""Given a file with SRT-format subtitles, indexes them into Vectara.
Args:
file_path: Path to the SRT file.
video_title: Title of the video.
corpus_id: Corpus ID to index into.
"""
subs = self.... |
def makeTextFilter():
xml = "<filter>"
xml += makeFilterLabel()
#randomly create fields
for n in range(random.randint(1,3)):
xml += "<field>" + random.choice(STR_FIELD_POOL) + "</field>"
#create filter operator for the values
xml += makeOperator()
xml += makeFilterExclude()
... | The main task of the code is to randomly generate one of four filter types ("filter", "idFilter", "dateFilter", "booleanFilter") by selecting a random type from a predefined list and returning an instance created by the corresponding function (e.g., makeTextFilter, makeIdFilter). It acts as a factory function to produc... | def makeRandomFilter():
types = ["filter", "idFilter", "dateFilter", "booleanFilter"]
chosenType = random.choice(types)
if chosenType == "filter":
return makeTextFilter()
elif chosenType == "idFilter":
return makeIdFilter()
elif chosenType == "dateFilter":
return makeDateFilt... |
def makeRandomWords(numberWords=20):
words = random.sample(WORD_POOL, numberWords)
words = " ".join(words)
return re.sub("[^a-zA-Z0-9 ]", "", words)
def makeRandomIcon():
icon = random.choice(ICON_POOL)
icon = re.sub("[^a-zA-Z0-9]", "", icon)
return icon
def makeUIFilter():
xml = "<filter>... | The code generates a random XML structure for a UI filter group, including a label, description, icon, and 1–8 randomly selected filter types (e.g., dateFilter, booleanFilter). Each component uses randomized content, creating a dynamic UI configuration. | def makeUIFilterGroup():
xml = "<filterGroup>"
xml += "<label>" + makeRandomWords(random.randint(1,3)) + "</label>"
xml += "<description>" + makeRandomWords(random.randint(3,20)) + "</description>"
xml += "<icon>" + makeRandomIcon() + "</icon>"
filterTypes = ["filter", "dateFilter", "booleanFilt... |
def makeRandomFilters(maxFilters=10):
filtersXML = ""
for n in range(random.randint(1,maxFilters)):
filtersXML += makeRandomFilter()
return filtersXML
def makeOperator():
#Choose a random operator or skip one altogether
operators = ["<operator>AND</operator>", "<operator>OR</operator>", ""... | This function generates an XML string representing a hierarchical filter structure with random components. It creates a base set of filters, recursively adds nested filter groups (up to maxLevels depth), includes an operator, and an exclude filter, adhering to constraints on maximum filters, groups, and nesting levels. | def makeFilterGroupType(maxLevels = 6, maxFilters = 6, maxFilterGroups = 4):
xml = ""
xml += makeRandomFilters(maxFilters = maxFilters)
levels = random.randint(1,maxLevels)
levels -= 1
for n in range(random.randint(0,maxFilterGroups)):
if levels > 0:
xml += "<filterGroup>"
... |
def createRandomPools():
#Get the list of ids from the local ids file
idFile = open("ids.txt", "r")
global ID_POOL
ID_POOL = idFile.readlines()
idFile.close()
#Get the list of image ids from the local image ids file
imageIdFile = open("imageIds.txt", "r")
global IMAGE_POOL
IMAGE_POO... | The code generates a randomized XML document for a portal, creating elements like label, name, description, logo, sections, and associated parties with random values. It constructs a structured XML file using predefined functions, adds dynamic content through loops, and writes the result to "portal.xml". The script inc... | def makePortalDocument():
createRandomPools()
#Start the portal node
xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><por:portal xmlns:por=\"https://purl.dataone.org/portals-1.1.0\">"
label = makeRandomWord() + str(random.randint(10, 99))
name = makeRandomWords(random.randint(5, 10))
print("L... |
def get_user_int(message, valid_range=None):
"""Return an integer from the user
Args:
message (str): Message to prompt user with.
valid_range (iter or list of ints): A range or list of valid numbers.
"""
while True:
user_input = input('{}: '.format(message))
# Type val... | The main task of the code is to display a student menu, validate user input as an integer between 1-4, and execute corresponding actions: registering/dropping courses, displaying schedules, or exiting. It uses a loop to repeatedly prompt until the user selects "Quit" (option 4). | def main_menu(student):
"""
Display menu for user, checks if the user input is an integer and does
action basis option chosen.
"""
menu_string = (
'\n\t** MAIN MENU **\n'
'\nStudent: {} {}\n'
'\t1) Register Course\n'
'\t2) Drop Course\n'
'\t3) Display Schedu... |
def check_keydown_events(stats, aliens,event, ship, screen, ai_settings, bullets,sb):
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:
# Create a Bullet and adds it in bullet group
... | The main task of the code is to handle user input events in a Pygame game. It processes keyboard presses (movement/shooting), mouse clicks (play button interaction), and quit commands. Events trigger functions to update game state, control ship movement, manage bullets, and initiate gameplay when the play button is cli... | def check_events(ship, screen, ai_settings, bullets, play_button, stats,aliens,sb):
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(stats, aliens,event... |
def check_fleet_edges(ai_settings, aliens):
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai_settings, aliens)
break
def check_aliens_bottom(ai_settings, stats, aliens, ship, screen, bullets,sb):
screen_rect = screen.get_rect()
for alien in ali... | This function updates alien behavior in a game, checking for edge collisions, updating alien positions, detecting if aliens reach the screen bottom, and handling ship-alien collisions. It triggers responses like ship damage or game state changes when collisions occur, ensuring game mechanics like movement, boundaries, ... | def update_aliens(ai_settings, stats, aliens, ship, screen, bullets,sb):
check_fleet_edges(ai_settings, aliens)
aliens.update()
check_aliens_bottom(ai_settings, stats, aliens, ship, screen, bullets,sb)
if pygame.sprite.spritecollideany(ship, aliens):
ship_hit(ai_settings, stats, aliens, ship, sc... |
def _execute_standard(self, *args, **kwargs):
if self._host_is_local():
return self._execute_local(*args, **kwargs)
else:
return run(*args, **kwargs)
def _execute_append(self, filename, text, **kwargs):
if self._host_is_local():
file = open(filename, "a+")
... | The main task of the code is to start a Clipper instance by generating a `docker-compose.yml` file with specified configurations, removing any existing file, and launching the `query_frontend` service in detached mode using Docker Compose. The process ensures Clipper is initialized and operational, enabling machine lea... | def start(self):
"""Start a Clipper instance.
"""
with hide("output", "warnings", "running"):
self._execute_standard("rm -f docker-compose.yml")
self._execute_append("docker-compose.yml",
yaml.dump(
se... |
def _publish_new_model(self, name, version, labels, input_type,
container_name, model_data_path):
url = "http://%s:%d/admin/add_model" % (self.host,
CLIPPER_MANAGEMENT_PORT)
req_json = json.dumps({
"model_name": name,... | (The main task of the code is to register a machine learning model with Clipper, deploy it in Docker containers, and configure model data handling. It accepts a model (as an object or file path), container specifications, and metadata, then serializes the model, publishes it to Clipper, copies data to the host, and lau... | def deploy_model(self,
name,
version,
model_data,
container_name,
labels,
input_type,
num_containers=1):
"""Registers a model with Clipper and deploys instances of i... |
def generate_random_pos(N):
x = random.randint(0, N - 1)
y = random.randint(0, N - 1)
return (x, y)
def initialize(self, port):
self.serverclass = self.CommanderInitializer(self)
self.server = grpc.server(futures.ThreadPoolExecutor())
self.server.add_insecure_port(f"{get_ipv4_address... | This code initializes a game environment with parameters N, M, t, T, s, and a port. It sets up soldier positions, starts a game loop, and checks if at least half of the maximum soldiers (M) are present to determine a win/loss outcome, displaying colored console messages accordingly. | def __init__(self, N, M, t, T, s, port, skip_init=False) -> None:
if not skip_init:
self.N = N
self.M = M
self.t = t
self.T = T
self.s = s
self.soldiers = {} # soldier = (ip, port, (x, y))
self.pos = generate_random_pos(self.N)... |
def read_traj(traj_name):
print("loading %s"%traj_name)
with open(traj_name) as raw:
lines = raw.readlines()
split_lines = list_splitter(lines)
num_atoms = int(split_lines[0][0])
print("num_atoms: %i"%num_atoms)
traj_length = int(len(split_lines)/(num_atoms+2)) #accounting for the atom l... | The code identifies the top and bottom N frames with largest/smallest energy differences from a list, computes adjusted distance matrices by subtracting a reference frame, averages these matrices, and saves results. It reads trajectory data, processes distance matrices, visualizes key frames, and exports indices to a f... | def N_comp(n, diff_list):
# find N largest difference
# n = 100
diff_sort = sorted(diff_list)
print(diff_sort[-n:])
traj, num_atoms, traj_length, atomlist, elements = read_traj('all.xyz')
dist_matrix = get_dist_matrix(traj_length, num_atoms, traj, 'all_dist_matrices.p')
plot_fra... |
def parser(sam, SE=None):
sam = pysam.AlignmentFile(sam)
dic = {}
res = []
dic_segment = {}
for i in sam.fetch():
dic.setdefault(i.qname, {}).setdefault(
'chrom', []).append(i.reference_name)
if i.is_read1:
dic.setdefault(i.qname, {}).setdefault('read1', []).a... | The code processes chimeric RNA-seq reads (`chimericSam`) and gene annotations (`gtf`) to identify and count splice sites. It converts GTF annotations to gene prediction format, maps chimeric reads to gene regions, annotates overlapping segments, validates splice sites against a genome, and outputs counts. Temporary fi... | def main(chimericSam, gtf, out, genome, SE):
test, dic_segment = parser(chimericSam, SE)
os.system('gtfToGenePred -genePredExt -geneNameAsName2 %s %s.GenePred' % (gtf, out))
a = GenePred('%s.GenePred'%out)
anno = getInterect(test, a.gene_pos, out)
b = get_annotation(anno, dic_segment, a.genes)
... |
def get_subscribed_users():
global SUBSCRIBED_USERS
return SUBSCRIBED_USERS
def get_reactor(event):
return event['user']
def get_reaction_author(event):
message, emoji_name = get_message(event), get_emoji_name(event)
reaction = get_reaction(message, emoji_name)
users = get_users(reaction)
re... | The main task of the code is to notify subscribed users when they added a reaction to an event, but the reactor (the entity triggering the event) is not themselves. It iterates through subscribed users, checks if the reaction author matches the user and the reactor differs, then sends a notification to the user if so. | def process_reaction_added(event):
for subscribed_user in get_subscribed_users():
reactor = get_reactor(event)
reaction_author = get_reaction_author(event)
if reaction_author == subscribed_user and reactor != subscribed_user:
tell_subscribed_user(subscribed_user, event)
... |
def is_emoji_added_event(event):
return event['value'].startswith('https://')
def process_emoji_added(event):
emoji_name = event['name']
tell(DESTINATION_CHANNEL, f'New emoji added!')
tell(DESTINATION_CHANNEL, f'`:{emoji_name}:`')
tell(DESTINATION_CHANNEL, f':{emoji_name}:')
def is_alias_added_event... | The function `process_emoji_changed` handles events related to emoji or alias additions. It checks the event type using helper functions: if it's an emoji addition, it calls `process_emoji_added`; if an alias addition, it calls `process_alias_added`. If the event type is unknown, it raises an exception. The main task i... | def process_emoji_changed(event):
if is_emoji_added_event(event):
process_emoji_added(event)
elif is_alias_added_event(event):
process_alias_added(event)
else:
raise Exception('UNKNOWN EMOJI CHANGED EVENT') |
def get_time_est(time):
# Parse the date string into a datetime object
date_time_utc = datetime.fromisoformat(time[:-1]) # Remove 'Z' at the end
# Convert UTC datetime to Eastern Time (subtracting 4 hours for EDT)
date_time_est = date_time_utc - timedelta(hours=4)
# Extract hour and minut... | The code schedules and triggers specific announcements based on the time provided in the event. It converts the UTC time to EST, checks if the time matches predefined conditions (Sunday 8 AM, Friday 8 AM, or Friday 5:50 PM), and sends corresponding messages: weekly announcements, day-of announcements, or reminders. | def lambda_handler(event, context):
print('EVENT', event)
if 'time' not in event:
return
time_utc = event['time']
day, hour, minute = get_time_est(time_utc)
if ([day, hour] == 'Sunday', 8):
send_weekly_announcement()
elif ([day, hour] == 'Friday', 8):
send_d... |
def get_request(lambda_event):
body = lambda_event.get("body")
if body is None:
return None
else:
request = json.loads(body)
return request
def process_reaction_added(event):
for subscribed_user in get_subscribed_users():
reactor = get_reactor(event)
reaction_auth... | This Lambda function handles Slack application events by verifying the endpoint with a challenge response and processing specific event types like 'reaction_added' and 'emoji_changed'. It logs events, checks for Slack's challenge token, and triggers corresponding processing functions based on event types, returning app... | def lambda_handler(event, context):
print(json.dumps(event))
lambda_event = event
req = get_request(lambda_event)
print(json.dumps(req))
#
# Random GET request and the like
#
if req is None:
return {
'statusCode': 200
}
#
# Slack application ... |
def update_clock(self):
current_time = datetime.now().strftime("%H:%M")
self.clock_label.config(text=current_time)
self.after(1000, self.update_clock)
def update_date(self, date_str):
self.date_label.config(text=date_str)
def update_weather(self):
temperature, humidity, condition... | The code initializes an MQTT handler for communication, updates the clock, date, weather, and clothing information on a mirror interface, then starts the main application loop to maintain real-time updates and functionality. | def start_mirror(self):
mqtt_handler = MQTTHandler(self)
mqtt_handler.start()
self.update_clock()
self.update_date(datetime.now().strftime("%A, %B %d"))
self.update_weather()
self.update_clothing() # Call the new function to update clothing
self.mainloop() |
def has_finished(self) -> bool:
"""
Return wether all rounds have been played.
"""
return self.rounds_played == self.n_rounds
def play_round(self) -> None:
"""
Play a single round and save associated statistics.
"""
top_scored_players = self.roll()
... | The main task of the code is to run a game simulation by repeatedly executing rounds until completion, ensuring at least one player exists. It loops, playing each round and saving statistics after every iteration, raising an exception if no players are present. | def play(self) -> None:
"""
Run game simulation.
"""
if self.n_players == 0:
raise NoPlayerException
while not self.has_finished():
self.play_round()
self.save_round_stats() |
def __height__(self, node):
if node is None:
return 0
else:
left = self.__height__(node.left)
right = self.__height__(node.right)
return 1 + max(left, right)
def __right_rotation__(self, node):
lefty = node.left
temp = lefty.right
l... | This function inserts a new Pokémon node into an AVL tree, maintaining balance through rotations. It recursively places data based on ID comparisons, updates node heights, and applies left/right rotations to correct imbalances caused by insertions, ensuring the tree remains height-balanced for efficient operations. | def __insertion__(self, node, data):
if node is None:
return AVL(data['id'], data['name'], data['pk_height'], data['pk_weight'], data['xp'], data['image_url'],
data['pokemon_url'], data['abilities_1_name'], data['abilities_1_bool'],
data['abilities_2_nam... |
def take_screenshot(device_id, count, adb_path):
# Check if the screenshot file already exists
if os.path.exists(f"screenshot{count}.png"):
count += 1
else:
# Use adb to take screenshot on the device
os.system(
f"{adb_path} -s {device_id} shell screencap -p /sdcard/screen... | The main task of the code is to continuously capture screenshots using ADB, process new images when changes are detected, execute tasks based on the processed image, and clean up previous screenshots. The loop runs indefinitely, handling keyboard interrupts to exit gracefully. | def main_loop():
global count
global old_count
global adb_path
global click_location
while True:
# Take the screenshot
try:
count = take_screenshot(device_id, count, adb_path)
if count != old_count or img is None: # Check if the screenshot is new
... |
def stargeomtime(T,m,rho=None):
return stargeomshrink(T,m,rho)
def starrho(T,m,rho=None):
if rho==None:
rho = m*(m/(m-1))**(m-1)
low = 2
high = int(m*np.log(T)/np.log(rho))+2
hx = gausssolveexacttopdown(high,T,m,rho)
while not hx:
low=high
high*=2
hx = gausssolvee... | The function `testrho` generates and plots clearance values for three different strategies (Optimal, Mixed aggressive, Scaled geometric) against varying R values. It calculates R values by linearly spacing between a base value `rhom` and a scaled version (`rhofactor * rhom`), then evaluates each strategy's clearance at... | def testrho(x,m,rhofactor,npoints):
rhom = m**m/(m-1)**(m-1)
rhos = np.linspace(rhom,rhofactor*rhom,npoints)
yfact = [stargeomtime(x,m,rho) for rho in rhos]
yfact2 = [starrho(x,m,rho) for rho in rhos]
yfact3 = [staraggrtime(x,m,rho) for rho in rhos]
plt.plot(rhos*2+1,yfact2,label="Opti... |
def starrho(T,m,rho=None):
if rho==None:
rho = m*(m/(m-1))**(m-1)
low = 2
high = int(m*np.log(T)/np.log(rho))+2
hx = gausssolveexacttopdown(high,T,m,rho)
while not hx:
low=high
high*=2
hx = gausssolveexacttopdown(high,T,m,rho)
#print(low,high)
lx = gausssolvee... | The code calculates and plots the clearance ratio for three different metrics (Optimal/scaled geometric, Optimal/mixed aggressive, Mixed aggressive/scaled geometric) across a logarithmic range of T values. It computes these ratios using functions starrho, stargeomtime, and staraggrtime, then visualizes them on a log-sc... | def testfactor(x0,xn,m,rhofactor,npoints):
rho = m**m/(m-1)**(m-1)*rhofactor
xs = np.logspace(x0,xn,npoints)
yfact = [starrho(x,m,rho)/stargeomtime(x,m,rho) for x in xs]
yfact2 = [starrho(x,m,rho)/staraggrtime(x,m,rho) for x in xs]
yfact3 = [staraggrtime(x,m,rho)/stargeomtime(x,m,rho) for ... |
def stargeomtime(T,m,rho=None):
return stargeomshrink(T,m,rho)
def starrho(T,m,rho=None):
if rho==None:
rho = m*(m/(m-1))**(m-1)
low = 2
high = int(m*np.log(T)/np.log(rho))+2
hx = gausssolveexacttopdown(high,T,m,rho)
while not hx:
low=high
high*=2
hx = gausssolvee... | The function `testx` generates logarithmically spaced values `xs` between `x0` and `xn`, computes a parameter `rho` based on `m` and `rhofactor`, and evaluates three strategies—geometric, aggressive, and optimal—using helper functions. It then plots the results of these strategies against `xs` on a logarithmic scale, l... | def testx(x0,xn,m,rhofactor,npoints):
xs = np.logspace(x0,xn,npoints)
rho = m**m/(m-1)**(m-1)*rhofactor
ygeom=[stargeomtime(x,m,rho) for x in xs]
yrho=[starrho(x,m,rho) for x in xs]
yaggr=[staraggrtime(x,m,rho) for x in xs]
plt.plot(xs,ygeom,label="Geometric strategy")
plt.plot(xs,... |
def stargeomtime(T,m,rho=None):
return stargeomshrink(T,m,rho)
def starrho(T,m,rho=None):
if rho==None:
rho = m*(m/(m-1))**(m-1)
low = 2
high = int(m*np.log(T)/np.log(rho))+2
hx = gausssolveexacttopdown(high,T,m,rho)
while not hx:
low=high
high*=2
hx = gausssolvee... | The function `testm` compares three strategies (geometric, optimal, aggressive) by computing and plotting their clearance values against varying `m` parameters. It generates `m` values from `m0` to `mn`, calculates clearance for each strategy using specific formulas involving `rhofactor` and `m`, then visualizes the re... | def testm(x,m0,mn,rhofactor,npoints):
ms = list(range(m0,mn))
ygeom=[stargeomtime(x,m,rhofactor*m**m/(m-1)**(m-1)) for m in ms]
yrho=[starrho(x,m,rhofactor*m**m/(m-1)**(m-1)) for m in ms]
yaggr=[staraggrtime(x,m,rhofactor*m**m/(m-1)**(m-1)) for m in ms]
plt.plot(ms,yrho,label="Optimal strategy"... |
def testfactor(x0,xn,m,rhofactor,npoints):
rho = m**m/(m-1)**(m-1)*rhofactor
xs = np.logspace(x0,xn,npoints)
yfact = [starrho(x,m,rho)/stargeomtime(x,m,rho) for x in xs]
yfact2 = [starrho(x,m,rho)/staraggrtime(x,m,rho) for x in xs]
yfact3 = [staraggrtime(x,m,rho)/stargeomtime(x,m,rho) for ... | This function executes predefined tests based on the 'testid' parameter, invoking sub-functions like testfactor, testx, testrho, or testm with parameters such as x, m, rhofactor, and npoints. If testid is 'table', it iterates over m and rhofactor values to compute and print 'gain'. It saves generated plots to a specifi... | def test(testid,filename=None,x=1e5,x0=1,xn=15,m=4,m0=3,mn=20,rhofactor=1,npoints=1000):
if testid=='factor':
testfactor(x0,xn,m,rhofactor,npoints)
elif testid=='x':
testx(x0,xn,m,rhofactor,npoints)
elif testid=='rho':
testrho(x,m,rhofactor,npoints)
elif testid=='m':
test... |
def check_employee_benefit(doc):
has_employee_benefit = 0
payments = doc.custom_invoice_payments
for payment in payments:
if payment.payment_mode =="Employee Benefit":
has_employee_benefit = 1
if (has_employee_benefit == 1) and ((doc.custom_employee=="") or (doc.custom_employee=... | The function `validate_si` performs multiple validation tasks on a document by sequentially executing helper functions like `make_packing_list`, `check_employee_benefit`, `validate_payments`, and others, likely ensuring data integrity, compliance, or correctness in a specific system. The `method` parameter is unused in... | def validate_si(doc, method):
make_packing_list(doc)
check_employee_benefit(doc)
validate_payments(doc)
pull_item_pf_incentives(doc)
check_hmo_card_no(doc)
check_or(doc) |
def _flatten_options(option_values: OptionDict) -> OptionDict:
flat = {}
for key, value in option_values.items():
if type(value) == dict:
flat.update(value)
else:
flat[key] = value
return flat
def format_command(command: Command, option_dic... | The code executes a command with dynamic and static options multiple times (`iterations`), skipping the first `skip` executions. It generates all possible combinations of dynamic options using `itertools.product`, formats the command with option values, runs it via `subprocess`, and logs results or timeouts. Each comma... | def run(self, iterations: int = 1, skip: int = 0):
"""
Runs the given command over all the options `iterations` times, skipping the first `skip` values.
Skip counts command executions, not commands themselves. ie if iterations is 2, skip=2 will skip the first command entirely
Calls `hand... |
def _get_evidence(self, state):
"""
Computes noisy distances between pacman and ghosts.
Arguments:
----------
- `state`: The current game state s_t
where 't' is the current time step.
See FAQ and class `pacman.GameState`.
Return:
... | The main task of the code is to update the belief state of ghost positions in a Pacman game based on the current game state. It initializes necessary variables, gathers evidence from the environment, updates the belief states using this evidence, records performance metrics, and returns the updated belief states along ... | def get_action(self, state):
"""
Given a pacman game state, returns a belief state.
Arguments:
----------
- `state`: the current game state.
See FAQ and class `pacman.GameState`.
Return:
-------
- A belief state.
"""
"... |
def getSortUpDownForFields(self):
def toggleSort(what):
what = what.strip().lower()
if what == "" or what is None:
what = "down"
elif what == "down":
what = "up"
elif what == "up":
what = ""
else:
... | This function handles paginated data retrieval by calculating current page, offset, and total pages, then fetching data with specified limits and offsets. It incorporates sorting, session-based pagination state, and dynamic page adjustments based on item count and navigation parameters. | def getRowsWithPaginate(self):
self.getSortUpDownForFields()
nav, limit = self.getNavAndLimit()
currentPage = self.getSessionItemByNameWithDefault("currentPage", 0)
offset = self.getSessionItemByNameWithDefault("offset", 0)
q, count = self.basicSelectWithCount() # will later n... |
def getRowsWithPaginate(self):
self.getSortUpDownForFields()
nav, limit = self.getNavAndLimit()
currentPage = self.getSessionItemByNameWithDefault("currentPage", 0)
offset = self.getSessionItemByNameWithDefault("offset", 0)
q, count = self.basicSelectWithCount() # will later n... | The main task of the code is to retrieve and format paginated data from a database model, prepare structured response data including items, pagination metadata, and session filters/sort settings, then return it as a dictionary for a list view. It processes raw rows into dictionaries, applies field formatting, and inclu... | def listAll(self): # pylint: disable=unused-argument
if self.verbose:
self._verb(str("POST: {self.request.POST}"))
rows, limit, count, pages, currentPage = self.getRowsWithPaginate()
# apply format to date time items
prepRows = []
for row in rows:
prepR... |
def clickph(img):
btn = None
findWin("sponsored session", True)
btn = clickOnScreen(img)
if not btn:
print('[{}] {} not found'.format(time.strftime('%d/%m %X'), img))
raise Exception
return btn
def sl(i):
time.sleep(i)
def findWin(w, close=False, fg=True):
def myHandler(hwnd,... | The main task of the code is to automate connecting a wallet (likely Metamask) by simulating UI interactions: clicking "connect wallet" and "sign" buttons via image recognition, handling notifications, and waiting for processes to complete. It includes timestamp logging, delays, and window interaction to execute wallet... | def connectWallet():
print("[{}] connect wallet".format(time.strftime('%d/%m %X')))
clickph('assets/connect-wallet.png') # connect wallet #clickk(978,785) # connect wallet
sl(5) # for metamask notification to disapear
findWin("metamask notification")
clickph('assets/sign.png') # sign metamas... |
def startBrowser():
global secretshit
print("[{}] start new - wrong windows".format(time.strftime('%d/%m %X')))
subprocess.Popen(["taskkill","/f","/im","chrome.exe"],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
sl(2)
subprocess.Popen([NAVI,"app.bombcrypto.io"],stdout=subprocess.DEVNULL,stder... | The code's main task is to start a browser, check for and close existing MetaMask notification windows, connect a wallet, and navigate to a map. It ensures no lingering MetaMask alerts are present before proceeding with wallet connection and mapping functions. | def onStart():
startBrowser()
# fermer les anciennes page MetaMask
found = findWin("metamask notification", True)
print("[{}] close metamask if any".format(time.strftime('%d/%m %X')))
while(found):
found = findWin("metamask notification", True)
connectWallet()
toMap() |
def findWin(w, close=False, fg=True):
def myHandler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
top_windows = []
win32gui.EnumWindows(myHandler, top_windows)
res = False
for i in top_windows:
if w in i[1].lower():
res = True
if... | This function automates game actions: locates the Bombcrypto Chrome window, captures a screenshot, navigates back from a map, logs the timestamp, moves to a hero location, waits 3 seconds, then clicks an 'rest-all.png' image to trigger a rest action. | def allToRestNew():
findWin("bombcrypto - google chrome")
screenshot()
backFromMap()
print("[{}] -- AllToRest()".format(time.strftime('%d/%m %X')))
toHero1()
sl(3)
clickph('assets/rest-all.png')
sl(3) |
def screenshot():
sl(1)
sc = pa.screenshot()
scdir = str(Path(__file__).parent)#.replace('\\','\\')
scdir += "\\screen\\{}.png".format(time.strftime('%d-%m__%H-%M-%S'))
#print('[{}] screenshot()'.format(time.strftime('%d/%m %X')))
sc.save(scdir)
def backFromMap():
clickph('assets/back-from-m... | The main task of the code is to automate interactions in a game or application by navigating to a hero section, capturing screenshots at key steps, scrolling through content, and returning to the map. It includes debugging timestamps and image-based clicks, likely for monitoring or testing UI behaviors. | def bomberState():
print("[{}] bomberstate()".format(time.strftime('%d/%m %X')))
screenshot()
backFromMap()
toHero1()
clickph('assets/home2.png')
screenshot()
for i in range(2):
scroll5()
screenshot()
backFromHero1()
toMap() |
def findWin(w, close=False, fg=True):
def myHandler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
top_windows = []
win32gui.EnumWindows(myHandler, top_windows)
res = False
for i in top_windows:
if w in i[1].lower():
res = True
if... | This function automates game actions: locates a Chrome window, takes a screenshot, navigates to a hero, waits, instructs bombers to rest, then returns to the map, logging the process with a timestamp. | def allToRest():
findWin("bombcrypto - google chrome")
screenshot()
backFromMap()
print("[{}] -- AllToRest()".format(time.strftime('%d/%m %X')))
toHero1()
sl(3)
for i in range(BOMBERS): bomber(0, 'rest')
backFromHero1()
toMap() |
def bomberState():
print("[{}] bomberstate()".format(time.strftime('%d/%m %X')))
screenshot()
backFromMap()
toHero1()
clickph('assets/home2.png')
screenshot()
for i in range(2):
scroll5()
screenshot()
backFromHero1()
toMap()
def sl(i):
time.sleep(i)
def findWin(w,... | The main task of this code is to execute periodic sleep intervals (default 15 minutes) while performing actions like checking window states, calling `bomberState()` conditionally, and executing `toGain2()`/`backFromGain()` routines. It ensures the total duration `d` is at least `p` minutes, splits it into `count` inter... | def sleepInPeriods(d, p=15, state=False):
assert(p>0)
assert(d>0)
print("[{}] -- sleepInPeriods()".format(time.strftime('%d/%m %X')))
if d < p:
d = p
count = int(d/p)
for i in range(int(d/p)):
if state:
bomberState()
#e = random.randint(-1,1)
e=0
... |
def findWin(w, close=False, fg=True):
def myHandler(hwnd, top_windows):
top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
top_windows = []
win32gui.EnumWindows(myHandler, top_windows)
res = False
for i in top_windows:
if w in i[1].lower():
res = True
if... | The code automates tasks in a game or application by checking for a specific window ("bombcrypto - google chrome"), detecting an image ('assets/gain2.png') on the screen, navigating to a map if the image isn't found, performing work-related actions, and introducing timed delays. It uses functions like findWin, findOnSc... | def dayModeOnce(p=15):
for i in range(2): findWin("bombcrypto - google chrome")
if not findOnScreen('assets/gain2.png'):
toMap()
toWorkNew()
# sleepInPeriods(10*2,10, False)
d = 40*3 #(60 + random.randint(-5,5))
p = 40
sleepInPeriods(d,p, True) |
def perploc(self):
#Find the user defined locations for the perpendicular vectors.
dist_coast=self.distancefrominit()
index_perp=[find(dist_coast,dis*1000) for dis in self.dist]
return index_perp
def perp2coast(self,method='smooth',x=10):
'''
Input:
m... | This function computes and scales perpendicular vectors from a coastline grid, generating gridded normal and perpendicular vectors at specified distances. It calculates scaled vectors, adjusts coordinates for grid spacing, and returns multiple formatted vector arrays (normal, perpendicular, and midpoint-adjusted) for f... | def vertor_perp(self,shift=0):
# Nearest location of perpendicular vectors from coastline grid.
index_perp=self.perploc()
# Compute perpendicular vectors.
perp_dict=self.perp2coast()
# Scale perpendicular vector to desired distance self.length.
scale=self.vector_scale(ind... |
def add_prefix(message):
return str.format("aioftp client: {}", message)
def parse_response(self):
"""
:py:func:`asyncio.coroutine`
Parsing full server response (all lines).
:return: (code, lines)
:rtype: (:py:class:`aioftp.Code`, :py:class:`list` of :py:class:`str`)
... | This function executes a command, waits for responses until non-matching codes are received, validates against expected codes, and returns the final response code and info. It handles asynchronous communication by sending commands, parsing responses, and ensuring outcomes match expected results while managing wait cond... | def command(self, command=None, expected_codes=(), wait_codes=()):
"""
:py:func:`asyncio.coroutine`
Basic command logic.
1. Send command if not omitted.
2. Yield response until no wait code matches.
3. Check code for expected.
:param command: command line
... |
def exists(self, path):
"""
:py:func:`asyncio.coroutine`
Check path for existence.
:param path: path to check
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
:rtype: :py:class:`bool`
"""
code, info = yield from self.command(
... | This code defines an asynchronous method to recursively remove a file or directory at the specified path. It checks if the path exists, determines its type (file/dir), and deletes files directly or recursively removes all contents of directories before deleting the directory itself. | def remove(self, path):
"""
:py:func:`asyncio.coroutine`
High level remove method for removing path recursively (file or
directory).
:param path: path to remove
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
"""
if (yield from self.exis... |
def make_directory(self, path, *, parents=True):
"""
:py:func:`asyncio.coroutine`
Make directory.
:param path: path to directory to create
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
:param parents: create parents if does not exists
:type p... | This method asynchronously uploads files or directories from the client's filesystem to the server, recursively handling nested structures. It supports renaming files/directories via `write_into`, specifies block size for data transfer, and uses streams for efficient file upload. The function checks if the source is a ... | def upload(self, source, destination="", *, write_into=False,
block_size=DEFAULT_BLOCK_SIZE):
"""
:py:func:`asyncio.coroutine`
High level upload method for uploading files and directories
recursively from file system.
:param source: source path of file or directo... |
def is_file(self, path):
"""
:py:func:`asyncio.coroutine`
Checks if path is file.
:param path: path to check
:type path: :py:class:`str` or :py:class:`pathlib.PurePosixPath`
:rtype: :py:class:`bool`
"""
info = yield from self.stat(path)
return i... | This method asynchronously downloads files or directories from a server to the local filesystem, recursively handling nested structures. It creates necessary directories, writes files in blocks, and optionally renames files by appending the source name if `write_into` is False. The operation uses coroutines for non-blo... | def download(self, source, destination="", *, write_into=False,
block_size=DEFAULT_BLOCK_SIZE):
"""
:py:func:`asyncio.coroutine`
High level download method for downloading files and directories
recursively and save them to the file system.
:param source: source... |
def args_parser():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--document', help='The ID of the document into which tickets are to be generated', type=str, default=DOC_ID)
parser.add_argument('-t', '--tickets',
help='The filename of the CSV containing the final deli... | The code sets up logging, parses command-line arguments, validates input flags (--tickets or --pickup), reads and processes CSV data, sorts rows, and generates tickets. It ensures only one of --tickets or --pickup is specified, logs errors for invalid cases, and uses logging for debugging. | def main():
logging.basicConfig(level=logging.INFO)
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")
ch = logging.StreamHandler()
# add formatter to ch
ch.setFormatter(formatter)
logging.getLogger('main').setLevel(logging.DEBUG)
# logging.getLogger('make_tickets').setL... |
def choose_clips(self, idx):
"""Choose the second clip and random negative caption
Return indices of each of the clips"""
#########################
# GET FIRST CLIP FUNCTION
clip1_idx = idx
video_ids, clip_ids, narration_pass_list, narration_ind_list, verb_class_list, no... | This method retrieves and processes video clip data for a given index, combining features from multiple clips based on sampling strategies. It generates labels, extracts BERT features, and returns structured tensors including combined features, video IDs, captions, and narration for model training or evaluation. | def __getitem__(self, idx):
clip1_idx, clip2_idx, clip3_idx, clip_bck_idxs, multi_clip_bck_feature_idxs, clip1_feature_idxs, \
clip2_feature_idxs, video_ids, clip1_id, clip2_id, clip3_id, clip_bck_ids, \
num_bck_id_features, num_features_clip_bck = self.choose_clips(idx)
narrati... |
def precision(self):
TP, FP, FN, TN, totalCorrect = self.writePredictions()
precisionValueA = 0
precisionValueB = 0
if TP + FP != 0:
precisionValueA = TP/(TP+FP)
if TN + FN != 0:
precisionValueB = TN/(TN+FN)
return precisionValueA, prec... | This function calculates evaluation metrics (accuracy, precision, recall, F1-score) for a model, then writes them to a text file with four decimal places. It stores two sets of metrics, likely for different classes or tasks, and formats them sequentially in the file. | def writeMetricsToText(self):
precision1, precision2 = self.precision()
recall1, recall2 = self.recall()
f1Measure1, f1Measure2 = self.F1Measure()
with open(self.eval_name, "w") as file:
file.write("{:.4}\n".format(self.accuracy()))
file.write("{:.4} {:.4}\n".for... |
def readTestFile(self, file_name):
f = open(file_name, "r", encoding="utf-8")
reader = csv.reader(f, delimiter="\t")
rows = list(reader) # We don't want the header for the training set
ids = [r[0] for r in rows] # Tweet ids
twt = ... | The code's main task is to evaluate a model on a test dataset by reading the test file, setting trace and evaluation names, generating predictions (calculating TP, FP, FN, TN, and total correct), and writing the computed metrics to a text file for analysis. | def predict(self, test_set, trace_name, eval_name):
self.readTestFile(test_set)
self.trace_name = trace_name
self.eval_name = eval_name
TP, FP, FN, TN, totalCorrect = self.writePredictions()
self.writeMetricsToText() |
def item_query(self, module, storage, block_hash: str = None, force_cache_refresh: bool = False):
# Check if item is cached
is_cached = False
if module in self.cache:
if storage in self.cache[module]:
is_cached = True
try:
if not is_cached or force... | The code estimates the validator payout for the current era by calculating inflation rates, staking ratios, and distributing rewards based on validator performance. It computes total payouts, treasury shares, and individual validator rewards using economic data and reward points, returning either a specific validator's... | def estimate_payout(self, validator_address: str = ""):
# Get current era stake
era = self.item_query("Staking", "ActiveEra")
start = era['start']
era = era['index']
stake = self.map_query("Staking", "ErasTotalStake", era)
stake = helpers.remove_decimals(stake)
#... |
def create_ni2017():
"""
Create the overall score for the 2017 NI ranking
"""
origin = Path(raw_data, "country_indexes", "nimdm2017", "nimdm2017-soa.csv")
destination = Path(
interim_data, "country_indexes", "nimdm2017", "nimdm2017-soa-withoverall.csv"
)
map = {
"D1_Income_ra... | The function `fill_in_scores` addresses missing data in non-English indexes by generating or initializing specific datasets (NI 2017, SIMD 2020, WIMD 2019) to ensure completeness. It likely serves as part of a preprocessing pipeline for statistical or socio-economic analyses where language-specific data gaps need corre... | def fill_in_scores():
"""
Fill in missing data for non-English indexes
"""
create_ni2017()
create_simd2020()
create_wimd2019() |
def index_to_nation_options(index: _allowed_indexes) -> str:
"""
return a string of the allowed nation initials (e..g ESWN)
"""
if index == "uk":
nations = "ESWN"
elif index == "gb":
nations = "ESW"
return nations
def transform_index(
source_nation: str,
dest_nation: str,... | This function transforms and aggregates data from multiple nations into a target nation's index (e.g., England "E") by remapping all nations' data, merging population statistics, calculating population-weighted deciles/quintiles, and exporting the result as a CSV. It adjusts scores, expands deciles, ranks areas, and en... | def transform_all_to(
destination_index: _component_indexes | str = "E", setting: _allowed_indexes = "uk"
):
"""
remap all nations to target nation
"""
nations = index_to_nation_options(setting)
collection = []
col_name = "{s}_IMD_{n}".format(n=destination_index, s=setting).upper()
for ... |
def all_summary_models():
"""
Produce summaries of the distributions of different models
"""
summary_models("uk")
summary_models("gb")
def transform_all():
"""
Create Re-targetted indexes for all items
"""
UK_NATIONS = "NESW"
GB_NATIONS = "ESW"
for nation in UK_NATIONS:
... | The function `produce_indexes_and_analysis` orchestrates a pipeline to generate summary models, transform data, analyze deprivation breakdowns, and compare local/global metrics. It sequentially executes four key tasks: creating summary models, applying transformations, decomposing deprivation data, and contrasting loca... | def produce_indexes_and_analysis():
all_summary_models()
transform_all()
all_deprivation_breakdowns()
compare_both_local_global() |
def _check_mouse_button_down_events(self, event):
"""Respond to mouse button presses."""
self._try_select_defender(event.pos)
def _check_mouse_button_up_events(self, event):
"""Respond to mouse button releases."""
self._try_place_defender(event.pos)
def _check_mouse_motion_events(self, e... | The main task of the code is to process Pygame events, detect user inputs like window closure, mouse clicks, and motion, and delegate specific event handling to dedicated methods. It iterates through events, checks their types, and triggers corresponding actions such as exiting the program or calling methods for mouse ... | def _check_events(self):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
self._check_mouse_button_down_events(event)
elif... |
def _check_events(self):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
self._check_mouse_button_down_events(event)
elif... | The code defines a method `run_game` that starts an infinite loop to manage the game's main operations. It continuously checks for events, updates game elements like arrows, updates the screen display, and maintains a frame rate of 60 FPS using `clock.tick(60)`. The loop ensures real-time interaction, rendering, and sm... | def run_game(self):
"""Start the main loop for the game."""
while True:
self._check_events()
self._update_arrows()
self._update_screen()
self.clock.tick(60) |
def consume():
t = current
advance()
return t
def consume_if(*tt: TokenType):
if match(*tt):
return consume()
return None
def add_diagnostic(type: DiagnosticType, range: SourceRange):
diagnostics.append(Diagnostic(type, range))
def expect_semicolon(range: Sour... | This function parses an import statement by creating an Import node, consumes the 'import' token, checks for a string path, expands the node's range if valid, adds diagnostics if missing the path, expects a semicolon, and returns the constructed Import node with metadata. | def parse_import():
import_tok = consume()
import_node = Node(NodeType.Import, import_tok.to_range())
path_tok = consume_if(TokenType.String)
if path_tok:
import_node.range.expand(path_tok.to_range())
import_node.data.path = path_tok.lexeme
else:
... |
def consume():
t = current
advance()
return t
def consume_if(*tt: TokenType):
if match(*tt):
return consume()
return None
def add_diagnostic(type: DiagnosticType, range: SourceRange):
diagnostics.append(Diagnostic(type, range))
def advance():
nonlocal ... | This function parses a definition or alias, handling colon, assign, or type syntax. It creates a Node (Definition or Alias) with documentation, name, type, and value, validating tokens and adding diagnostics for errors like missing colons. It expands node ranges and expects semicolons, returning the constructed node or... | def parse_definition():
# this could be: constant or variable
doc_str = doc_comment
name_tok = consume()
colon = consume_if(TokenType.Colon)
if not colon:
add_diagnostic(DiagnosticType.DefinitionExpectedColon, name_tok.to_range())
err = Node(NodeType.Erro... |
def parse_import():
import_tok = consume()
import_node = Node(NodeType.Import, import_tok.to_range())
path_tok = consume_if(TokenType.String)
if path_tok:
import_node.range.expand(path_tok.to_range())
import_node.data.path = path_tok.lexeme
else:
... | This function determines the parsing action for global declarations based on the current token type. If the token is an import, it calls parse_import(); if an identifier, it calls parse_definition(); otherwise, it generates an error diagnostic and returns an error node indicating global declarations are not allowed her... | def switch_global():
match current.type:
case TokenType.Import:
return parse_import()
case TokenType.Identifier:
return parse_definition()
case _:
add_diagnostic(DiagnosticType.GlobalNotAllowed, current.to_range())
... |
def match(*tt: TokenType):
return current.type in tt
def switch_global():
match current.type:
case TokenType.Import:
return parse_import()
case TokenType.Identifier:
return parse_definition()
case _:
add_diagnostic(Diagn... | The main task of the code is to parse a module by collecting global elements (like imports/variables) into a Module node, handling syntax errors by skipping invalid tokens, and expanding the module's source range to include all parsed content. | def parse_module():
module_node = Node(NodeType.Module, SourceRange.zero())
while not match(TokenType.EndOfFile):
node = switch_global()
if node.type is NodeType.Error:
# error already reported and advanced
advance_until(TokenType.Identifier, Token... |
def reset_v_pointer(self):
"""Reset vertical movement."""
self.vertical_movement_pointer = -1
def move_pointer(self, steps, strict: bool = False) -> None:
"""Move the pointer forwards a number of steps or into the next match of some pattern."""
if isinstance(steps, (str, re.Pattern)):
... | This function processes buffer navigation actions (left, right, up, down, word) to move a text cursor. It adjusts the pointer position using regex for word jumps and line-based movements, ensuring edge cases like top/bottom boundaries are handled. Vertical movement aligns the cursor to the same relative position on adj... | def handle_buffer_action(self, action: BufferAction):
"""Handle actions."""
if action == BufferAction.LEFT:
# Go backwards one character.
self.reset_v_pointer()
self.move_pointer(-1)
elif action == BufferAction.RIGHT:
# Go forwards one character.
... |
def write_with_callback(self, chars: str) -> None:
"""Write some text, calling the callback on newlines."""
lines = chars.splitlines()
n_lines = len(lines)
for i, line in enumerate(lines):
self.write(max(0, self.pointer - 1), line)
# Avoid writing newline on the... | This function handles text input and editing operations, including sending characters, navigating buffers (left/right/up/down), deleting text, and managing special keys like Tab, Ctrl+V (clipboard paste), and ISO_Left_Tab (text modification). It processes key presses, adjusts the text buffer, and manages pointer moveme... | def send_text(self, key: int, name: str) -> None:
"""Handle sending text and similar modifications to the selected buffer."""
mapping = {"Tab": TAB_CHAR}
char = mapping.get(name, chr(key))
# Handle Ctrl + V
if name == "v":
control_held_down = sc.HELD_DOWN["Control_R"... |
def replace_major_with_broader_major(dataframe):
"""
This function replaces all the specific major names with the broader
major names in a dataframe
Args:
dataframe: A Pandas DataFrame containing a column called "Major" that
has specific names for majors.
Returns:
A Pandas ... | The function generates three CSV files for data visualization: 1) A modified dataset with specific majors replaced by broader categories, 2) State-level aggregated student counts per major, and 3) Nationwide aggregated student counts per major. It processes a DataFrame containing state, major, and student enrollment da... | def create_csvs(dataframe):
"""
This function creates three csvs for further visualization.
1. Contains all data from `combined_data.csv`, replaces major names with
broader categories. Done by calling replace_major_with_broader_major
2. Sums students in each state with certain major. Done by ca... |
def liberties(self, x, y):
scratch = self.scratch_board()
self.flood(scratch, self.board[x][y], x, y)
n = 0
for i in range(5):
for j in range(5):
if self.board[i][j] == 0 and self.group_border(scratch, i, j):
n += 1
return n
def scratch_board(self):
return [[False for _ i... | The main task of the code is to capture opponent stones by checking if a group at position (x,y) has no liberties. If liberties exist, it returns an empty set. Otherwise, it uses a flood fill to identify the connected group, updates the board to mark these stones as captured by the current player, and returns a set of ... | def capture(self, x, y):
"""
Attempt to capture opponent stones.
:return: a set of stone coords captured
"""
if self.liberties(x, y) > 0:
return set()
captured = set()
scratch = self.scratch_board()
self.flood(scratch, self.board[x][y], x, y)
for i in range(5):
for j in ... |
def move_ok(self, move):
"""
Check whether a move is valid based on current board.
:return: a tuple (boolean, integer)
1st element indicates whether move is valid
2nd element indicates the number of liberties
if it is valid and not pass; otherwise it is -1
... | The function `try_move` attempts to execute a given move in a board game (likely Go), validating its legality and updating game state. It checks if the game is over, handles pass moves, verifies move validity, captures stones if applicable, switches players, and returns whether the game continues along with captured co... | def try_move(self, move, debug=False):
"""
Try move based on argument move.
:return: a flag indicates whether game should continue,
and a set of stone coords captured if any
"""
if debug:
print("entering try_move()")
if self.game_status != CONTINUE:
if debug:
pr... |
def _add_log(self, text):
if self.verbose > 0:
self.log_func('[{}] - {}'.format(self.state_round, text))
self.log_counter += 1
def _update_arm_stats(self, arm, rew, col):
self._add_log('Played arm {} - Reward: {} - Collision: {}'.format(
arm, rew, col))
if col... | This code manages a distributed multi-armed bandit algorithm, tracking collisions and rewards across phases (sampling, verification, ranking, exploitation, communication). It identifies player roles, updates optimal arm sets, and coordinates agents through collision detection, leader-follower dynamics, and dynamic arm ... | def update(self, play, obs):
self.total_time += 1
arm = play + 1
rew, col = obs
self.total_collisions += col
if col > 0 and self.phase >= self.EXPLOIT:
self._add_log('Had a collision! Playing {}'.format(arm))
self._update_arm_stats(arm, rew, col)
# If ... |
def setup_dirs():
delete_test_dirs()
create_test_dir()
create_dir_replicate_to()
create_test_file('./testdir/f')
create_log_dir()
def delete_test_dirs():
try:
rm_test_dir()
except FileNotFoundError:
pass
try:
rm_dst_dir()
except FileNotFoundError:
pass... | The main task of the code is to test a file copying functionality by comparing the contents of a source file in './testdir' with its copied version in './dst' after executing the 'walk' function. It sets up test directories, performs the copy operation, verifies file content equality, and cleans up temporary files and ... | def test_walk_basic():
setup_dirs()
walk.walk('./testdir', './dst', './log/log')
f1 = open('./testdir/f')
f2 = open('./dst/f')
assert f1.read() == f2.read()
f1.close()
f2.close()
delete_test_dirs()
rm_log_dir() |
def setup_dirs():
delete_test_dirs()
create_test_dir()
create_dir_replicate_to()
create_test_file('./testdir/f')
create_log_dir()
def delete_test_dirs():
try:
rm_test_dir()
except FileNotFoundError:
pass
try:
rm_dst_dir()
except FileNotFoundError:
pass... | The main task of the code is to test directory creation and replication by copying the structure and file sizes from './testdir' to './dst', verifying consistency with assertions, then cleaning up test directories and logs. | def test_dir_creation():
setup_dirs()
walk.walk('./testdir', './dst', './log/log')
assert os.stat('./testdir/nesteddir1').st_size == os.stat(
'./dst/nesteddir1').st_size
delete_test_dirs()
rm_log_dir() |
def setup_dirs():
delete_test_dirs()
create_test_dir()
create_dir_replicate_to()
create_test_file('./testdir/f')
create_log_dir()
def delete_test_dirs():
try:
rm_test_dir()
except FileNotFoundError:
pass
try:
rm_dst_dir()
except FileNotFoundError:
pass... | The code tests the functionality of the `backwalk` function by setting up a directory structure, performing a walk operation, removing a nested directory, executing `backwalk`, and verifying that the destination directory contains exactly two items, ensuring correct handling of directory operations and cleanup. | def test_backwalk_basic():
setup_dirs()
walk.walk('./testdir', './dst', './log/log')
os.rmdir('./testdir/nesteddir1')
walk.backwalk('./testdir', './dst', './log/log')
assert len(os.listdir('./dst')) == 2
delete_test_dirs()
rm_log_dir() |
def setup_dirs():
delete_test_dirs()
create_test_dir()
create_dir_replicate_to()
create_test_file('./testdir/f')
create_log_dir()
def create_test_file(path):
with open(path, 'w') as f:
f.write(gen_random_string())
def delete_test_dirs():
try:
rm_test_dir()
except FileNotF... | This test verifies that the backwalk function correctly removes files from the destination directory when corresponding source files are deleted. It creates a nested directory structure, copies files using walk.walk, deletes the source file, executes backwalk to synchronize the destination, and checks if the destinatio... | def test_backwalk_nested():
setup_dirs()
create_test_file('./testdir/nesteddir1/f')
walk.walk('./testdir', './dst', './log/log')
os.remove('./testdir/nesteddir1/f')
walk.backwalk('./testdir', './dst', './log/log')
assert len(os.listdir('./dst/nesteddir1')) == 0
delete_test_dirs()
rm_log_... |
def setup_dirs():
delete_test_dirs()
create_test_dir()
create_dir_replicate_to()
create_test_file('./testdir/f')
create_log_dir()
def delete_test_dirs():
try:
rm_test_dir()
except FileNotFoundError:
pass
try:
rm_dst_dir()
except FileNotFoundError:
pass... | This test checks if the 'walk.walk' function correctly raises a SystemExit with code 1 when encountering insufficient permissions on the source directory. It sets up test directories, restricts access to the source directory, invokes walk.walk, verifies the exception type and exit code, then restores permissions and cl... | def test_perms_basic():
with pytest.raises(SystemExit) as e:
setup_dirs()
os.chmod('./testdir', 16384)
r = walk.walk('./testdir', './dst', './log/log')
assert e.type == SystemExit
assert e.value.code == 1
os.chmod('./testdir', 16877)
... |
def setup_dirs():
delete_test_dirs()
create_test_dir()
create_dir_replicate_to()
create_test_file('./testdir/f')
create_log_dir()
def delete_test_dirs():
try:
rm_test_dir()
except FileNotFoundError:
pass
try:
rm_dst_dir()
except FileNotFoundError:
pass... | This test checks if the backwalk function properly exits with code 1 when encountering permission issues. It sets up test directories, restricts access to './testdir', invokes backwalk, verifies SystemExit exception with code 1, then restores permissions and cleans up test artifacts. | def test_perms_backwalk_basic():
with pytest.raises(SystemExit) as e:
setup_dirs()
os.chmod('./testdir', 16384)
r = walk.backwalk('./testdir', './dst', './log/log')
assert e.type == SystemExit
assert e.value.code == 1
os.chmod('./testdir', ... |
def setup_dirs():
delete_test_dirs()
create_test_dir()
create_dir_replicate_to()
create_test_file('./testdir/f')
create_log_dir()
def create_test_file(path):
with open(path, 'w') as f:
f.write(gen_random_string())
def delete_test_dirs():
try:
rm_test_dir()
except FileNotF... | This test checks if the `walk` function correctly exits with code 1 when encountering a file with restricted permissions. It sets up test directories, creates a file with limited permissions (16384), triggers the walk process, verifies the SystemExit exception, resets permissions, and cleans up test artifacts. | def test_walk_perms():
with pytest.raises(SystemExit) as e:
setup_dirs()
create_test_file('./testdir/f')
os.chmod('./testdir/f', 16384)
r = walk.walk('./testdir', './dst', './log/log')
assert e.type == SystemExit
assert e.value.code == 1
... |
def Insertion_sort(arr):
for i in range(1,len(arr)):
key = arr[i]
j=i-1
while j>=0 and key<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
return arr
def bubble_sort(x):
swap = False
for i in range(0,len(x)):
for j in range(0,len(x)):
... | The code compares the performance of five sorting algorithms (Insertion Sort, Bubble Sort, Merge Sort, Selection Sort, and Heap Sort) by measuring the time each takes to sort a randomly generated list of size `sizen`. It returns a list of time durations for each algorithm. The main task is to benchmark and evaluate the... | def Compare_all(sizen):
y = []
data = random.sample(range(1, 1000000),sizen)
start_time = time.time()
res = Insertion_sort(data)
time_taken = time.time() - start_time
y.append(time_taken)
start_time = time.time()
res = bubble_sort(data)
time_taken = time.time() - start_time
y.append(time_taken)... |
def arg_rd(n):
if n not in argv:
raise IOError
return open(n)
def arg_wr(n):
if n not in argv:
raise IOError
return open(n, 'w')
def article_of(notebook_txt, HTMLExporter):
notebook = nbformat.reads(notebook_txt)
hide, meta = artic... | The main task of the code is to convert a Jupyter notebook file into an HTML article by reading the notebook content, processing it with an HTMLExporter (which likely uses Pandoc), and writing the resulting HTML chunks to an output file with specified encoding. | def main(argv, arg_rd, arg_wr, HTMLExporter,
encoding='utf-8'):
'''
.. note:: HTMLExporter includes access to run pandoc etc.
'''
notebook_fn, article_fn = argv[1:3]
notebook_txt = arg_rd(notebook_fn).read()
with arg_wr(article_fn) as outfp:
for chunk in article_of(notebook_tx... |
def fileToBytes(file):
with open(file, "rb") as f:
byteDump = f.read()
return byteDump
def bytesToSequence(byte):
byteList = list(byte)
byteSequence = str(byteList).replace("[", "").replace("]", "").replace(' ', '')
return byteSequence
def encryptText(self, text, key)... | The main task of the code is to encrypt the contents of a specified file using a given key. It checks if the file exists, converts it to bytes, transforms the bytes into a sequence, and then encrypts the sequence with the provided key. If an error occurs during the process, it prints the exception and returns nothing. | def encryptFile(self, file, key):
try:
if path.exists(file):
byteBase = self.fileToBytes(file)
sequenceBase = self.bytesToSequence(byteBase)
return self.encryptText(sequenceBase, key)
return
except Exception as err:
prin... |
def decryptText(self, cipher, key):
return self.crypt(cipher, key, 0)
def sequenceToBytes(sequence):
listOfBytes = sequence.split(',')
return bytes(list(map(int, listOfBytes)))
def bytesToFile(bytes, file):
f = open(file, "wb")
f.write(bytes)
f.close()
return file | This code decrypts a given cipher using a key by first decrypting the text, converting the result to bytes, and then saving it as a file. It handles exceptions by printing errors and returning None if decryption fails. | def decryptFile(self, cipher, key):
try:
if cipher:
sequenceBase = self.decryptText(cipher, key)
byteBase: bytes = self.sequenceToBytes(sequenceBase)
return self.bytesToFile(byteBase)
return
except Exception as err:
prin... |
def set_session():
cookie = getattr(browser_cookie3, "firefox")(domain_name="leetcode.com")
global session
session = requests.Session()
for c in cookie:
if c.name in ("LEETCODE_SESSION", "csrftoken"):
session.cookies.set_cookie(c)
def get_problem_info(problem_number):
query = """... | The main task of the code is to retrieve and process problem information, input, code, and expected output for a given problem number. It fetches data using helper functions, formats the input as a list of strings, and returns a structured dictionary containing the problem's input, code snippet, and expected result for... | def get_problems_infos(n):
set_session()
problem = get_problem_info(n)
input = get_problem_input(problem["titleSlug"])
code = get_code_snippet(problem["titleSlug"])
expected = get_problem_expected(
problem["titleSlug"], "\n".join(input), problem["questionId"], code
)
input = list(ma... |
def gibbs_search(model_list, adj_list, choice_func, num_iter=1000, comp='speaker', prob_var=True, scen_perm=False):
'''
Run gibbs search to find high utility scenarios
:param model_list: list of models to compare in (adj_mat, prag)
:param adj_list: list of adjectives
:param choice_func: function to ... | The code performs listener search using Gibbs sampling to generate and save top scenarios (with utilities, clues, and model choices) from codename-word associations, comparing multiple models. It logs acceptance probabilities, writes scenario details to a file, and stores results in a pickled file for analysis of model... | def run_listener_search(adj_list, word_list, num_iter, model_comp_list, comp_list_str, prob_var, scen_perm=False):
'''
run listener search using gibbs sampling, save scenarios in ../output
:param adj_list: list of all possible adjectives
:param word_list: list of all possible codenames
:param num_it... |
def gibbs_search(model_list, adj_list, choice_func, num_iter=1000, comp='speaker', prob_var=True, scen_perm=False):
'''
Run gibbs search to find high utility scenarios
:param model_list: list of models to compare in (adj_mat, prag)
:param adj_list: list of adjectives
:param choice_func: function to ... | This function performs Gibbs sampling for speaker search to generate and evaluate scenarios based on given models and parameters. It logs acceptance probabilities, saves top scenarios with their utilities, codenames, adjectives, and model-specific probabilities, then stores the results in a pickle file for further anal... | def run_speaker_search(adj_list, word_list, num_iter, model_comp_list, comp_list_str, prob_var, scen_perm=False):
'''
run speaker search using gibbs sampling, save scenarios in ../output
:param adj_list: list of all possible adjectives
:param word_list: list of all possible codenames
:param num_iter... |
def gibbs_search(model_list, adj_list, choice_func, num_iter=1000, comp='speaker', prob_var=True, scen_perm=False):
'''
Run gibbs search to find high utility scenarios
:param model_list: list of models to compare in (adj_mat, prag)
:param adj_list: list of adjectives
:param choice_func: function to ... | The function `run_comb_search` simulates and compares multiple speaker-listener models (pragmatic vs. baseline) over iterations, generating scenarios with codenames and adjectives. It logs acceptance probabilities, scenario utilities, and model-specific choices (e.g., clue probabilities, noun pair preferences) for each... | def run_comb_search(adj_list, word_list, num_iter, model_comp_list, comp_list_str, prob_var, scen_perm=False):
'''
run speaker and listener together, save scenarios in ../output
:param adj_list: list of all possible adjectives
:param word_list: list of all possible codenames
:param num_iter: number ... |
def load_full_set_scen(single_adj=True):
'''
helper function to load semantic 5 noun 8 adj experiment data
:param single_adj: only consider first adjective
:return: (codename listener scenarios, adjective listener scenarios, mturk listener data, mturk listener confidence),
(codename speaker ... | This function performs semantic RSA analysis on model features by comparing listener and speaker scenarios across different experiments (1-3). It loads scenario data, calculates similarity metrics using specified aggregation functions, and saves results in a CSV file. The analysis evaluates model performance by merging... | def run_rsa_analysis(model_feature_list, model_feature_names, csv_keys, word_list, ex=3):
'''
run semantic top match rsa analysis and save results in ../results/temp/
:param model_feature_list: list of (adj_noun_feats, comp_func)
:param model_feature_names: names of input features
:param ex: experim... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.