dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def split_query(terms):
each = preprocess_text(terms)
return each.split()
def intersection(lists):
"""
Performs the intersection operation.
Args:
lists (list): The lists to perform the intersection operation on.
Returns:
list: The result of the intersection operation.
"""
inter... | The function `vertical_search_engine` performs a vertical search on a DataFrame using a query and an index. It splits the query into keywords, retrieves document IDs (SN) from the index, and combines them via intersection (high rank) and union (low rank). Results are merged with the original DataFrame, prioritizing int... | def vertical_search_engine(df, query, index):
"""
Performs vertical search engine.
Args:
df (DataFrame): The DataFrame containing the data.
query (str): The search query.
index (dict): The index dictionary.
Returns:
DataFrame or str: The search result DataFrame or a message if no resul... |
def read_data():
"""
Reads data from the CSV file and returns it as a pandas DataFrame.
Returns:
DataFrame: The data read from the CSV file.
"""
df = pd.read_csv('data.csv').reset_index().rename(columns={'index': 'SN'})
return df
def index_data(df, indexes):
"""
Indexes the data.
... | The main task of the code is to execute a search query by reading data, processing and formatting specific columns (e.g., links and profiles), updating indexes, saving/loading them to/from JSON, and returning a styled DataFrame containing search results with formatted fields for display. | def search_query():
"""
Executes the search query.
Returns:
DataFrame: The search result DataFrame.
"""
global indexes
df = read_data()
single = df.loc[0, :].copy()
indexes = index_data(df, indexes)
save_index_to_json(indexes, 'indexes.json')
indexes = load_index_from_json('... |
def data_setup(df):
#Collect the list of attributes in the dataset
attributes = df.columns.tolist()
#output dict will contain the name of the output attribute as key and the list of values that the attribute takes as values
output = {}
output['play'] = df['play'].values.tolist()
#remove unwanted attributes ... | This function builds a decision tree by recursively selecting the attribute with maximum information gain, partitioning the dataset based on attribute values, and assigning 'Yes'/'No' classifications or further splitting subproblems. It tracks the decision path and constructs the tree structure through recursive calls ... | def build_tree(df,path,attributes):
data = data_setup(df)
input = data[0]
output = data[1]
ig = ig_arr(df)
attr = max(ig,key=lambda x:ig[x])
attr_values = get_unique_attr_values(input,attr)
path.append(attr_values[0])
for each in attr_values[1]:
path.append(each)
flag = check_output(attr,each,in... |
def load_targets(filename = 'example_targets.dat'):
'''
Load a list of candidate host galaxies from the CLU catalogue.
:param filename: a string, the name of the file containing the list of host galaxies
'''
### This probably needs to be improved - it works for the test case but who knows if it'll work ... | This function generates mosaic and schedule files for follow-up observations of a LIGO event. It loads galaxy targets, creates a mosaic file, calculates observation groupings, splits mosaics, selects a calibrator, and outputs a schedule file with target data. Parameters control timing, calibration, and file naming. Tem... | def event_response(event_code, observer='DDobie', time_between_cal = 20*u.min, time_per_gal = 1.5*u.min, calibrator=None, obfuscate=True):
'''
Output mosaics and a schedule file for follow-up of a LIGO event
:param event_code: A string, the event code of the event. Used only for organisation
:param observer:... |
def getStyle():
style = """<style>
/* Style the body */
body {
font-family: Arial;
margin: 0;
}
/* Header/Logo Title */
.header {
padding: 10px;
te... | The function `testdatausage` retrieves parameters from a request, fetches test and test data information from a system using given URLs and IDs, and generates HTML content. It checks if a test exists, validates its type, and conditionally displays test data if available. The HTML includes headers, style elements, and d... | def testdatausage():
entity_ids = request.args.get('entity_ids')
url = request.args.get('octane_url')
shared_space = request.args.get('shared_space')
workspace = request.args.get('workspace')
resource = 'manual_tests/' + entity_ids
# get style
style = getStyle()
divHeader = getDivHeade... |
def deep_copy(matrix_1: list)->list:
"""
Creates a copy of a matrix
Makes a matrix of zeroes. Replaces the zeroes in the matrix with the
corresponding values of another matrix. Returns a matrix.
Args:
matrix_1: A matrix stored as a list of lists.
Returns:
A copy of the... | The code performs QR factorization using Householder reflections. It iteratively applies Householder transformations to reduce the input matrix to upper triangular form (R), while constructing the orthogonal matrix Q by multiplying the conjugate transposes of the generated Householder matrices. The process modifies R t... | def householder(matrix_A: list)->list:
"""
Gives the householder QR factorization
Takes R as a copy of the input matrix. Create an empty set. Call Q_build
to create values to solve for R with matrix multiplication. Append the
values created in Q_build to empty list. Set Q equal to the last ind... |
def get_hamiltonian(n, w, t):
hamiltonian = sp.sparse.lil_matrix((n ** 3, n ** 3))
for i in range(n):
ip1 = (i + 1) % n
for j in range(n):
jp1 = (j + 1) % n
for k in range(n):
kp1 = (k + 1) % n
hamiltonian[i * n * n + j * n + k, i * n * n +... | The function computes the average density of states across 10 randomly selected sites in a quantum system, using a rescaled Hamiltonian matrix. It performs `n_runs` simulations per site, accumulates density results, and returns the site-averaged density vector and the final state vector `x`. The process involves eigenv... | def average_of_densities(n_runs, n, w, t, EPSILON, j):
l = np.random.choice(range(n ** 3), size=10, replace=False)
hamiltonian = get_hamiltonian(n, w, t)
rescaled_hamiltonian = eigen_values(hamiltonian, n, EPSILON)
complete_loop = np.zeros(1000)
for k in l:
y = np.zeros(1000)
alpha_1... |
def get_hamiltonian(n, w, t):
hamiltonian = sp.sparse.lil_matrix((n ** 3, n ** 3))
for i in range(n):
ip1 = (i + 1) % n
for j in range(n):
jp1 = (j + 1) % n
for k in range(n):
kp1 = (k + 1) % n
hamiltonian[i * n * n + j * n + k, i * n * n +... | The code computes the average density of states for 10 specific sites across multiple Hamiltonian realizations. It generates random sites, calculates rescaled Hamiltonians, computes density distributions for each site, and averages results over runs. The output is the mean density and corresponding x-values from the fi... | def average_densities(n_runs, n, w, t, EPSILON, j):
l = np.random.choice(range(n ** 3), size=10, replace=False)
# hamiltonian = get_hamiltonian(n, w, t)
# rescaled_hamiltonian = eigen_values(hamiltonian, n, EPSILON)
average_density_final = np.zeros(1000)
for i in range(n_runs):
hamiltonian =... |
def get_pool(data_queues, args):
size=[14 * 2, 7]
train_queue, _ = data_queues
if not os.path.exists(args.arch_path):
start = time.time()
logging.info('Start sampling architectures...')
sampled_genos, opt_genos, sampled_metrics = {}, {}, {}
new_weights = [... | The code performs neural architecture search (NAS) on CIFAR/Imagenet datasets using Bayesian optimization. It initializes GPU settings, loads and splits datasets, normalizes evaluation metrics (grad_norm, SNIP, etc.), samples candidate architectures, and optimizes them via BayesianOptimization. The goal is to identify ... | def main():
if not torch.cuda.is_available():
logging.info('no gpu device available')
sys.exit(1)
torch.cuda.set_device(args.gpu)
cudnn.benchmark = False
cudnn.deterministic = True
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
... |
def speak(audio_string):
voices = speech_engine.getProperty("voices")
speech_engine.setProperty("voice", voices[1].id)
speech_engine.setProperty("rate", 160)
speech_engine.say(audio_string)
speech_engine.runAndWait()
upload(audio_string, False)
def respond(voice_data):
# Name
if ('what... | This function processes voice commands from a Firebase database. It identifies the most recent input, checks if it contains "add", and either prompts for a to-do list item or adds it directly. If not "add", it responds with the input. It uses recursion to handle the "add" command flow and updates Firebase accordingly. | def website_input(first=True):
myGetResults = fb_db.child('/command').get()
myGetResults = myGetResults.val()
mostrecentKeyID = 0
mostrecentTimestamp = 0
if myGetResults == None:
pass
else:
# To get the most recent input
for keyID in myGetResults:
if int(int... |
def chooser(choiceName, choiceList, player):
print(choiceName)
if len(choiceList) < 1:
print("Nothing to pick")
return -1
i = 1
while True:
for choice in choiceList:
print("{0}: {1}".format(i, choiceList[i - 1]))
i += 1
choice = int(playerInput(len... | This function handles a player's attack phase in a game, allowing them to select weapons, attack a monster, or retreat. It processes attack outcomes, reduces monster health on successful hits, triggers monster counterattacks, and returns "victory" if the monster dies or "retreat" if the player flees. | def getPlayerAttack(self, monster, player):
attackComplete = False
chosenWep = player.getActiveWep()
#player attack loop (I know I'm bad at naming things)
while attackComplete == False:
playerOptions1 = ["Choose Weapon", "Attack Monster", "Retreat"]
choice = int(c... |
def alignment(self, str_x, str_y):
len_x = len(str_x)
len_y = len(str_y)
opt_matrix = np.zeros(shape=(len_x+1, len_y+1)) # characters count from 1
for i in range(len_x+1): # when j == 0
opt_matrix[i][0] = i * self.gap_penalty
for j in range(len_y+1): # when i == 0
... | The main task of the code is to perform sequence alignment using a divide-and-conquer strategy. It splits the target string `str_y` into two halves, computes optimal alignment scores for each half recursively, combines results to find the minimum alignment cost, and records alignment positions. The algorithm recursivel... | def divide_and_conquer_alignment(self, str_x, str_y, offset=(0, 0)):
len_x = len(str_x)
len_y = len(str_y)
mid_col = len_y // 2
# if len_x <= 2 or len_y <= 2:
# # use alignment to solve. to be continued.
# self.res_list.append((offset[0]+len_x)
# retur... |
def extract_img_feat(self, img_data):
img_feat = self.ResNet50Truncated(img_data)
# Resize the features to the image/depth resolution
img_feat = F.interpolate(img_feat, size=(self.crop_size[1], self.crop_size[0]), mode='nearest')
return img_feat
def extract_depth_feat(self, de... | The code processes a sequence of observations by projecting image and depth features onto a ground grid, predicts positions (p_) using rotational feature stacks, and updates a map representation iteratively. It initializes the map, predicts positions for each time step, registers observations using predicted or ground-... | def forward(self, local_info, update_type, input_flags, p_gt=None):
# Runs MapNet for an entire episode
(img_data, points2D, local3D, sseg, depth_data) = local_info
batch_size = img_data.shape[0]
seq_len = img_data.shape[1]
# Extract the img features
with_feat, with_dept... |
def _endless_loop_check(self, changed):
if changed:
self.store_not_change = 0
else:
self.store_not_change += 1
if self.store_not_change > 10:
raise Exception("dead loop")
def _process_stream(self, boxs=None):
if not boxs:
boxs = self._find_... | This function processes incoming byte streams by appending or replacing stored data based on the offset. It checks for loop conditions, updates internal state, and triggers stream processing. If the offset aligns with existing data, it extends the buffer; otherwise, it replaces data and identifies relevant boxes for pr... | def feed(self, bytes_steam, offset=-1):
# no offset or offset continuous, just append
if offset < 0 or self.store_offset + len(self.store_bytes) == offset:
self.store_bytes += bytes_steam
self._endless_loop_check(len(bytes_steam) > 0)
return self._process_stream()
... |
def _prepareBettingRound(self):
# Start of betting round, so set all madeBets to false
for player in self.players:
if not player.folded and not player.allIn:
player.betMade = False
self.pots.finalised = False
def _stillBetting(self) -> bool:
"""
Has ev... | The main task of the code is to manage a betting round in a poker game. It processes player bets sequentially, updates the action index, resets betting parameters (maxBet, lastRaise), and finalizes pots if specified. The loop continues until all active players have acted, ensuring proper betting flow and state preparat... | def bettingRound(self, finalisePots=True):
self._prepareBettingRound()
while self._stillBetting():
if not self.players[self.actionIndex].folded: self.getPlayerBet(self.players[self.actionIndex])
self.actionIndex = nextPlayerIndex(self.actionIndex, self.nplayers, self.pla... |
def wild(self):
"""Allows the current player to change the top card color.
NOTE: this sets the color of the wild card to the players choice to maintain game state.
"""
new_color = self.current_player().choose_color()
self.top_card.color = new_color
def skip(self):
""" Sk... | The main task of the code is to handle actions triggered by special Uno cards (e.g., 'wild', 'skip', 'reverse', 'draw-two', 'wild-draw-four') by invoking corresponding methods. It checks the card's 'special' attribute, executes the appropriate game logic, and raises an error for unrecognized card types, ensuring proper... | def special_card_action(self, card):
""" Deals with a special card's action
Args:
card (Card): they special card that was played
"""
if card.special == 'wild':
self.wild()
elif card.special == 'skip':
self.skip()
elif card.special == '... |
def current_player(self):
"""Returns the current Player object.
"""
return self.players[self.current_player_index]
def valid_card_choice(self, card_choice):
""" Check to see if the card is playable given the top card
Args:
card_choice (Card): a potentially playable C... | The function `play_turn` handles a single round of Uno by allowing the current player to select and validate a card, updating the game state, triggering special card effects, managing card draws for invalid plays, and checking if the player has won by depleting their hand. | def play_turn(self):
""" Plays one round of uno
Returns:
(bool) whether the game has been won by the current player
"""
player = self.current_player()
self.view.show_beginning_turn(player, self.top_card)
if type(player) == HumanPlayer:
card = pla... |
def sigmoid(z):
return 1/(1 + np.exp(-z))
def sigmoid_prime(z):
return sigmoid(z)*(1 - sigmoid(z))
def evaluate(self, test_data):
'''Return the percentage representing how much of the test data was correctly computed.'''
return (sum(np.rint(self.feedforward(x)) == y for x, y in test_data)/len(te... | The main task of the code is to train a neural network using backpropagation. It iterates over epochs, computes gradients via forward and backward passes, accumulates weight/bias updates, and adjusts parameters using the learning rate. Optional testing evaluates performance per epoch. | def backprop(self, training_data, epochs, lr, test_data = None):
'''Train the neural network with a given training data set, number of epochs, and learning rate.
A testing data set can be given to evaluate the network's performance at the end of each epoch.'''
for epoch in range(epochs):
... |
def hash_pubkey(self):
public_key = self.load_public_key()
hash_object = RIPEMD160.new(public_key.encode("utf-8"))
hash_public_key = hash_object.hexdigest()
return hash_public_key
def load_public_key(self):
route_public_key = "public_keys/" + str(self.socket.getsockname()[1]) + ... | The code handles user input to create and send blockchain transactions. It lists unspent transactions, lets users select a transaction, signs it with a private key, and sends the serialized transaction to a server. If no unspent transactions exist, it prevents sending. Other commands like showing addresses or creating ... | def send_message(self):
while True:
input_command = input()
# This variable is set to True when is a server command
send_message_to_server = True
if input_command.startswith("cmd_new_tx"):
# Show available transactions
block_numb... |
def drawButtons():
#draws out the game buttons
pygame.draw.rect(DISPLAY, YELLOW, YELLOWRECT)
pygame.draw.rect(DISPLAY, GREEN, GREENRECT)
pygame.draw.rect(DISPLAY, BLUE, BLUERECT)
pygame.draw.rect(DISPLAY, RED, REDRECT)
def checkForQuit():
for event in pygame.event.get(QUIT): # get all the QUIT e... | The code implements a Simon memory game where the player must replicate a sequence of colored buttons. It initializes Pygame, loads sounds, and manages a game loop that generates random patterns, flashes them, and checks player input against the sequence. Correct matches increase the score, while errors trigger a game ... | def main():
global DISPLAY, YELLOWSOUND, GREENSOUND, BLUESOUND, REDSOUND
pygame.init()
DISPLAY = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
#sound played with every BRIGHT color
YELLOWSOUND = pygame.mixer.Sound("beep1.ogg")
GREENSOUND = pygame.mixer.Sound("beep2.ogg... |
def _resolve_dependency_callbacks(self):
"""jobs may depend on functions that return their actual dependencies.
This resolves them
"""
# we need this copy,
# for the callbacks may create jobs
# so we can't simply iterate over the jobs.values()
with_callback = [j f... | The main task of this code is to execute a directed acyclic graph (DAG) of jobs, managing dependencies, logging, error handling, and result tracking. It validates the DAG structure, initializes logging and directories, runs jobs via a Runner, processes outcomes, handles failures, and returns a dictionary of job results... | def _run(
self,
print_failures: bool = True,
raise_on_job_error=True,
event_timeout=5,
focus_on_these_jobs=None,
dump_graphml=False,
) -> Dict[str, JobOutcome]:
"""Run the jobgraph - possibly focusing on a subset of jobs (ie. ignoring
anything that's n... |
def __setup_gui_window(self):
self.__gui.configure(background="cyan")
self.__gui.title("Simple Calculator")
self.__gui.geometry("290x130")
def __setup_expression_field(self):
expression_field = Entry(self.__gui, textvariable=self.__equation)
expression_field.grid(columnspan=5, ip... | The main task of the code is to initialize and launch a GUI application. It sets up the main window, creates an expression input field, attaches functional buttons, and starts the GUI event loop via `mainloop()` to make the interface interactive and visible to the user. | def start(self):
self.__setup_gui_window()
self.__setup_expression_field()
self.__create_and_attach_buttons()
# start the GUI
self.__gui.mainloop() |
def _get_observation(self):
if self.re_calculate:
designed_info = self.text_obs_dict_to_gym_status_dict(self.initial_text_obs_dict)
current_info = self.text_obs_dict_to_gym_status_dict(self.current_text_obs_dict)
if self.data_augmentation:
if self.gym_moves_2_... | The main task of the code is to reset the environment's state for a new episode in a reinforcement learning setup. It increments episode counters, manages expert sampling strategies, initializes/reverts topology configurations, and prepares initial observations. Key steps include resetting step/reward counters, handlin... | def reset(self):
self.gym_episodes += 1
i_replay = self.gym_episodes % self.num_replay
self.expert_sampling = self.expert_sampling_list[i_replay]
self.used_actions = []
self.true_steps = 0 # count all steps
self.steps = 0 # ignore steps for "move"
self.substep =... |
def action_to_command_index(self, action):
i = -1
if self.substep == 0:
i = action - (self.len_ip_addresses_simple+1 + self.len_port_commands_list+self.len_routing_commands_list)
elif self.substep == 1:
if action == 0:
i = 0
elif action > self.... | The code simulates a network troubleshooting environment where an agent takes actions to diagnose and fix faults. It processes device positions, checks/configures network features, calculates rewards (positive for correct actions, negative otherwise), tracks steps, and updates the environment state. The function return... | def step(self, action):
self.reward_multiplier = 1 # disabled it by forcing it to 1, remove this line to re-enable it
#
y = self.gym_position_info[1]
sub_pos = self.gym_position_info[10]
if y != self.num_devices: # not routing features
if sub_pos == 0:
... |
def mkdir(dirpath, force = False):
if path.exists(dirpath):
if force:
delete(dirpath)
else:
return
os.makedirs(dirpath)
def delete(delpath):
"""
Deletes the given file, link, or directory and silently fails if nothing exists.
Returns the path info as well
"""
pinfo = pathinfo(delpath)
if pinfo == PATH... | This function transpiles JavaScript by running npm scripts to build or watch TypeScript files. It creates a directory, deletes existing JS files, executes 'npm run build-ts' or 'npm run watch-ts' based on the 'watch' flag, checks the command's exit status, and exits with an error if transpilation fails. | def js(watch=False):
print("Transpiling JS")
mkdir("html/js/")
delete("html/js/gochan.js")
delete("html/js/gochan.js.map")
npm_cmd = "npm --prefix frontend/ run"
if watch:
npm_cmd += " watch-ts"
else:
npm_cmd += " build-ts"
status = run_cmd(npm_cmd, True, True, True)[1]
if status != 0:
print("JS transpi... |
def mkdir(dirpath, force = False):
if path.exists(dirpath):
if force:
delete(dirpath)
else:
return
os.makedirs(dirpath)
def symlink(target, link):
"""Create symbolic link at `link` that points to `target`"""
targetinfo = pathinfo(target)
linkinfo = pathinfo(link)
if target == PATH_NOTHING:
raise FileN... | The code installs the gochan application by copying or creating symbolic links for its components (JavaScript, CSS, templates) and executables to specified directories. It checks the OS, handles installation flags, creates necessary directories, copies files, builds if needed, and provides post-installation instruction... | def install(prefix="/usr", document_root="/srv/gochan", symlinks=False, js_only=False, css_only=False, templates_only=False):
if gcos == "windows":
print("Installation is not currently supported for Windows, use the respective directory created by running `python build.py release`")
sys.exit(1)
mkdir(document_roo... |
def set_vars(goos=""):
""" Sets GOOS-related variables to be used globally"""
global gcos
global gcos_name # used for release, since macOS GOOS is "darwin"
global exe
global gochan_bin
global gochan_exe
global migration_bin
global migration_exe
if goos != "":
os.environ["GOOS"] = goos
gcos, gcos_status =... | The code creates a release package for a GoChan application by copying specified files and directories into a structured release directory, then archiving them as a zip or gztar file based on the OS. It deletes existing releases, organizes files into 'html' and 'sql' subdirectories, and ensures proper file paths for cr... | def release(goos):
set_vars(goos)
build(False)
release_name = gochan_bin + "-v" + GOCHAN_VERSION + "_" + gcos_name
release_dir = path.join("releases", release_name)
delete(release_dir)
print("Creating release for", gcos_name, "\n")
mkdir(path.join(release_dir, "html"))
mkdir(path.join(release_dir, "sql"))
fo... |
def default_name(self) -> str:
raise NotImplementedError()
def setup_resume(
self,
eid:int,
out:Optional[str] = None,
data:str = 'data',
gpu:bool = True,
checkpoint:int = 25) -> _Setup:
out, db = self._setup_out(out)
resume ... | This function parses command-line arguments to configure experiment setup. It handles GPU usage, output/data paths, cross-validation parameters, and hyperparameter overrides. If resuming an experiment, it calls `setup_resume`; otherwise, it merges default parameters with CLI overrides and invokes `setup_new` for a fres... | def _setup_from_args(self) -> _Setup:
parser = argparse.ArgumentParser()
parser.add_argument(
'--no_gpu', dest='gpu', action='store_false',
help='Do NOT use GPU if available')
parser.add_argument(
'-o', '--out', default=os.path.join('results', self.default_nam... |
def get_scone(self, proxy):
proxy = self.communicator().stringToProxy(proxy)
sconePrx = Semantic.SconeServicePrx.checkedCast(proxy)
if not sconePrx:
raise RuntimeError('Invalid proxy')
return sconePrx
def get_wiring_service(self, proxy):
proxy = self.communicator().st... | The code's main task is to initialize components `scone` and `wiring_service` using input arguments, execute a "compose" action with the command "open door," and print "Done." It processes arguments, configures system components, and triggers a predefined operation sequence. | def run(self, args):
self.scone = self.get_scone(args[1])
self.wiring_service = self.get_wiring_service(args[2])
self.compose("open door")
print("Done.") |
def _customize_compiler_flags(self):
"""Modify standard compiler flags."""
try:
# -Wstrict-prototypes is not a valid option for c++
self.compiler.compiler_so.remove("-Wstrict-prototypes")
if NGRAPH_PYTHON_DEBUG in ["TRUE", "ON", True]:
# pybind11 is mu... | This method customizes compiler and linker flags for building extensions based on the platform (Windows/Unix/darwin) and build type (debug/release). It adds C++ flags, platform-specific settings, and libc++ support for macOS, then invokes the base class's build_extensions method to compile the extensions with these con... | def build_extensions(self):
"""Build extension providing extra compiler flags."""
self._customize_compiler_flags()
for ext in self.extensions:
ext.extra_compile_args += [cpp_flag(self.compiler)]
if sys.platform == "win32":
self._add_win_compiler_flags(ext... |
def polygonal_number(s, limit):
return get_ns_less_than(lambda x: (x**_sage_const_2 * (s - _sage_const_2 ) - x*(s - _sage_const_4 )) / _sage_const_2 , limit)
def build_p61_cyclic_lists(ns, length=_sage_const_0 , verbose=_sage_const_0 ):
nsstr = map(str, ns)
res = map(lambda x: [x], nsstr)
for l in xran... | The code generates cyclic polygonal number sequences of a given length, filters them to ensure distinctness across specified parameters, and returns the unique, sorted results as tuples. | def p61(length):
all_polygonals = set(combine_lists(map(lambda i: filter(lambda x: x >= _sage_const_1000 , polygonal_number(i, _sage_const_10000 )), (ellipsis_range(_sage_const_3 ,Ellipsis,length + _sage_const_2 )))))
res = build_p61_cyclic_lists(all_polygonals, length, verbose=_sage_const_1 )
distinct = f... |
def load_url_html_to_soup(self, session, request: RequestInfo):
try:
response = session.get(request.url, timeout=request.timeout)
if response.status_code == 200:
soup = BeautifulSoup(response.content, "html.parser")
return soup
# TODO: create c... | This method loads a webpage using a session, parses its HTML with BeautifulSoup, generates metadata, extracts and saves various assets (images, styles, scripts, links) from the HTML, and writes the processed HTML content to a file named after the request. | def load_url(self, request: RequestInfo, show_metadata, metadata):
s = requests.Session()
soup = self.load_url_html_to_soup(s, request)
self.create_metadata(request.base_url, soup, show_metadata, metadata)
# save assets...not perfect
self.save_assets(soup, request.file_name + "_a... |
def edit_config():
if not os.path.exists(CONFIG_PATH):
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
with open(CONFIG_PATH, "w") as fp:
fp.write(CONFIG_TEMPLATE)
click.edit(filename=CONFIG_PATH)
def load_config():
global OPENAI_SECRET
global OPENAI_MODEL
if no... | The function processes user inputs for an AI interaction, validating parameters (edit flag, history count), loading configurations, sanitizing input, and invoking an OpenAI model with adjusted inputs and history. It handles errors, exits on invalid inputs, and returns processed results. | def v4(edit, history, inputs):
if edit is True:
return edit_config()
if history < 0:
click.echo("history must be positive")
exit(2)
if inputs is None:
click.echo(v4.get_help(click.Context(v4)))
exit(1)
load_config()
inputs = inputs.strip()
if not in... |
def make_game_board(size=size):
# Make an empty board
board=[[empty]*size for i in range(size)]
# Even Columns
for i in range(0,size,2):
board[1][i]=player_1
board[-1][i]=player_2
board[-3][i]=player_2
# Odd Columns
for i in range(1,size,2):
board[0]... | The main task of the code is to run a checkers game by creating a board, alternating turns between two players, allowing each player to make moves, checking if the game has been won, and displaying the final result including the winner and remaining pieces. The loop continues until a player wins, with the game tracking... | def checkers_game():
print ("Welcome to Checkers.")
print ("--------------------")
# Make a game board
board_0=make_game_board()
# Start with player 1
player=player_1
this_game_won=False
while not this_game_won:
# Draw the board
draw_board(board_0)
... |
def get_winner(red_moves: Iterable[Tuple[int, int]], blue_moves: Iterable[Tuple[int, int]], last_move: Tuple[int, int],
size: int) -> Optional[int]:
if last_move in red_moves and check_basic_win_condition_for_red_player(red_moves, size):
if (check_if_connects_to_nth_row(last_move, red_moves, ... | This function implements the negamax algorithm with alpha-beta pruning for the game of Hex, evaluating optimal moves by recursively exploring game states. It calculates the best score and corresponding move for the current player, considering available positions and pruning branches to improve efficiency. The score is ... | def negamax_alpha_beta_pruned(
player: int,
red_moves: Iterable[str],
blue_moves: Iterable[str],
last_move: str,
alpha: float,
beta: float,
size: int
) -> Dict[str, int]: # yapf: disable
"""
Simple implementation of the negamax (minimax) algorithm for the game of hex. Includes an im... |
def get_winner(red_moves: Iterable[Tuple[int, int]], blue_moves: Iterable[Tuple[int, int]], last_move: Tuple[int, int],
size: int) -> Optional[int]:
if last_move in red_moves and check_basic_win_condition_for_red_player(red_moves, size):
if (check_if_connects_to_nth_row(last_move, red_moves, ... | This function implements the negamax algorithm with alpha-beta pruning and transposition tables for the game of Hex. It evaluates all possible moves recursively, using transposition tables to store and reuse results for efficiency, and alpha-beta pruning to reduce computation. The function returns the best move and sco... | def negamax_alpha_beta_pruned_with_transposition_tables(
player: int,
red_moves: Iterable[Tuple[int, int]],
blue_moves: Iterable[Tuple[int, int]],
last_move: Tuple[int, int],
alpha: float,
beta: float,
size: int
) -> Dict[str, int]: # yapf: disable
"""
Simple implementation of the n... |
def init_hidden(self, bsz):
weight = next(self.parameters())
return (weight.new_zeros(self.num_layers, bsz, self.rnn_size),
weight.new_zeros(self.num_layers, bsz, self.rnn_size))
def _prepare_feature(self, fc_feats, att_feats, att_masks):
att_feats, att_masks = self.clip_att(att_... | This function generates sequence outputs using attention mechanisms and scheduled sampling. It initializes hidden states, prepares features, iteratively computes log probabilities for each token in the sequence, and applies stochastic sampling during training to improve generalization. The output tensor contains predic... | def _forward(self, fc_feats, att_feats, seq, att_masks=None):
batch_size = fc_feats.size(0)
state = self.init_hidden(batch_size)
outputs = fc_feats.new_zeros(batch_size, seq.size(1) - 1, self.vocab_size+1)
# Prepare the features
p_fc_feats, p_att_feats, pp_att_feats, p_att_mask... |
def _prepare_feature(self, fc_feats, att_feats, att_masks):
att_feats, att_masks = self.clip_att(att_feats, att_masks)
# embed fc and att feats
fc_feats = self.fc_embed(fc_feats)
att_feats = pack_wrapper(self.att_embed, att_feats, att_masks)
# Project the attention feats first ... | The code implements a beam search algorithm to generate sequences (e.g., captions) from input features. It processes each image independently, expanding features to match the beam size, initializes hidden states, and iteratively computes log probabilities for token predictions. Beam search explores top candidate sequen... | def _sample_beam(self, fc_feats, att_feats, att_masks=None, opt={}):
beam_size = opt.get('beam_size', 10)
batch_size = fc_feats.size(0)
p_fc_feats, p_att_feats, pp_att_feats, p_att_masks = self._prepare_feature(fc_feats, att_feats, att_masks)
assert beam_size <= self.vocab_size + 1, 'l... |
def _sample_beam(self, fc_feats, att_feats, att_masks=None, opt={}):
beam_size = opt.get('beam_size', 10)
batch_size = fc_feats.size(0)
p_fc_feats, p_att_feats, pp_att_feats, p_att_masks = self._prepare_feature(fc_feats, att_feats, att_masks)
assert beam_size <= self.vocab_size + 1, 'l... | This function generates sequences using a model with features and attention, applying constraints like trigram blocking and decoding rules. It uses greedy sampling or beam search based on parameters, handling features, states, and log probabilities to produce output sequences with controlled generation. | def _sample(self, fc_feats, att_feats, att_masks=None, opt={}):
sample_method = opt.get('sample_method', 'greedy')
beam_size = opt.get('beam_size', 1)
temperature = opt.get('temperature', 1.0)
decoding_constraint = opt.get('decoding_constraint', 0)
block_trigrams = opt.get('bloc... |
def _create_audio(self, text):
try:
if len(text) > 7000:
f = open("tmp/audio_files/tmp.txt", "w")
f.write(text)
f.close()
os.system(f"balcon -w tmp/audio_files/tmp.wav -n \"{self.voice}\" -f \"tmp/audio_files/tmp.txt\" -v {self.voice_vo... | The main task of the code is to generate a video by concatenating image files with synthesized audio, overlaying music, and exporting the result. It creates an FFmpeg script (`script.ffconcat`) to sequence images, generates audio segments (including silence, processed data, TV sound, and an outro), combines them with m... | def create_video(self, file_path, ID):
concat = open("script.ffconcat", "w")
concat.write("ffconcat version 1.0\n")
audio = self._create_audio("r slash ask reddit by Rbotainment")
audio += self.silence
concat.write(f"file resources/images/outro.png\nduration {round(len(audio) / 1... |
def _explicit_selector(self, method, logic): # selects element while waiting until it appears
return WebDriverWait(self.driver, self.delay).until(EC.presence_of_element_located((method, logic)))
def _screenshot(self, element, path):
location = element.location_once_scrolled_into_view
if location... | The code's main task is to take a screenshot of a web element identified by a dynamic ID. If the element isn't found, it locates a "moreComments" element, triggers its click via JavaScript, scrolls the page, and recursively retries the screenshot. The process includes error handling and a 0.5-second delay to ensure pro... | def screenshot_comment(self, ID, path):
try:
elem = self._explicit_selector(By.ID, f"t1_{ID}")
self._screenshot(elem, path + ".png")
except (NoSuchElementException, TimeoutException) as e:
more_comments_path = "//div[starts-with(@id,'moreComments') and @style='padding... |
def check_if_commons(commonfile, exact = True):
filepath = "/".join(os.path.realpath(__file__).split("/")[:-2]) \
+ "/common_files/*"
commons = glob.glob(filepath)
for file_full in commons:
file_name = file_full.split("/")[-1]
if exact:
if commonfile == fi... | The main task of the code is to build a transcription factor (TF) matrix by downloading a MEME motif database and genome data, then using the FIMO tool to identify motif occurrences in genomic regions specified by a BED file. The function returns the resulting TF matrix file path after logging key inputs and outputs. | def build_tf_matrix(bed,
meme_db,
memedb,
orgname,
gvers,
logger,
vector = None):
correction = check_if_commons(meme_db, False)
meme_file = download_meme(meme_db, memedb)
genome ... |
def getTcp(s, TCPString, isFlt=True, isInt=False, asIs=False):
s.send(TCPString.encode("utf-8"))
retStr = TCPBlockingReceive(s)
if asIs:
# print('is asIs = ', TCPString, retStr)
return retStr
elif isInt:
if is_number(retStr):
return int(retStr)
else:
... | The main task of the code is to update module information by retrieving and storing module names, mnemonics, and operational limits from a connected device via TCP communication. It first checks device connectivity, fetches the number of modules, then iterates through each module to collect valid data (excluding disabl... | def updateModules(self):
if not self.Leem2000Connected:
print("Please connect first")
return None
else:
# Get list of devices
self.nModules = getTcp(self.s, "nrm", False, True, False)
# Get list of devices
self.Modules = {}
... |
def getTcp(s, TCPString, isFlt=True, isInt=False, asIs=False):
s.send(TCPString.encode("utf-8"))
retStr = TCPBlockingReceive(s)
if asIs:
# print('is asIs = ', TCPString, retStr)
return retStr
elif isInt:
if is_number(retStr):
return int(retStr)
else:
... | The main task of the code is to establish a TCP connection to a Leem2000 device using the specified IP and port, initialize string communication, retrieve device module lists, and update device values. It ensures no duplicate connections by raising an exception if already connected, then provides user guidance on inter... | def connect(self):
if self.Leem2000Connected:
raise Exception("Already connected")
# print('Already connected ... exit "connect" method')
# return
else:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("connecting leem with")
... |
def load_npy(npypath):
return np.load(npypath)
def load_vocabulary(dataset, type):
Vcb_path = './Vocabulary/cross_data/train.'+type+'.pkl'
pkl = open(Vcb_path, 'rb')
vocabulary = pickle.load(pkl)
return vocabulary
def load_data(path):
with open(path, 'r') as f:
lines = f.read().split('\n... | The main task of the code is to generate ensemble summaries by combining outputs from three approaches ("crossrencos", "crossdeep", "crossnmt") using weighted parameters (alpha, lambda_f). It processes code and summary data, computes cosine similarity between test and training code, loads generated summaries, transform... | def EnsGen(dataset, alpha, lambda_f):
print("Dataset: %s alpha: %0.2f lambda: %0.2f" % (dataset, alpha, lambda_f))
approaches = ["crossrencos", "crossdeep", "crossnmt"]
train_code_path = "./" + dataset + "/" + "train.txt.src"
train_sum_path = "./" + dataset + "/" + "train.txt.tgt"
test_code_path =... |
def load_npy(npypath):
return np.load(npypath)
def load_vocabulary(dataset, type):
Vcb_path = './Vocabulary/cross_data/train.'+type+'.pkl'
pkl = open(Vcb_path, 'rb')
vocabulary = pickle.load(pkl)
return vocabulary
def load_data(path):
with open(path, 'r') as f:
lines = f.read().split('\n... | The code trains a model to optimize thresholds for combining three code summarization approaches (crossrencos, crossdeep, crossnmt) using differential evolution. It loads datasets, computes cosine similarity between code snippets, transforms generated summaries into vectors, extracts non-zero elements, and evolves thre... | def Ensum_train(dataset):
print("Dataset: %s " % (dataset))
#The three code summarization approaches
approaches = ["crossrencos", "crossdeep", "crossnmt"]
train_code_path = "./" + dataset + "/" + "train.txt.src"
train_sum_path = "./" + dataset + "/" + "train.txt.tgt"
valid_code_path = "./" + dat... |
def Find(self, parent, i):
if parent[i] == i:
return i
return self.Find(parent, parent[i])
def Union(self, parent, rank, x, y):
xRoot = self.Find(parent,x)
yRoot = self.Find(parent, y)
if rank[xRoot] < rank[yRoot]:
parent[xRoot] = yRoot
elif rank[... | The code implements Kruskal's algorithm to find a Minimum Spanning Tree (MST). It sorts edges by weight, uses Union-Find to detect cycles, and adds edges to the MST if they connect disjoint sets. The process continues until the MST contains all vertices, ensuring minimal total weight. | def KruskalMST(self):
result = []
i = 0 # An index variable, used for sorted edges
e = 0 # An index variable, used for result[]
# Step 1: Sort all the edges in
# non-decreasing order of their
# weight. If we are not allowed to chan... |
def forwardPass(self, data: np.ndarray) -> (np.ndarray, list):
result_a = data
result_sets = [result_a]
for weights, bias in zip(self._weight_sets, self._bias_sets):
result = np.dot(weights, result_a)
result += np.reshape(bias, (10, 1))
result_a = self._acti... | This code trains a neural network using backpropagation. It iterates through training data, computes forward and backward passes to adjust weights and biases, updates the network, and monitors accuracy. Training stops early if the convergence accuracy threshold is met, optimizing model performance while limiting unnece... | def train(self, train_data, label_data, iterations, convergence, learning_rate):
for i in range(iterations):
result, layer_values = self.forwardPass(train_data)
loss = lossFunction(result, label_data)
weight_corrections, bias_corrections = self.backPropagation(loss, layer_v... |
def convertToListCoords(self, x, y):
return int(x//(16*3)-1), int(y//(16*3)-4)
def findHScore(self, coord):
x, y = coord[0], coord[1]
return abs(x-self.end[0]) + abs(y-self.end[1])
def findPath(self):
currentNode = self.findMinFScore()
if currentNode.node == self.end:
... | This code implements a pathfinding algorithm (likely A*) to generate a route from a starting position (startY, startX) to a target location on a grid. It initializes nodes for all grid cells, calculates heuristic scores, and explores unvisited nodes to find the optimal path. If a path is found, it reconstructs it by ba... | def generatePath(self, target, startY, startX):
self.target = target #targets a counter with food on it
self.targetX, self.targetY = self.convertToListCoords(target.x0, target.y0)
self.start = (startY, startX)
self.end = (self.targetY, self.targetX)
# print('target', self.targetY... |
def get_game_word():
words_list = []
with open(DATA_WORDS_FILE_ROUTE, "r", encoding="utf-8") as words_file:
words_list = [word for word in words_file]
assert len(words_list) > 0, "Game file is empty"
return words_list[random.randint(0, len(words_list) - 1)].upper()
def is_above_50_percent_li... | The code implements a hangman game where the player guesses letters to reveal a hidden word. It tracks remaining attempts, adjusts game status (e.g., "scared" when attempts drop below 50% of initial), updates the displayed word with correct guesses, and determines win/loss outcomes. Points are calculated and awarded if... | def play_game(user_info):
word_game = get_game_word()
word_game = re.sub("\\n", "", word_game)
initial_round_retries = len(word_game) + GAME_BASE_RETRIES
round_retries = initial_round_retries
player_word = "".join(["_"] * len(word_game))
round_status = "initial"
while player_word.__contains... |
def start_game(user_info):
keep_playing = True
while keep_playing:
play_game(user_info)
keep_playing = int(input("""
Enter '1' to play again.
If you want to go back at menu enter anything.
"""))
def look_the_the_scoreboard():
users_scoreboard = refresh_score_board()
print_cus... | The code presents a game menu allowing users to play Hangman, view the scoreboard, check their position, or exit. It uses a loop to handle choices, invokes corresponding functions via lambda operations, and manages invalid inputs with exception handling. | def game_menu(user_info):
MENU = """
What do yo want to do?
1. Play
2. Look the scoreboard
3. Look your actual position in scoreboard
4. exit
Enter the numeric code of your choice:
"""
active_session = True
operations = [
lambda x: start_game(x),
lambda x: look_the_the_scoreboard(... |
def gmail_authenticate():
creds = None
# the file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first time
if os.path.exists("token.pickle"):
with open("token.pickle", "rb") as token:
creds = pic... | The code's main task is to authenticate with the Gmail API, search for emails matching a query, retrieve their content (plain text, HTML), and save attachments. It processes each matched email by printing results, extracting data, and storing HTML/attachments locally. | def main():
# get the Gmail API service
service = gmail_authenticate()
# get emails that match the query you specify
results = search_messages(service, "query")
print(f"Found {len(results)} results.")
# for each email matched, read it (output plain/text to console & save HTML and attachments)
... |
def getImagesInFolder(absolutePath, forName):
assert isinstance(absolutePath, str)
assert isinstance(forName, str)
image_names = [renameImageUUID(absolutePath, img, forName) for img in os.listdir(absolutePath) if img.endswith(".jpg") or img.endswith(".jpeg") or img.endswith(".png")]
images = [TrainingIm... | The main task of the code is to process a set of images by checking if they have been modified since the last run using hashing. If unmodified, it retrieves previous data to avoid redundant processing. If modified, it creates a video from the images, runs mediapipe analysis on it, and returns the results while updating... | def photoToJSON(absolutePath, word, mediapipeDirectory):
ALL_IMAGES = getImagesInFolder(absolutePath, word) # collects all images in the absolute path and renames them if they are new to take on an UUID4-based name
savedHash = Hash.getSavedHash(absolutePath, word)
print("Saved hash: {} vs generated hash: ... |
def sudoActivator():
stream = os.popen("sudo echo 'Sudo mode activated'")
output = stream.read()
return True
def getMediapipeDirectory():
MEDIAPIPE_DIRECTORY = None
while MEDIAPIPE_DIRECTORY is None or not os.path.isdir(MEDIAPIPE_DIRECTORY):
if MEDIAPIPE_DIRECTORY:
print("Invalid... | The code processes each subdirectory in the current working directory by converting photos to JSON using MediaPipe, collects results in a dictionary, and saves them to a JSON file. It prompts the user for the MediaPipe directory, iterates through subfolders (excluding __pycache__), and executes photoToJSON for each, st... | def main():
global SCRIPT_PATH
sudoActivator()
pathname = os.path.dirname(sys.argv[0])
SCRIPT_PATH = os.path.abspath(pathname)
MEDIAPIPE_DIRECTORY = getMediapipeDirectory() # prompts user for mediapipe directory
CURRENT_PATH = os.getcwd()
RESULTS = {}
for file in os.listdir(CURREN... |
def load_datasets(train_dataset_params: Union[dict, DataParams],
validation_dataset_params: Union[dict, DataParams]):
# load PyTorch ``Dataset`` objects for the train & validation sets
train_dataset = TwitterDataset(**train_dataset_params)
validation_dataset = TwitterDataset(**validation_d... | This function trains a tagging model with configurable parameters, supporting hyperparameter tuning and Comet experiment tracking. It loads datasets, initializes the model/optimizer, and executes training with/without tuning, handling device placement, checkpointing, and logging. | def train_tagger(config: Union[dict, TaggingParams],
tuning: bool = False,
checkpoint=True,
serialization_dir: str = None,
checkpoint_dir: str =None,
root_dir: str = None,
usecomet: bool = False,
silen... |
def formDataframe(userAgent, timestamp, userID, location):
browser, os_version, device = extractAgentData(userAgent)
country = getCountryFromIP(location)
login_time = getLoginTime(timestamp)
data = {
'user_id': [userID],
'timestamp': [timestamp],
'login_time': [login_time],
... | The main task of the code is to calculate an anomaly risk score for a user by processing incoming POST data, combining it with historical user data, encoding features, and applying either supervised or unsupervised learning models. The function returns the computed risk score in a JSON response, handling errors like mi... | def getAnomalyScore():
if request.method == 'POST':
incoming_data = request.get_json()
userAgent = incoming_data['userAgent']
timestamp = incoming_data['timestamp']
userID = incoming_data['userID']
location = incoming_data['location']
df = formDataframe(userAgent, tim... |
def valid_action(self, moves, current_pos, visited_pos):
invalid_actions = []
for ndx, act in enumerate(self.addpos_action):
if moves == 0:
# 0 is valid, 1 invalid, 2 lost game
if self.validatemove(current_pos, act) != 0:
invalid_actions.ap... | The main task of the code is to train a reinforcement learning agent in a 2D Gridworld environment using Q-learning. It runs multiple epochs, interacts with the environment, collects rewards, and stores experiences in a replay buffer. Mini-batches are sampled to update the model's parameters via Q-value estimation and ... | def train_step(self):
self.model.train()
mode = self.mode
epsilon_ = self.config["epsilon"]
total_moves = 0
total_unsync_moves = 0
num_epochs = self.config["num_epochs"]
replay = deque(maxlen=self.config["mem_size"])
print("num_epochs:", num_epochs)
... |
def tilt(rocks_str: str, direction: Direction) -> str:
# We pass around strings rather tha lists so we can cache our results
rocks = rocks_str.strip().split("\n")
# transform the rocks array so we are always looking at a row of rocks
# and shifting rocks to the start of those rows.
rocks = transfor... | The function calculates the maximum load on a platform after tilting rocks northward. It first tilts the input rock configuration north, splits the string into rows, processes rock positions, and computes the maximum load by measuring the distance of rocks from the bottom of the platform (start of the string). | def calculate_max_load_north_tilt(rocks_str: str) -> int:
# "tilt" the platform so the rocks move "north"
rocks_str = tilt(rocks_str, Direction.NORTH)
# load is the distance from the bottom of the platform, or in our case the
# start of the string, so we can simply note the location of the rock and
... |
def cycle(rocks: str) -> str:
for direction in [Direction.NORTH, Direction.WEST, Direction.SOUTH, Direction.EAST]:
# Perform operations with the direction
rocks = tilt(rocks, direction)
return rocks
def rotate_rocks_north_tilt(rocks):
rotated_rocks = []
for i in range(len(rocks[0])):
... | The function simulates processing a string of rocks through multiple cycles, detecting loops to optimize computation, then calculates the maximum load after all cycles by rotating the final state northward and determining the load. | def calculate_max_load_after_cycles(rocks_str: str, cycles=1000000000) -> int:
cycle_set = []
skipped = False
i = 0
while i < cycles:
rocks_str = cycle(rocks_str)
if not skipped:
if rocks_str not in cycle_set:
cycle_set.append(rocks_str)
else:
... |
def recvMessage(expectedSeqNum):
global SERVER_SOCKET
payloadData, client = SERVER_SOCKET.recvfrom(MAX_PAYLOAD_LENGTH)
processedPayload = processPayloadData(payloadData, expectedSeqNum)
if processedPayload is None:
sendAck(client, expectedSeqNum)
return None
hasNext = proce... | The main task of the code is to implement a UDP server that listens on a specified port, receives data packets in sequence with timeout handling, accumulates the received message, sends acknowledgments to the client, and writes the complete message to stdout. The server continues operating until interrupted by a keyboa... | def main():
global SERVER_PORT, SERVER_SOCKET
argv = sys.argv
if len(argv) <= 1:
sys.exit(1)
port = None
try:
port = int(argv[1])
except:
sys.exit(1)
SERVER_PORT = port
SERVER_SOCKET = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
SERVER_SOCK... |
def _position_in_goal_area(self, position):
w, h = position
width, height = self.dims
return w <= 2 or w >= width - 3 or h <= 2 or h >= height - 3
def _get_positions_adjacent_to_small_box(self, position):
adjacent_positions = [(position[0], position[1] + 1),
... | This function removes small or large boxes that have been moved into the goal area. It checks each small box's position, removes it if in the goal, updates the grid, and calculates rewards. For large boxes, it verifies all four positions are in the goal before removal. Adjacent positions are retrieved, and rewards are ... | def _remove_cleared_boxes(self):
reward = np.zeros(self.nrobots)
# Make position None (or remove one), free agents, update grid, give reward to each agent that participated
if self.small_box_positions is not None:
box_id = 0
while True:
position = self.sma... |
def _take_action_free(self, agent_id, action):
# Actions: 0: STAY, 1: UP, 2: RIGHT, 3: DOWN, 4: LEFT, 5: UP_POW, 6: RIGHT_POW, 7: DOWN_POW, 8: LEFT_POW
position = self.robots[agent_id][0]
width, height = self.dims
new_position = (position[0] + self.action_specs[action][0], position[1] +... | This function processes robot actions in a multi-robot environment. It first applies actions to free robots, then handles attached robots near large/small boxes. Rewards are calculated for attached robots' actions and aggregated. The function returns total rewards for all robots after executing their respective actions... | def _take_actions(self, actions):
# Action specs: [num actions, (w change, h change, energy_success, energy_fail)]
# Actions: 0: STAY, 1: UP, 2: RIGHT, 3: DOWN, 4: LEFT, 5: UP_POW, 6: RIGHT_POW, 7: DOWN_POW, 8: LEFT_POW
reward = np.zeros(self.nrobots)
# Take free robot actions first
... |
def _get_step_reward(self):
boxes_remaining = 2
if self.small_box_positions is not None:
boxes_remaining -= len(self.small_box_positions)
elif self.large_box_position is not None:
boxes_remaining -= 1
return np.full(self.nrobots, boxes_remaining * self.reward_per... | The `step` function processes agent actions in a multi-robot environment, computes rewards for box interactions, updates the environment state, and returns observations, rewards, episode status, and statistics. It validates actions, applies them to move boxes, calculates rewards from actions and cleared boxes, tracks m... | def step(self, actions):
if self.episode_over:
raise RuntimeError("Episode is done")
actions = np.array(actions).squeeze()
reward = self._get_step_reward() # All agents given negative reward for boxes
assert np.all(actions <= self.naction), "Actions should be in the range ... |
def generate_mines(self):
count = 0
while count < self.mines:
x = random.randint(0, self.rows - 1)
y = random.randint(0, self.columns - 1)
if (x, y) not in self.mine_positions:
self.mine_positions.append((x, y))
count += 1
def create_bu... | This code initializes a Minesweeper game by setting up a grid with specified rows, columns, and mines. It generates mine positions, creates buttons for each cell, and displays either a mine ("*") or adjacent mine counts. The GUI is configured with a titled window, and the field is populated with interactive buttons rep... | def __init__(self, root):
self.root = root
self.root.title("Minesweeper")
self.rows = 10
self.columns = 10
self.mines = 1
self.field = []
self.mine_positions = []
self.generate_mines()
for i in range(self.rows):
row = []
... |
def pdb_pipeline(topol, trj, i_start, i_end, restart, dnaLig, time_limit, worker_id, size, out_path):
#set time limit in seconds for each process
time_limit_s = time_limit * 60 * 60
set_error = 0
table = {"hbonds":dict(), "pi-stacks":dict(), "salt-bridges":dict(), "hydrophobic-interactions":dict... | The code implements a parallel processing task using MPI to distribute work across processes. It validates input parameters, scatters time intervals to workers, executes a pipeline for data analysis, gathers results, merges tables, and saves outputs as CSV files. Error handling ensures proper termination on invalid inp... | def main(topol, trj, start, end, restart, out_path, ligand_id, dnaLig, timeLimit):
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
err_code = 0
work = np.arange(start, end + 10, 10, dtype=np.uintc)
recv_size = int(((end - start) / 10) // size + 1)
if size > work.s... |
def parse_arguments():
# record, trim, replay, parse
if args.debugreplay:
return False, True, True, False
elif args.recordonly:
return True, False, False, False
elif args.notrim:
return True, False, True, False
else:
return True, True, True, True
def run_concolic(do_r... | The main task of the code is to execute a concolic testing workflow by setting up the working directory, parsing command-line arguments to control recording, trimming, replay, and parsing modes, running the concolic process, and handling errors during replay or parsing. It returns status codes based on success/failure ... | def main():
setup_work_dir(target=args.target)
rc, tm, rp, ps = parse_arguments()
ret = run_concolic(do_record=rc, do_trim=tm, do_replay=rp)
if rp and ret in [RECORD_ERROR_CODE, MAPPING_ERROR_CODE]:
print(f"Concolic run/replay failed with status {ret}")
return ret
if ps and parse_con... |
def bytes_to_file(fname, bs):
with open(fname, 'wb') as f:
return f.write(bs)
def get_out_file(n):
return os.path.join(get_out_dir(args.target), str(n))
def run_concolic_model(target, inp, model):
global br_blacklist
test_branch = last_branch_in_model(model)
zeros, ones, others, jcc_pcs = ge... | The function `search_greedy` performs a greedy search to find an optimal input by iteratively exploring symbolic branches in a concolic execution model. It prioritizes branches based on execution scores, updates the model with the best branch-condition pair, and tracks new branches, non-flippable branches, and repeatin... | def search_greedy():
"""search for an optimal input
"""
print('[search_group]: search_greedy')
global br_model
global cur_input
global new_branch_ips
nonflippable = set()
new_branch = True
output = b''
repeating_branches = set()
with open(args.input, "rb") as f:
outp... |
def bytes_to_file(fname, bs):
with open(fname, 'wb') as f:
return f.write(bs)
def get_out_file(n):
return os.path.join(get_out_dir(args.target), str(n))
def bytes_to_hash(bs):
hash = hashlib.sha1(bs).hexdigest()
hashfile = get_out_file(hash)
with open(hashfile, 'wb') as f:
f.write(bs... | This function evaluates a branch condition in a concolic execution model, checking if it leads to new branches. It runs the model with merged conditions, records results if new branches are found, updates preferred outcomes, and handles unflippable branches. The task involves symbolic execution to explore program paths... | def run_branch_condition(br, c):
print(time.ctime())
print(f"Trying ({hex(br)}, {c})")
bytes_to_file(get_out_file(0), cur_input)
infile = bytes_to_hash(cur_input)
concolic_result = run_concolic_model(
args.target, infile, merge_dict(deepcopy(br... |
def get_ols_est(x, y):
xtx = np.swapaxes(x, -1, -2) @ x
xtx_inv = np.linalg.inv(xtx)
xty = np.swapaxes(x, -1, -2) @ y
est = xtx_inv @ xty
return est, xtx_inv
def fit_smooth(value, filter_size, coord=None, img_shape=None):
if coord is None:
assert img_shape is not None
value = val... | This function computes a statistical threshold for significance testing using permutation-based null distribution. It shuffles input data (x) multiple times, estimates main effects (maineff_null) via OLS or neural network approximation, and calculates a threshold as the (1-alpha) quantile of absolute null values. The t... | def compute_threshold(
x, y, alpha,
hidden_widths, activation, lr, batch_size, epochs, prefix,
s=None, img_shape=None,
n_permute=10, fast_approximation=False):
n_observations = x.shape[0]
maineff_null_list = []
for i in range(n_permute):
order = np.random.choice(
... |
def compute_threshold(
x, y, alpha,
hidden_widths, activation, lr, batch_size, epochs, prefix,
s=None, img_shape=None,
n_permute=10, fast_approximation=False):
n_observations = x.shape[0]
maineff_null_list = []
for i in range(n_permute):
order = np.random.choice(
... | The function `fit_nnisr` trains a neural network model to estimate individual and main effects from input data (`x`, `y`), incorporating a thresholding mechanism and parallel state computation. It computes an initial threshold, initializes effect predictions, and iteratively trains multiple neural network states in par... | def fit_nnisr(
x, y, s=None, img_shape=None,
hidden_widths=(256,)*4, activation='leakyrelu',
alpha_threshold=0.05,
n_permute=100, lr=1e-3, epochs=50, batch_size=4096,
n_states=11, alpha_states=0.5,
prefix='nnisr/', device=None, n_jobs=None):
if device is None:
... |
def getStack(self):
return self.stack
def setStack(self, cards):
self.stack = cards
def revealTopCard(self):
""" Reveals the top card of the pile """
if self.getTopCard() != None:
self.getTopCard().reveal() | The main task of the code is to remove specified cards from a pile by adjusting the stack. If the stack has multiple cards, it removes the specified cards and reveals the new top card. If the stack has only one card, it empties the stack. The function returns True if cards were removed, otherwise False. | def removeCards(self, cards):
""" Removes cards from a pile """
stack = self.getStack()
if len(stack) > 1:
index = stack.index(cards[0])
if index != None:
self.setStack(stack[:index])
self.revealTopCard()
return True
... |
def cached_type_info(zserio_t) -> Optional[TypeInfo]:
if not hasattr(zserio_t, "type_info"):
return None
key = f"{zserio_t.__module__}.{zserio_t.__qualname__}"
if key not in TYPE_INFO_CACHE:
TYPE_INFO_CACHE[key] = zserio_t.type_info()
return TYPE_INFO_CACHE[key]
def check_uninstantiable(... | This function creates an instance of a given type `t`, recursively instantiates its non-scalar fields, and assigns them as underscore-prefixed attributes. It first checks if the type is uninstantiable, raising an error if so. For each member, if the member's type is not scalar, it instantiates that type and sets it on ... | def instantiate(t: Type) -> Any:
result_instance = t()
type_info = cached_type_info(t)
if reason := check_uninstantiable(type_info):
raise reason
for _, member_info in members(type_info):
field_name: str = member_info.attributes[MemberAttribute.PROPERTY_NAME]
member_type_info = m... |
def cached_type_info(zserio_t) -> Optional[TypeInfo]:
if not hasattr(zserio_t, "type_info"):
return None
key = f"{zserio_t.__module__}.{zserio_t.__qualname__}"
if key not in TYPE_INFO_CACHE:
TYPE_INFO_CACHE[key] = zserio_t.type_info()
return TYPE_INFO_CACHE[key]
def str_to_bytes(s: str, ... | The function processes request parameters to serialize a request object into bytes. It instantiates a request object, converts parameters to appropriate types, applies them to the object, and serializes it using a bit stream writer, returning the resulting byte array. | def request_object_blob(*, req_t: Type, headers: Dict[str, Any], spec: OAMethod, **kwargs) -> bytes:
# Lazy instantiation of request object and type info
req: Optional[req_t] = None
req_t_info = cached_type_info(req_t)
# Apply parameters
param_name: str
param: OAParam
for param_name, param i... |
def eval_ethnic_bias(WE):
"""
Evaluate the black as ethnic group vs. colour bias.
"""
#balck_ethnic_sid = "black%1:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b" # noun
#black_colour_sid = "black%1:fc00:db20:35b:7399::5" # noun
balck_ethnic_sid = "black%3:fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b" # ... | The main task of the code is to load a pre-trained word embedding model from a specified file and evaluate potential biases in the embeddings related to ethnicity, race, and gender using three evaluation functions: eval_ethnic_bias, eval_racial_bias, and eval_gender_bias. The code structure initializes the model and se... | def main():
WE = WordEmbedding("./data/lmms_1024.bert-large-cased.npz")
eval_ethnic_bias(WE)
eval_racial_bias(WE)
eval_gender_bias(WE)
pass |
def get_data_groupings(data, SampleId_lookup, grouping, group_key='Group'):
grouping = str(grouping)
assert grouping in ("1","2","3","4","5","6","7")
drop_row_vals, mapping = get_grouping_label_map(grouping)
data_labels = SampleId_lookup.loc[data.index][group_key]
data_labels = data_labels[~data_la... | This function performs hyperparameter tuning and evaluation of random forest models across multiple groupings of data. It iterates through specified group configurations, splits data into training/test sets, conducts random search optimization, and stores validation/test results, feature importances, and sample IDs for... | def full_analysis_all_groupings_all_features(df, SampleId_lookup
, n_iter=80, n_estimators=250, group_key='Group'
, metric=balanced_accuracy_score
, groupings=[2,3,4,5,6,7]):
all_best_scores, all_best_params = {}, {}
all_train_sample_ids, all_test_sample_ids = {}, {}
all_best_results... |
def preprocess():
""" main function that does the preprocessing """
train_path = "Dataset_crimes.csv"
train_path2 = "crimes_dataset_part2.csv"
train = process_data(pd.read_csv(train_path)).dropna()
train2 = process_data(pd.read_csv(train_path2)).dropna()
train_co = pd.concat([train, train2], axi... | The main task of the code is to train multiple classifiers using ensemble methods (Bagging and Adaboost), combine them into a model list, and serialize each model into pickle files for storage. The process involves preprocessing data, creating base classifiers, applying ensemble techniques, and saving trained models fo... | def train():
""" main function to train the model """
X_train, y_train = preprocess()
CLASSIFIERS = create_classifiers()
CLASSIFIERS_1 = Bagging(X_train, y_train, T, CLASSIFIERS[1:2])
CLASSIFIERS_2 = Adaboost(X_train, y_train, T, CLASSIFIERS[2:])
models = CLASSIFIERS_1 + CLASSIFIERS_2
pkl_fi... |
def get_health(checks):
dict = {}
dict['summary'] = is_present(checks, 'ospf_status_summary')
dict['all_up'] = is_present(checks, 'all_neighbors_up')
dict['all_down'] = is_present(checks, 'all_neighbors_down')
dict['min_up'] = is_present(checks, 'min_neighbors_up')
return dict
def get_status(st... | The code processes health facts from OSPF neighbors, evaluates their states (up/down), and generates a structured health check report. It aggregates statistics, checks predefined conditions (e.g., all neighbors up/down, minimum up count), and updates the status to 'unsuccessful' if checks fail. The result includes deta... | def health_check_view(*args, **kwargs):
params = ["health_facts", "target"]
data = dict(zip(params, args))
data.update(kwargs)
if len(data) < 2:
raise AnsibleFilterError(
"Missing either 'health facts' or 'other value in filter input,"
"refer 'health_check_view' filter pl... |
def do_cert_request(
module, csr, principal, add_principal=None, ca=None, profile=None,
chain=None, certificate_out=None
):
"""Request a certificate."""
args = gen_args(
module, principal=principal, ca=ca, chain=chain,
add_principal=add_principal, profile=profile,
)
exit_args = {... | (This code defines an Ansible module for managing FreeIPA certificate lifecycle operations. It validates parameters for certificate states (requested, revoked, etc.), connects to IPA API, and executes actions like requesting, revoking, releasing, or retrieving certificates based on the specified state. It ensures param... | def main():
ansible_module = IPAAnsibleModule(
argument_spec=dict(
# requested
csr=dict(type="str"),
csr_file=dict(type="str"),
principal=dict(type="str"),
add_principal=dict(type="bool", required=False, aliases=["add"]),
profile_id=dic... |
def getHits(query,keywords,searcher):
hits = searcher.search(query + '. ' + keywords)
n_hits = len(hits)
## collect the relevant data in a hit dictionary
hit_dictionary = {}
for i in range(0, n_hits):
doc_json = json.loads(hits[i].raw)
idx = str(hits[i].docid)
hit_dictionary[... | The code retrieves relevant information based on a query and keywords by first obtaining search hits, then extracting abstracts from these hits, and finally generating a summary of the results. The main task is to process the query through search, abstraction, and summarization to provide a concise answer. | def getResult(self,query,keywords):
hits = getHits(query,keywords,self.searcher)
answers = self.searchAbstracts(hits,query)
return self.getSummary(hits,answers,query) |
def conv_int_to_rat(int_: int) -> Rat:
'''
summary: Convert an integer to a rational.
All integers are rationals, so there's no risk of failure.
params:
int_: int to be converted.
return: Rat of the integer.
'''
rat: Rat = Rat()
rat.num = int_
rat.den = 1
return rat
def... | The function `eval_mod` computes the modulo of two numbers (`number_a` and `number_b`), handling both integers and rational numbers (`Rat`). It standardizes results by converting integers to `Rat` when needed, performs division, calculates quotients, and subtracts products to derive remainders. The output is a simplifi... | def eval_mod(number_a: Number, number_b: Number) -> Number:
'''
summary: Evaluate the modulo of two numbers.
params:
number_a: Number of the left operand of an <MOD-(EXPR|SUBEXPR)>.
number_a: Number of the right operand of an <MOD-(EXPR|SUBEXPR)>.
return: Number of the modulo, simplified and s... |
def eval_int_subexpr(node: Node) -> int:
'''
summary: Evaluate an <INT-SUBEXPR> Node by converting its literal.
params:
node: Node of the <INT-SUBEXPR>.
An <INT-SUBEXPR> is terminal.
An <INT-SUBEXPR> literal is a collection of digits '0' through '9'.
'''
int_a: int = 0
for c... | This function evaluates arithmetic expressions represented by a tree structure, recursively computing integer, rational, or real values for operations like addition, subtraction, multiplication, division, and modulus. It handles variables by scope and name, applies corresponding evaluation functions for each expression... | def eval_arit_tree(tree: Node) -> Number:
'''
summary: Evaluate every <ADD-EXPR>, <SUB-EXPR>, <MUL-EXPR>, <DIV-EXPR>,
<EXP-EXPR>, <DEC-EXPR>, <INT-SUBEXPR>,
as well as their matching <___-SUBEXPR>, to an integer, rational, or real.
params:
tree: Node of the tree whose root should evalua... |
def parse(done_item: str) -> done.CompletedItem:
'''Raises `ValueError` if parse fails.'''
completed_item = try_parse(done_item)
if completed_item:
return completed_item
else:
raise ValueError("`done_item` must be of format '[isodate] completed item'")
def _check_completed_since(complete... | The function reads a file at the specified path, filters lines based on a date condition relative to `completed_since`, parses valid lines into `CompletedItem` objects, and returns the filtered list. If the file does not exist, it returns an empty list. | def get(path: str, completed_since: datetime) -> List[done.CompletedItem]:
if not os.path.exists(path):
return []
with open(path) as f:
return [
parse(line.strip())
for line in f.readlines()
if _check_completed_since(try_parse(line), completed_since)
... |
def find_duplicate_keys(self, table_name, key_field):
"""Find if a table has duplicates by a certain column, if so return all the instances that
have duplicates together with their counts."""
query = f"""
SELECT {key_field}, COUNT({key_field}) as cnt
FROM {table_name}
GRO... | This function removes duplicate records from a Google BigQuery table based on a specified primary key field. It identifies duplicates, constructs a SQL query to retain only the first occurrence of each duplicate group using ARRAY_AGG, and replaces the table with deduplicated data. Partitioning and clustering expression... | def remove_duplicate_keys_from_bigquery(self, table_name, key_field):
"""Remove any duplicate records when comparing primary keys.
Note: this currently only supports Google Biquery
"""
dups = self.find_duplicate_keys(table_name, key_field)
if dups:
logging.info(f"... |
def import_data(csv_file):
return pd.read_csv(csv_file)
def split(data):
" Split the data into X and y. "
# No Scaling
end_inp = int(np.where(data.columns == 'CompRqPost')[0]) #Find the index in data headers where input ends and output begins
input_data = data.iloc[:, 0:end_inp] # X
output_data ... | The code compares multiple regression and classification models on a dataset, evaluating their performance using accuracy and mean squared error (MSE). It iterates through combinations of regression (e.g., Random Forest, SVR) and classification (e.g., Random Forest, Extra Trees) methods, trains each on the data, and co... | def main():
#return 0
# Choose the ML method and retrieve the model
method_regr = [0, 1, 0, 0, 0, \
0, 0]
regr_names = ['Random Forest', 'Gradient Boost', 'Linear Regression', 'SVR', 'KNeighbors', \
'Gaussian Process' , 'Decision Tree']
method_classi = [0, 1]
clas... |
def checkRole(userId, role):
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from user_details where id = %s"
values = (userId,)
try:
r = cur.execute(query,values)
rows = cur.fetchall()
cur.close()
conn.close()
if rows[0][-3] == role:
return True
else:
r... | The function retrieves attendance records for a specific course and date, verifies the user is a student, fetches student details, and returns a structured list of attendance data including student IDs, names, emails, and batch information. | def viewAttendance(userId,courseId,date):
d = checkRole(userId,"student")
if d == False:
return "User must be student"
try:
batch_id = getStudentBatch(userId)
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from attendance where course_id = %s and date = %s"
values = (c... |
def checkRole(userId, role):
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from user_details where id = %s"
values = (userId,)
try:
r = cur.execute(query,values)
rows = cur.fetchall()
cur.close()
conn.close()
if rows[0][-3] == role:
return True
else:
r... | The function retrieves student results for a given course by verifying the user's student role, querying a database for matching records, converting binary image data to base64 encoding, and returning structured result dictionaries. It handles exceptions by returning False on errors. | def getResult(userId,courseId):
d = checkRole(userId,"student")
if d == False:
return "User must be student"
try:
conn = getConnectionDetails()
cur = conn.cursor()
batch_id = getStudentBatch(userId)
# print(batch_id,courseId)
query = "Select * from result where batch_id = %s and course_id ... |
def checkRole(userId, role):
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from user_details where id = %s"
values = (userId,)
try:
r = cur.execute(query,values)
rows = cur.fetchall()
cur.close()
conn.close()
if rows[0][-3] == role:
return True
else:
r... | The main task of the code is to retrieve a student's timetable from a database by verifying the user's role, converting the timetable data to base64 encoding, and returning it in a dictionary format. If the user is not a student or an error occurs, it returns an error message or False. | def viewTimetable(userId):
d = checkRole(userId,"student")
if d == False:
return "User must be student"
try:
conn = getConnectionDetails()
cur = conn.cursor()
batchId = getStudentBatch(userId)
query = "Select * from timetable where batch_id = %s"
values = (batchId,)
r = cur.execute(que... |
def checkRole(userId, role):
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from user_details where id = %s"
values = (userId,)
try:
r = cur.execute(query,values)
rows = cur.fetchall()
cur.close()
conn.close()
if rows[0][-3] == role:
return True
else:
r... | The main task of the code is to retrieve all feedback records from a database, compile them with related student, course, and faculty details, and return them as a structured list if the user is an admin. It verifies user role, queries feedback data, fetches associated details, and formats results, returning an error i... | def getAllFeedbacks(userId):
d = checkRole(userId,"admin")
if d == False:
return "User must be admin"
try:
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from feedback"
result = []
r = cur.execute(query)
rows = cur.fetchall()
for row in rows:
j = {}
... |
def checkRole(userId, role):
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from user_details where id = %s"
values = (userId,)
try:
r = cur.execute(query,values)
rows = cur.fetchall()
cur.close()
conn.close()
if rows[0][-3] == role:
return True
else:
r... | The function retrieves and processes batch and course details for a faculty member based on their user ID. It verifies the user's faculty role, queries the database for their record, and extracts batch and course data. If these fields are null, it initializes them as empty lists; otherwise, it processes them using reso... | def getFacultyBatchCourseDetails(userId):
d = checkRole(userId,"faculty")
if d == False:
return "User must be faculty"
else:
try:
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from faculties where user_id = %s"
values = (userId,)
r = cur.execute(query,va... |
def checkRole(userId, role):
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from user_details where id = %s"
values = (userId,)
try:
r = cur.execute(query,values)
rows = cur.fetchall()
cur.close()
conn.close()
if rows[0][-3] == role:
return True
else:
r... | The main task of the code is to retrieve a list of students associated with a faculty member based on their user ID. It first verifies the user's role as faculty, queries the database for the faculty's batches, and fetches students linked to those batches. If the user isn't faculty or an error occurs, it returns an err... | def getFacultyStudents(userId):
d = checkRole(userId,"faculty")
if d == False:
return "User must be faculty"
else:
try:
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from faculties where user_id = %s"
values = (userId,)
r = cur.execute(query,values)
... |
def checkRole(userId, role):
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from user_details where id = %s"
values = (userId,)
try:
r = cur.execute(query,values)
rows = cur.fetchall()
cur.close()
conn.close()
if rows[0][-3] == role:
return True
else:
r... | The main task of the code is to allow an admin user to assign a new course to a faculty member by updating the faculty's course list in a database. It verifies the user's admin role, retrieves existing faculty course data, appends the new course ID, and executes an SQL update to store the updated course list for the fa... | def assignCourse(userId,courseId,facultyId):
d = checkRole(userId,"admin")
if d == False:
return "User must be admin"
facultyCourse = getFacultyBatchCourseDetails(facultyId)
courseDetails = facultyCourse[1]
print(courseDetails)
courseDetails = courseDetails['courses']
courseIds = []
for course in co... |
def checkRole(userId, role):
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from user_details where id = %s"
values = (userId,)
try:
r = cur.execute(query,values)
rows = cur.fetchall()
cur.close()
conn.close()
if rows[0][-3] == role:
return True
else:
r... | This function allows an admin to assign a batch to a faculty by updating their record in the database. It verifies the user's admin role, retrieves the faculty's existing batch IDs, adds the new batch ID, and executes an SQL update to store the updated batch list for the faculty. Error handling ensures database operati... | def assignBatch(userId,batchId,facultyId):
d = checkRole(userId,"admin")
if d == False:
return "User must be admin"
facultyBatch = getFacultyBatchCourseDetails(facultyId)
# print(facultyBatch)
batchDetails = facultyBatch[0]
batchDetails = batchDetails['batches']
print(batchDetails)
batchIds = []
f... |
def checkRole(userId, role):
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from user_details where id = %s"
values = (userId,)
try:
r = cur.execute(query,values)
rows = cur.fetchall()
cur.close()
conn.close()
if rows[0][-3] == role:
return True
else:
r... | The function retrieves course details for a student based on their batch. It first verifies the user is a student, fetches their batch from the database, and then retrieves course information using the batch. If validation fails or errors occur, it returns appropriate messages. | def getStudentBatchCourseDetails(userId):
d = checkRole(userId,"student")
if d == False:
return "User must be student"
try:
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from students where user_id = %s"
values = (userId,)
r = cur.execute(query,values)
rows = cur.... |
def checkRole(userId, role):
conn = getConnectionDetails()
cur = conn.cursor()
query = "Select * from user_details where id = %s"
values = (userId,)
try:
r = cur.execute(query,values)
rows = cur.fetchall()
cur.close()
conn.close()
if rows[0][-3] == role:
return True
else:
r... | The main task of the code is to add a new course to a specific batch in a database, requiring the user to be an admin. It retrieves the batch's existing courses, appends the new course ID, and updates the batch's course list. If the user isn't an admin or an error occurs during execution, it returns an error message or... | def addNewCourseToBatch(userId,batch_id,course_id):
d = checkRole(userId,"admin")
if d == False:
return "User must be admin"
try:
conn = getConnectionDetails()
cur = conn.cursor()
courses = getCourseDetailsFromBatch(batch_id)
courses = courses['courses']
cl = []
for course in courses:
... |
def ColoredEdges(P):
edges = []
for chr in P:
Nodes = ChromosomeToCycle(chr)
for j in range(1, len(chr)+1):
if j == len(chr):
edges.append((Nodes[(2*j) - 1], Nodes[0]))
else:
edges.append((Nodes[(2*j) - 1], Nodes[(2*j+1) - 1]))
... | The function performs two-break sorting to transform permutation P into Q by iteratively applying two-break operations. It constructs a breakpoint graph using red edges (from P) and blue edges (from Q), then iterates through blue edges to identify non-self-cycle edges. For each valid edge, it modifies the graph and app... | def TwoBreakSorting(P, Q):
steps = [P.copy()]
RedEdges = ColoredEdges(P)
BlueEdges = ColoredEdges(Q)
BreakPointGraph = defaultdict(list)
for r in RedEdges:
BreakPointGraph[r[0]].append(r[1])
BreakPointGraph[r[1]].append(r[0])
for b in BlueEdges:
BreakPointGraph[b... |
def get(key, default=None):
try:
return db.config.find_one({"_id": key})["value"]
except Exception:
if default:
db.config.update_one( {"_id": key},{ "$set" : { "value": default } }, upsert=True )
return default
def send(event, info):
me.queue.append({ "event": event, "info": info})
if len(me.q... | This function continuously processes scheduled tasks by checking their designated execution time against the current UTC timestamp. When a task is due, it logs the command, executes it using a predefined command handler, removes the task from the schedule, and sends a feedback confirmation. The loop repeats with short ... | def perform_scheduled_tasks():
while True:
try:
scheduled = me.schedule.get()
while scheduled and scheduled["schedule"] <= datetime.datetime.utcnow().timestamp():
logger.info("performing scheduled cmd: {0}".format(scheduled) )
commands[scheduled["cmd"]](scheduled["args"])
me.sc... |
def print_board(self):
for i in range(64):
print('.BW'[self.board[i]],end='\n' if i&7==7 else '')
print()
def check_move(self,field):
if field<0:
return True
f1,f2=field//8,field%8
if self.board[field]!=0: return False
for x,y in gen():
... | The code implements a turn-based game loop where the board is displayed, checks for valid moves, switches player turns if no moves are available, and processes user input to execute moves. It handles invalid moves via exception handling, iterating indefinitely until the game concludes. | def play(self):
while True:
self.print_board()
dirty=False
for i in range(64):
if self.check_move(i):
dirty=True
break
if not dirty: self.color=3-self.color
s=list(map(int,input().split()))
... |
def remove_num_in_row(self, coord, solved_value):
"""
Remove solved_value from the list of possible values of
other unsolved cells in this row.
"""
ref_row, ref_col = coord # reference cell
for col_step in range(9):
if col_step != ref_col:
th... | The main task of the code is to remove a solved number from all possible positions in the same row, column, and 3x3 box after it is filled on the board, ensuring no duplicates in these regions. | def remove_num(self, coord, solved_value):
"""
After a number on the board has been filled in, remove it as a
possibility in all affected areas.
"""
self.remove_num_in_row(coord, solved_value)
self.remove_num_in_col(coord, solved_value)
self.remove_num_in_box(coor... |
def create_padding_mask(seq):
seq = tf.cast(tf.math.equal(seq, 0), tf.float32)
return seq[:, tf.newaxis, tf.newaxis, :]
def positional_encoding(max_seq_len, d_model):
angle_rads = get_angles(np.arange(max_seq_len)[:, np.newaxis], np.arange(d_model)[np.newaxis, :], d_model)
angle_rads[:, 0::2] = np.sin(a... | This code defines a Transformer model for binary classification. It processes input sequences through embedding, positional encoding, and encoder layers, then uses global average pooling and a sigmoid output layer. The model includes padding masking, dropout regularization, and is built using Keras with TensorFlow. | def transformer_model(input_shape, num_layers, d_model, num_heads, dff, vocab_size, maxlen):
inputs = tf.keras.layers.Input(shape=input_shape)
mask = tf.keras.layers.Lambda(lambda x: create_padding_mask(x))(inputs)
x = tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=d_model)(inputs)
x *= tf.m... |
def rmsprop_optimizer(y, X, theta, n_iter, eta, rho=0.99, delta=1e-7, lmd=0.01):
Giter = 0.0
for i in range(n_iter):
gradient = logistic_gradient(y, X, theta)
Giter = rho * Giter + (1 - rho) * gradient * gradient
update = (gradient + lmd * theta) * eta / (np.sqrt(Giter) + delta)
... | The code trains a logistic regression model using specified optimization algorithms (RMSProp, AdaGrad, or Adam) by initializing random weights and iteratively updating them with the chosen optimizer. It returns the optimized parameters (theta) after completing the specified number of iterations. | def train_logistic_regression(X_train, y_train, optimizer, n_iter=100, eta=0.01, lmd=0.01):
_, n_features = X_train.shape
theta = 0.01 * np.random.randn(n_features, 1)
if optimizer == 'rmsprop':
theta = rmsprop_optimizer(y_train, X_train, theta, n_iter, eta, lmd)
elif optimizer == 'adagrad':
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.