dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_db_info(env_name):
# Funcion to get DB connection parameters from AWS SSM
# env_name: string, like 'dev', 'sit' , etc - provided as EMR step argument
# returns: db_user, db_host, db_name, db_pwd
global DEBUG
log('Entering get_db_info')
log('getting SSM client so we can pull db-connection... | The main task of the code is to process multiple input folders by concatenating JSON files into a single large file on the local filesystem, using a specified chunk size limit. It retrieves database connection details from AWS SSM based on the environment, executes Hive table creation scripts from an S3 location, logs ... | def main():
"""
For every folder provided as argument, run the concatenation procedure:
read bunch of json files from current folder, and save as one big file on local fs
to create schema with
"""
global DEBUG
ap = argparse.ArgumentParser()
ap.add_argument('-hive', '--hive_table_creatio... |
def get_db_info( env_name):
#Funcion to get DB connection parameters from AWS SSM
#env_name: string, like 'dev', 'sit' , etc - provided as EMR step argument
#returns: db_user, db_host, db_name, db_pwd
global DEBUG
log('Entering get_db_info')
log('getting SSM client so we can pull db-connection info from SSM')
ss... | The main task of the code is to process multiple folders by concatenating JSON files into a single large file on the local filesystem, using database connection details retrieved from AWS SSM. It processes each folder, generates reports, and handles environment-specific S3 paths. The script logs debug information, mana... | def main():
"""
For every folder provided as argument, run the concatenation procedure:
read bunch of json files from current folder, and save as one big file on local fs
to create schema with
"""
global DEBUG
ap = argparse.ArgumentParser()
#ap.add_argument('-hive', '--hive_table_creation_files_location', requ... |
def concat_rpn_head_outputs(cls, deltas):
N, AxC, H, W = cls.shape
Ax4 = deltas.shape[1]
A = Ax4 // 4
C = AxC // A
cls = permute_and_flatten(cls, N, C, H, W)
deltas = permute_and_flatten(deltas, N, 4, H, W)
cls = cls.flatten(0, -2)
deltas = deltas.reshape(-1, 4)
return cls, deltas
de... | The code implements a Region Proposal Network (RPN) forward pass for object detection. It generates anchor boxes, computes objectness scores and bounding box deltas, decodes proposals, and filters them. During training, it matches anchors to ground-truth targets, samples positive/negative examples, and calculates binar... | def forward(self, images, targets, feature):
num_images = len(images.tensors)
objectness, bbox_deltas = self.rpn_head(feature)
anchors = self.anchor_generater(images, feature)
num_anchors = anchors[0].shape[0]
objectness, bbox_deltas = concat_rpn_head_outputs(objectness, bbox_del... |
def init_tree(self, conll_tree):
'''
Given a ConllTree object initializes the parser with
its edges and resets the configuration
'''
# reset state machine
self.reset()
# init conll_tree data
self.conll_tree = conll_tree
self.target_edges = co... | This code generates a sequence of arc-eager parsing configurations for a given dependency tree by iteratively selecting and applying parsing actions (shift, left/right arc, reduce), updating the parser's state (stack and buffer), and recording each configuration state. The final output is a list of training examples de... | def get_parser_config(self, dependency_tree):
'''
Gets the arc-eager configuration for a single
dependency tree
'''
self.init_tree(dependency_tree)
while self.buffer != []:
# get action
valid_actions, arc = self.get_next_action()
... |
def init_sentence_raw(self, words, postags):
'''
Given a raw sentence shaped as a string initializes
the parser in order to predict it
'''
# reset state machine
self.reset()
# init sentence data
self.words = words
self.postags = postags
... | The code predicts a dependency tree for a sentence using a model by iteratively selecting actions (left/right arcs, reduce, shift) based on predicted probabilities. It maintains a stack and buffer, updating them according to the chosen action, while recording configurations. Once all actions are processed, it construct... | def predict_dependency_tree(self, words, postags, model):
'''
Predicts the dependency tree for a single sentence
'''
# initialize sentence
self.init_sentence_raw(words, postags)
while self.buffer!=[]:
# predict actions list and (if arc made) relation... |
def createFolder (drive_service, fCollectName, fContainer):
id = checkFolderExist (drive_service, fCollectName, fContainer)
if id != '':
return id
file_metadata = {
'name': fCollectName,
'parents':[fContainer],
'mimeType': 'application/vnd.google-apps.folder'
}
try:
file = drive_service.files().crea... | This function recursively uploads files and folders to Google Drive. It creates folders for nodes with 'content' and processes their content recursively, while starting threads to upload individual files. The task involves hierarchical directory structure synchronization with multithreaded file uploads. | def uploadByList (drive_service, dir, node, parentId):
for file in node:
if 'content' in file:
id = createFolder (drive_service, file['name'], parentId)
uploadByList (drive_service, dir + '\\' + file['name'], file['content'], id)
print ("Updated Folder:%s(Id=%s)"%(dir + '\\' + file['name'], id))
else:
... |
def collectUploadedFiles (drive_service, folderId):
page_token = None
query='"%s" in parents' % folderId
file_service = drive_service.files ()
request = file_service.list (q=query,
spaces='drive',
fields='nextPageToken, files(id,name,mimeType)',
pageToken = page_token)
res = []
wh... | The code recursively downloads files and folders from Google Drive into a specified directory. It creates the directory if it doesn't exist, processes folders by recursively calling itself, and downloads individual files using threads. | def driveRawDownload (drive_service, nodeId, dir):
files = collectUploadedFiles (drive_service, nodeId)
if not os.path.exists (dir):
print ('There is no "%s", going to create: '%dir,end='...')
os.makedirs (dir)
print ('Created')
for file in files:
if file.get('mimeType','') == 'application/vnd.google-app... |
def readFileList (fname='.drive'):
try:
f = open (fname, 'r', encoding='utf-8')
content = f.read ()
j = json.loads (content)
except Exception as e:
print (e)
return []
return j
def createFolder (drive_service, fCollectName, fContainer):
id = checkFolderExist (drive_service, fCollectName, fContainer)
if... | The code uploads files from the current directory and a specified 'capFile' to a newly created Google Drive folder. It reads a file list, creates a root folder, logs the creation, uploads listed files to the folder, and uploads the 'capFile' to the same location. | def driveUpload (drive_service,theWrapFolderName, capFile='.drive'):
j = readFileList ()
id = createFolder (drive_service, theWrapFolderName, 'root')
log ("Folder '%s' created in root" % theWrapFolderName)
uploadByList (drive_service, '.', j['content'], id)
uploadFile (drive_service, capFile, capFile, id) |
def checkFolderExist (drive_service, fname, fContainer):
rId = ''
page_token = None
query='name = "%s" and "%s" in parents and mimeType = "application/vnd.google-apps.folder"'%(fname,fContainer)
rep = drive_service.files ().list (q=query,
spaces='drive',
fields='nextPageToken, files(id,name)... | This function downloads files from Google Drive by first checking if a specified folder exists. If found, it retrieves the folder's ID and triggers a raw download using that ID. If the folder isn't found, it raises an error. The main task is to facilitate Google Drive folder content retrieval by validating existence an... | def driveDownload (drive_service, theWrapFolderName):
id = checkFolderExist (drive_service, theWrapFolderName, 'root')
if id == '':
# log ("Folder '%s' doesn't found or wasn't been uploaded by this driver")
raise ValueError ("'%s' can not be found"%theWrapFolderName)
return -1
log ("Folder '%s' founded: id = %... |
def getRootPath ():
path = os.path.abspath(__file__)
dir_path = os.path.dirname(path)
return dir_path
def checkFolderExist (drive_service, fname, fContainer):
rId = ''
page_token = None
query='name = "%s" and "%s" in parents and mimeType = "application/vnd.google-apps.folder"'%(fname,fContainer)
rep = drive_se... | The code synchronizes files from Google Drive by checking the existence of a specified folder and a caption file ('.drive'). If both exist, it reads the caption file's JSON data to determine the target directory, adjusts it if necessary, and downloads all files from the folder to the matched directory. | def driveSync (drive_service, theWrapFolderName, defRDir = getRootPath (), defFname='.drive'):
id = checkFolderExist (drive_service, theWrapFolderName, 'root')
if id == '':
log ("No such folder with name '%s'" % theWrapFolderName)
return
capFile = checkFileExist (drive_service, defFname, id)
if capFile == '':
... |
def listFile (fPat = ['*'],ignoreSub=False):
result = {}
result ['name'] = os.getcwd ()
# print ("LF ignoreSub: ", ignoreSub)
result ['content'] = buildTree (os.walk('.'), fPat, ignoreSub=ignoreSub)
return result
def saveFileList (list, fname='.drive'):
content = __changeQuote (str(list))
try:
f = open (fn... | The code's main task is to manage file operations (uploading, downloading, listing) with Google Drive via command-line commands like 'init', 'iup', 'upload', 'download', 'rdirs', and 'sync'. It processes user inputs, interacts with Drive API using helper functions, and handles errors, while measuring execution time. | def main ():
now = time.time ()
commandList = ['init - get current directory discription', 'iup - upload with discription in .drive', 'upload - upload with default init call', 'download - download the specific uploaded folder', 'rdirs - list out uploaded folders']
if len (sys.argv) < 2:
print ('Command needed. H... |
def generate_licence(directory: Path, licence: str) -> None:
"""Generate licence file for the project.
Parameters
----------
directory : Path
Path to the project directory.
licence : str
Chosen licence.
"""
if licence is not None:
licence_origin = directory / "_licen... | The main task of the code is to generate a project's license and template files, conditionally remove unused files (CLI, Docker, GitLab, Docs) based on predefined flags, and print post-creation instructions. It uses variables like SCM_PLATFORM_LC and CREATE_* flags to determine which components to include/exclude, ensu... | def main() -> None:
REMOVE_GITLAB = SCM_PLATFORM_LC != "gitlab"
REMOVE_CLI = not CREATE_CLI
REMOVE_DOCKER = not CREATE_DOCKER
REMOVE_DOCS = not CREATE_DOCS
generate_licence(directory=PROJECT_DIRECTORY, licence=licences_dict[LICENCE])
generate_templates(directory=PROJECT_DIRECTORY, scm_platform... |
def validate_number_of_posts(page: AllPostsPage, number: int) -> None:
if not number:
assert not page.posts
else:
assert len(page.posts) == number, "invalid posts amount"
def create_post(page: AllPostsPage, content: str) -> None:
page.content = content
page.tell.click()
validate_redi... | The code tests a single user's interaction with a blog by creating, deleting, and wiping posts. It verifies post counts at each step: starting with 0, adding 1 post, deleting it, creating two more, and finally wiping all. The test ensures correct post management functionality through validation checks after each action... | def test_single_user(browser, request):
page = AllPostsPage(browser, URL_BLOG)
validate_number_of_posts(page, 0)
sign_up(page.browser)
content = "xxx"
create_post(page, content)
validate_number_of_posts(page, 1)
post = get_post(page, 0)
validate_post(post, content, True)
delete_... |
def _format_input(
self,
data,
pre_period,
post_period,
model_args,
ucm_model,
post_period_response,
alpha,
):
"""Check and format all input arguments supplied to CausalImpact().
See the documentation of CausalImpact() for details
... | The main task of the code is to execute either `_run_with_data` or `_run_with_ucm` based on input data availability. It formats parameters using `_format_input`, then dispatches to the appropriate method: `_run_with_data` if `self.data` exists, otherwise `_run_with_ucm`. This enables flexible model execution by handlin... | def run(self):
kwargs = self._format_input(
self.params["data"],
self.params["pre_period"],
self.params["post_period"],
self.params["model_args"],
self.params["ucm_model"],
self.params["post_period_response"],
self.params["alpha... |
def get_volume():
print('- get_volume')
script = """
tell application "Music"
set currentVolume to sound volume
currentVolume
end tell
"""
stdout, stderr = run_applescript(script)
print(f'-> stdout: {stdout} , stderr: {stderr}')
return stdout.strip('\n')
def set_volume(volume)... | The main task of the code is to execute music control commands (e.g., volume adjustment, playback toggling, track navigation, shuffle/repeat settings) based on input parameters, validate command structure, call corresponding functions, and return formatted status/results in [command](result) syntax. It handles errors f... | def run_cmd(cmd):
print(f'cmd: {cmd}')
if len(cmd) == 0:
return '[error](missing)'
name = cmd[0]
if name == 'get_volume':
result = get_volume()
return f'[volume]({result})'
elif name == 'set_volume':
if len(cmd) == 1:
return '[set_volume](missing)'
... |
def id_conv_string_to_int(self, val):
return int(val[1:])
def clustered_idx_tuples(self, leaf_node, rel, val, op):
res = []
content = leaf_node[LEAF_NODE["CONTENT"]]
counter = 0
related_list = []
for index, value in enumerate(content):
if isinstance(value, str... | This function performs a sequential search on an indexed data structure, recursively locating values by comparing input values with stored entries. It handles both clustered and unclustered indexes, using attribute type (IDS/NonIDS) to determine comparison logic. If a leaf node is reached, it searches content entries, ... | def seq_search(self, fname, rel, val, op, index_type=INDEX_TYPE["CLUSTERED_INDEX"], att_type=ATT_CATEGORY["NONIDS"]):
res = None
counter = 1
with open(self.index_dir + fname) as f:
info = f.readlines()[0]
data = json.loads(info)
if data[self.leaf_type_pos] == ... |
def cost_func(self, point,target):
return self.current_cost + self.heuristics_func(point,target)
def get_path(self,target):
path = []
self.VISITED.reverse()
for item in self.VISITED:
x,y = target[0]-item[0], target[1]-item[1]
d = abs(x)+abs(y)
if(d < 2... | This code implements a pathfinding algorithm using a priority queue (OPEN) to explore routes from a start point to an end point, avoiding obstacles (agent2_loc). It expands nodes, tracks visited points, and returns the path if the end is reached. If no path is found, it returns 0. | def search(self,start,end,agent2_loc):
self.OPEN.put((self.cost_func(start,end),start))
while not self.OPEN.empty():
point = self.OPEN.get()[1]
self.VISITED.append(point)
if(point == end):
return self.get_path(end)
self.expand(point,agent2_... |
def read_raw():
# load data:
# first argument: path to params.py
model = load_model(Data_folder + '/params.py')
spike_clusters = np.squeeze(np.load(Data_folder + '/spike_clusters.npy'))
spike_times = np.squeeze(np.load(Data_folder + '/spike_times.npy'))/30000 + offset
time_range = (spike_times[... | The main task of the code is to process neural spike data by loading raw data, saving spike information to CSV, extracting waveforms and templates, generating raster plots, and exporting cluster data to MATLAB format for further analysis and visualization. | def main():
model, cluster_info, cluster_df, good_clusters_id, good_spikes, spike_clusters, spike_times = read_raw()
spikes, spikes_df = save_spikes_csv(cluster_df, good_spikes, spike_clusters, good_clusters_id, spike_times)
extract_waveforms(model, cluster_info, good_clusters_id)
extract_templates(mode... |
def _write_byte(self, register, data):
"""
Write byte to specified register
:param register: byte
Address to write the byte to
:param data: byte
byte to write
:return:
Error code
"""
try:
self.i2cbus.write_byte_data(... | The code performs a factory reset on a device by sending a restore command, rebooting the device, resetting the I2C address to default, reloading settings, and returning an error code. It writes a byte to trigger the reset, reboots the device, waits briefly, updates the I2C address, reloads configuration settings, and ... | def factory_reset(self):
"""
Resets device to factory defaults
:return: int
Returns error code
"""
error = self._write_byte(TfLunaI2C.RESTORE_FACTORY_DEFAULTS, TfLunaI2C.TRUE)
self.reboot()
print("Resetting to factory defaults")
time.sleep(1)
... |
def _destroy(self):
if not self.road:
return
for t in self.road:
self.world.DestroyBody(t)
self.road = []
self.car.destroy()
def _create_track(self):
CHECKPOINTS = 12
# Create checkpoints
checkpoints = []
for c in range(CHECKPOINTS... | The main task of the code is to reset the environment's state by destroying existing elements, reinitializing tracking variables, regenerating a valid track through iterative attempts, creating a new car instance, and returning the initial observation state after resetting. This prepares the environment for a new episo... | def reset(self):
self._destroy()
self.reward = 0.0
self.prev_reward = 0.0
self.tile_visited_count = 0
self.t = 0.0
self.road_poly = []
while True:
success = self._create_track()
if success:
break
if self.verbose... |
def check_queue_status(self):
return [len(x) for x in self.queues]
def idle_process(self):
logging.info("Running idle process.")
def exec_process(self, proc, q_idx, time):
logging.info("Executing " + str(proc) + " with time slice " + str(time) + "ns")
if proc.has_io:
logging.... | The code implements a priority-based scheduler that allocates execution time to processes in the highest non-empty queue, iteratively reducing remaining scheduled time until it falls below the next time slice. It checks queue statuses, handles idle states when all queues are empty, and adjusts execution time dynamicall... | def run(self, sched_time):
logging.info("Running scheduler for " + str(sched_time) + "ns")
exec_time = self.priority_time_slices[self.current_queue] # time allocated to exec
# run the scheduler as long as the remaining time is greater than the next
# time slice, then cease
... |
def produceData(self):
"""
Returns:
various -- deterministic data in case there is scenario random data if there is not.
"""
if(self.scenario != None):
return self.getOutputFromScenario()
else:
return self.produceRandomData()
def getRawStatus(s... | The main task of the code is to generate data, convert it to a JSON string using UTF-8 encoding, send it to a HealthMonitor via socket, and update history and status files. It retrieves raw status data, serializes it, transmits it to a monitoring system, and logs the data in files for tracking and record-keeping. | def sendData(self):
"""This sends data to HealthMonitor.
The data sent are the same as the output of getStatus().
Encoding is utf-8
"""
# random data generation
self.lastData = self.produceData()
# return data as JSON string
d = self.getRawStatus()... |
def get_address_of_variable(var_name):
global RAM_ADDRESS
var_name = var_name.strip()
if not isVariableInRAM(var_name):
variables_address_mapping[var_name] = RAM_ADDRESS
RAM_ADDRESS += 1
return int(variables_address_mapping[var_name])
def isVariableInRAM(value):
return value in var... | This function assigns a value to a variable in RAM by generating code. It checks if the value is a number or another variable. If numeric, it directly sets the RAM address. If another variable, it retrieves its address, copies the value to a temporary register, then assigns it to the target variable's address in RAM. | def write_assignment(var_name, value):
global code
address = get_address_of_variable(var_name)
value = value.strip()
print("WriteAssignmentFunc:")
print(value)
print("is var in ram:")
print(isVariableInRAM(value))
print(variables_address_mapping)
# value can not only be number but ... |
def get_address_of_variable(var_name):
global RAM_ADDRESS
var_name = var_name.strip()
if not isVariableInRAM(var_name):
variables_address_mapping[var_name] = RAM_ADDRESS
RAM_ADDRESS += 1
return int(variables_address_mapping[var_name])
def isVariableInRAM(value):
return value in var... | This function generates assembly-like code to perform addition or subtraction operations on two variables or constants, storing the result in a specified memory location. It handles cases where both operands are in RAM, one is a constant, or both are constants, using ALU operations to compute and store the result. | def write_add_sub_assignment(result_var_name, var1, var2, operator):
global code
# Only if both the vars are another vars in memory.
result_address = get_address_of_variable(result_var_name)
var1 = var1.strip()
var2 = var2.strip()
op = 0
if operator == "+":
op = 0
if operator ==... |
def get_address_of_variable(var_name):
global RAM_ADDRESS
var_name = var_name.strip()
if not isVariableInRAM(var_name):
variables_address_mapping[var_name] = RAM_ADDRESS
RAM_ADDRESS += 1
return int(variables_address_mapping[var_name])
def isVariableInRAM(value):
return value in var... | This function generates assembly-like code to perform a logical AND or OR operation between two variables or constants, storing the result in a specified memory address. It checks whether the input variables are stored in RAM or are constants, then loads their values into temporary registers, applies the operation, and... | def write_and_or_assignment(result_var_name, var1, var2, operator):
global code
# Only if both the vars are another vars in memory.
result_address = get_address_of_variable(result_var_name)
var1 = var1.strip()
var2 = var2.strip()
op = 0
if operator == "&":
op = 0
if operator == ... |
def isVariableInRAM(value):
return value in variables_address_mapping.keys()
def get_address_of_variable(var_name):
global RAM_ADDRESS
var_name = var_name.strip()
if not isVariableInRAM(var_name):
variables_address_mapping[var_name] = RAM_ADDRESS
RAM_ADDRESS += 1
return int(variabl... | This function generates machine code for conditional assignments based on variable locations. It checks if variables are in RAM or constants, loads them into registers A/B, and applies logical operations. The code dynamically constructs instructions to handle different scenarios: both variables in RAM, one in RAM and o... | def write_conditional_assignment(var1, var2, operator):
global code
# Only if both the vars are another vars in memory.
var1 = var1.strip()
var2 = var2.strip()
# every operators result is calculated at once in their own register's.
op = 0
isVar1_var_in_ram = isVariableInRAM(var1)
isVar2... |
def check_variable_validity(var1, var2):
var1 = var1.strip()
var2 = var2.strip()
# A variable in RAM or a numeric constant is valid.
isVar1Valid = isVariableInRAM(var1) or is_number(var1)
isVar2Valid = isVariableInRAM(var2) or is_number(var2)
if not isVar1Valid:
print("Stack:")
... | This function generates assignment statements based on the operator type. It validates variables, checks the operator (+,- for arithmetic; &,| for logical; >,<, : for conditional), and delegates to specific helper functions to write the corresponding assignment code. | def write_arithmatic_assignment(result_var_name, var1, var2, p_op):
result_var_name = result_var_name.strip()
var1 = var1.strip()
var2 = var2.strip()
p_op = p_op.strip()
check_variable_validity(var1, var2)
if p_op == "+" or p_op == "-":
print("Add Sub Operator")
write_add_sub_a... |
def write_add_sub_assignment(result_var_name, var1, var2, operator):
global code
# Only if both the vars are another vars in memory.
result_address = get_address_of_variable(result_var_name)
var1 = var1.strip()
var2 = var2.strip()
op = 0
if operator == "+":
op = 0
if operator ==... | This function determines the type of operation (arithmetic, logical, or conditional) based on the input operator `p_op`, then delegates to specific helper functions to generate corresponding assignments. It first strips whitespace from inputs, prints the operator for debugging, and routes the task to `write_add_sub_ass... | def write_arithmatic_assignment(result_var_name, var1, var2, p_op):
result_var_name = result_var_name.strip()
var1 = var1.strip()
var2 = var2.strip()
p_op = p_op.strip()
print(p_op)
if p_op == "+" or p_op == "-":
print("add_sub_op")
write_add_sub_assignment(result_var_name, var1... |
def create_padding_mask(self, x: torch.Tensor):
return ~(x == self.pad_token_id)[:, None, None, :]
def encoder(self, x: torch.Tensor, padding_mask: torch.Tensor) -> torch.Tensor:
outputs = self.pos_encode(x)
for i in range(self.num_layers):
outputs = self.enc_layers[i](outputs, padd... | The code processes encoder and decoder inputs with padding masks, passing encoder outputs to the decoder, then generates final outputs via a dense layer, typical in sequence-to-sequence models like transformers. | def forward(self, enc_x: torch.Tensor, dec_x: torch.Tensor) -> torch.Tensor:
enc_padding_mask = self.create_padding_mask(enc_x)
enc_outputs = self.encoder(enc_x, enc_padding_mask)
dec_padding_mask = self.create_padding_mask(dec_x)
dec_outputs = self.decoder(dec_x, enc_outputs, dec_paddin... |
def r(x):
return sub(b,mult_A(x))
def sub(u,v):
sub=u.copy()
for i in range(len(u)):
sub[i] -= v[i]
return sub
def mult_c(c,v):
vect=v.copy()
for i in range(len(v)):
vect[i] *= c
return vect
def prod(u,v):
return prod_std(u,mult_A(v)) | The main task of the code is to compute the orthogonal projection of the gradient vector `grad` onto the subspace spanned by the vectors in `prev`, using a Gram-Schmidt-like process. It subtracts components of `grad` aligned with each vector in `prev`, normalizing by their squared magnitudes, and returns the resulting ... | def getp(x,prev):
grad=r(x)
p=grad.copy()
for i in range(len(prev)):
p=sub(p, mult_c(prod(prev[i],grad)/prod(prev[i],prev[i]),prev[i]))
return p |
def locb(i,j):
global h
global k
n=N*i+j
x=x0+(i+0.5)*h
y=y0+(j+0.5)*k
val=(0.6)**0.5
INT=[0]*4
for p in range(4):
INT[p] += 25*(P(-val,-val,p)*F(x-val*h/2,y-val*k/2)+P(val,-val,p)*F(x+val*h/2,y-val*k/2)+P(-val,va... | The code modifies the matrix A and vector b by applying boundary conditions to a grid. It iterates over each grid point (i,j), computes indices for neighboring points, and updates b with contributions from locb() or loc() functions. For non-boundary points, it subtracts values derived from the function g(x,y,time) and ... | def setMatrix():
for i in range(M):
for j in range(N):
n=i*(N-1)+j
temp=locb(i,j)
point1=[n-N, n-1, n, n-N+1]
for p in range(4):
if not boundary(i+pos[p][0], j+pos[p][1]):
b[point1[p]] += temp[p]
for... |
def r(x):
return sub(b,mult_A(x))
def getp(x,prev):
grad=r(x)
p=grad.copy()
for i in range(len(prev)):
p=sub(p, mult_c(prod(prev[i],grad)/prod(prev[i],prev[i]),prev[i]))
return p
def prod_std(u,v):
count=0
for i in range(len(u)):
count += v[i]*u[i]
return count
def prod(u... | The code implements an optimization algorithm to minimize a function by iteratively adjusting the vector x. It uses gradient descent with a direction vector p, updating x until the squared gradient norm falls below a threshold (mindiff). The loop computes the gradient, determines the search direction, calculates a step... | def solve(mindiff):
prev=[]
x=[0]*((M-1)*(N-1))
for i in range((M-1)*(N-1)):
grad=r(x)
p=getp(x,prev)
if prod_std(grad,grad) <mindiff:
return x
prev.append(p)
a=prod_std(p,grad)/prod(p,p)
x=sub(x,mult_c(-a,p))
return x |
def decodeDNSQuery(data: bytearray, offset) -> tuple[dNSQuery, int]:
pointer = offset
domain_name, pointer = dNSDomainNameReaderWithCompression(data, pointer)
query_type = lookUpInDict(dNSRecordTypeLookup, data[pointer : pointer + 2].hex())
query_class = lookUpInDict(
dNSRecordClassLookup, data[... | This function decodes DNS response records from a bytearray, parsing queries, answers, authority servers, and additional records based on given counts. It uses helper functions to extract each section, updates a pointer for data navigation, and organizes results into a structured dictionary with labeled lists. The main... | def decodeDNSRecords(data: bytearray, que: int, ans: int, auth: int, add: int):
result = {
"Queries": [],
"Answers": [],
"Authority Servers": [],
"Additional Records": [],
}
pointer = 0
for i in range(que):
query, npointer = decodeDNSQuery(data, pointer)
... |
def hex_to_binary(hex_string):
binary_string = ""
hex_to_bin_mapping = {
"0": "0000",
"1": "0001",
"2": "0010",
"3": "0011",
"4": "0100",
"5": "0101",
"6": "0110",
"7": "0111",
"8": "1000",
"9": "1001",
"A": "1010",
... | The main task of the code is to decode segmented DNS data into a structured dictionary. It extracts fields like Transaction ID, Flags (converted from hex to binary and decoded), and record counts, then processes DNS records (queries, answers, authorities, etc.) using `decodeDNSRecords`, returning a comprehensive parsed... | def decodeDNSData(data: segmentedDNSData):
result = {}
result["Transaction ID"] = data["Transaction ID"]
original_hex: str = data["Flags"]
binary_representation: str = hex_to_binary(original_hex)
result["Flags"] = decodeFlag(binary_representation)
result["Questions"] = data["Questions"]
resu... |
def get_data():
client = Cloudant.iam(CLOUDANT_ACCOUNT_NAME, CLOUDANT_API_KEY, connect=True)
kmeans_train = client['kmeans_train']
ar = []
for doc in kmeans_train:
ar.append([doc['x'], doc['y']])
return np.array(ar)
def randomly_initialize_centers(points,k):
return points[np.random.rand... | The main task of the code is to perform k-means clustering on data retrieved from a Cloudant database. It initializes centroids randomly, iteratively updates them by assigning data points to the nearest centroid and recalculating cluster centers, and prints centroid states after each iteration. The final centroids are ... | def main(dict):
global CLOUDANT_ACCOUNT_NAME
CLOUDANT_ACCOUNT_NAME = dict['CLOUDANT_ACCOUNT_NAME']
global CLOUDANT_API_KEY
CLOUDANT_API_KEY = dict['CLOUDANT_API_KEY']
k = dict['k']
it = dict['iterations']
print("Try to find", k, "clusters with", it, "iterations")
print("Get Data from Dat... |
def preprocess(points):
n = len(points)
x = 30.0*np.sqrt(2)
for i in points:
i[0]+=15
i[0]/=x
i[1]+=15
i[1]/=x
return points
def initialize_centers_randomly(k):
result = [[0,0],[0,0],[0,0]]
for i in range(k):
result[i] = [random.uniform(0,1), random.unifor... | The code performs k-means clustering on a set of 2D points. It initializes random centroids, iteratively assigns points to the nearest centroid, recalculates centroids based on cluster means, and repeats this process for a specified number of iterations. The final centroids after all iterations are returned as the resu... | def main(dict):
k = dict['k']
iterations = dict['iterations']
points = [[2.83074041, -3.40417462], [-1.88863985, 7.40552553], [1.31045817, -6.57269896], [-11.07281298, -5.93492344], [-2.42570216, 7.76584962]]
points = preprocess(points)
centroids = initialize_centers_randomly(k)
# run k-means a... |
def process_action(self, action):
"""Processes user input based on the current state of the coffeemachine. There are 5 options:
buy, fill, take, show remaining ingredients, exit.
:arg: action (str): user's inputted action
:returns: none"""
if action == "buy":
print("W... | The code processes user input based on the machine's current state. If in "waiting_for_action," it triggers an action; if in "choosing_coffee," it selects a coffee type and transitions to waiting; if in "filling," it prompts for supplies and returns to waiting. The function manages state transitions and delegates tasks... | def process_input(self, user_input):
"""Processes user input based on the current state of the machine
(such as waiting for action, choosing coffee type or being filled)
:argument: user_input (str): user's input
:returns: none"""
if self.state == "waiting_for_action":
... |
def f(x,a,b):
return (x[0]-x[1]**2)**2 + (a-x[0])**2 + b
def is_pos_def(x):
return np.all(np.linalg.eigvals(x) > 0)
def fib_search(f, bounds, tol, coef, max_eps = 0.01):
a = bounds[0]
b = bounds[1]
tol = 0.0007
N = 0
F_B = (b - a) / tol
F_N = 0
while F_N < F_B:
N += 1
... | (The function implements Newton's method to minimize a function $ f $ with parameters $ a, b $, using gradient $ df $ and Hessian $ H $. It iteratively computes the Newton step when the Hessian is positive definite or applies a line search with gradient descent otherwise. The algorithm stops when the gradient norm fall... | def newton_method(f, df, H,a,b, x0, M, t0, eps1, eps2):
x = x0.copy()
grad = np.array([df[0](x, a, b), df[1](x, a, b)])
stop_check = False
for i in range(M):
#print('i:', i)
#print(' x:', x, f(x, a ,b))
#print(' grad:', np.linalg.norm(grad))
if np.linalg.norm(grad) ... |
def read_input_file(file_path: str) -> str:
"""Read input file without splitting its lines."""
with open(file_path, "r", encoding="utf-8") as file_descriptor:
return file_descriptor.read().strip()
def parse_lists_pairs(input_str: str) -> List[Tuple[list, list]]:
"""Parse input into a list containing... | The code processes input data to solve two tasks: (1) Calculate the sum of indexes for ordered list pairs by comparing each pair's order, and (2) Compute a decoder key by identifying the positions of two specific divider packets in a sorted list of all packets. The results are printed as the sum of ordered indexes and ... | def main():
"""Resolve the problem."""
input_str = read_input_file(INPUT_FILE_PATH)
lists_pairs = parse_lists_pairs(input_str)
n_ordered_lists = count_ordered_lists(lists_pairs)
lists_unsorted = join_lists_with_divider_packets(input_str)
decoder_key = compute_decoder_key(lists_unsorted)
p... |
def create_game(self):
"""
create the game
"""
if isinstance(self.player_one, Human) or isinstance(self.player_two, Human):
self._print_message("Welcome to a game of tic tac toe")
print("Select a starting field (0-8)\n")
print(" 0 | 1 | 2 \n---+---+--... | The code's main task is to play a game by initializing the game state, handling turns based on player types (QPlayer vs Human), and determining the winner. If the initial player is a QPlayer and the opponent is Human, it executes an immediate turn. Otherwise, it loops until the game ends. The winner is set based on the... | def play(self):
"""
Play the game
"""
# opening message
self.create_game()
if isinstance(self.player_one, QPlayer) and isinstance(self.player_two, Human):
initial_selection = self.player_one.get_field(self.board)
self.perform_turn(initial_selecti... |
def BC_proxy_fit(X_train,Y_train,X_val,Y_val,args):
# grid search fitting models on training set using a fixed validation set
n_features = X_train.shape[1]
if args.algorithm=='SVR':
print(f'---------------\nFitting {args.algorithm}\n----------------')
grid_params = {
'model_... | The main task of the code is to train a machine learning model using a training set and validation set (no cross-validation), perform hyperparameter tuning via grid search if specified, evaluate the model on training and test sets, and save results. It uses `BC_proxy_fit` for hyperparameter optimization and `BC_proxy_m... | def main(ds,args,training_path,results_path):
"""
Fit a ML algorithm
The object data set already has a training and validation set.
The first column is the target and the others are the predictors
NO CROSS VALIDATION BUT A VALIDATION SET
"""
df_train = ds.train_set_scaled
df_val = d... |
def _generate_true_scores(self, seed):
"""
Generate true scores for simulated dataset.
This method simulates true scores based on the pre-defined
mean and standard deviation. The scores are sampled from the
normal distribution defined by ``train_score_mean`` and
``train_... | The main task of the code is to generate simulated true, rater, and system scores along with metadata. It first creates true scores using a seed value, then generates rater scores and metadata if they don't exist or if forced, followed by system scores and metadata under similar conditions. Each generation step uses di... | def generate(self):
"""
Generate the simulated true, rater, and system scores.
This method generates the simulated true scores, generates the
simulated rater scores (and metadata), and generates the simulate
system scores (and metadata).
"""
# first generate the ... |
def clear_terminal():
os.system('cls' if os.name == 'nt' else 'clear')
def computer_take_bet(chips: Chips):
if chips.money >= 100:
chips.bet = 50
chips.money -= 50
elif chips.money >= 50 < 100:
chips.bet = 25
chips.money -= 25
elif chips.money > 10 < 50:
chips.bet... | The code implements a Blackjack game where the user can play as either a player or dealer, managing bets, card dealing, and game logic. It handles player turns (hit/stand), dealer behavior (hitting until 17), and determines outcomes (win/loss/tie) based on hand values. The game continues until the player runs out of mo... | def play():
# the game
# flags for game states
is_playing = True
is_continue = True
is_drawing_card = True
while is_playing:
# reset them to true if they were false and started a new game
is_continue = True
is_drawing_card = True
clear_terminal()
# get i... |
def left_left(self, node):
return self.right_rotation(node)
def left_right(self, node):
node.left = self.left_rotation(node.left)
return self.left_left(node)
def right_right(self, node):
return self.left_rotation(node)
def right_left(self, node):
node.right = self.right_rotation(... | This function balances an AVL tree node by checking its balance factor (BF). If BF is -2 or 2, it performs rotations (left-left, left-right, right-right, right-left) to restore balance and returns the new root. If BF is within [-1, 1], it returns the node unchanged. | def balance(self, node) -> Node:
if node.BF == -2:
if node.left.BF <= 0:
return self.left_left(node)
else:
return self.left_right(node)
if node.BF == 2:
if node.right.BF >= 0:
return self.right_right(node)
... |
def update(self, node):
lh, rh = -1, -1
if node.left is not None:
lh = node.left.height
if node.right is not None:
rh = node.right.height
node.height = 1 + max(lh, rh)
node.BF = rh - lh
def balance(self, node) -> Node:
if node.BF == -2:
... | This function inserts a value into a binary tree node recursively, adjusting left or right children based on value comparison. After insertion, it updates the node's properties and balances the subtree to maintain AVL tree structure, returning the balanced node. | def _insert(self, node, value) -> Node:
if node == None:
return Node()
if node.value < value:
node.left = self._insert(node.left, value)
elif node.value > value:
node.right = self._insert(node.right, value)
self.update(node)
... |
def dig_left(self, node):
curr = node
while curr.left != None:
curr = curr.left
return curr
def update(self, node):
lh, rh = -1, -1
if node.left is not None:
lh = node.left.height
if node.right is not None:
rh = node.right.height
... | This function recursively removes a node with the specified value from a binary tree. It handles three cases: when the node has no children (returns the child), one child (returns that child), or two children (replaces the node with the leftmost node of its right subtree and removes that node). After deletion, it updat... | def _remove(self, node, value) -> Node:
if node is None:
return None
if node.right.value < value:
node.left = self._remove(node.left, value)
elif node.left.value > value:
node.right = self._remove(node.right, value)
else: # n... |
def applicable_options(s, all_cubes):
result = []
for cube in all_cubes:
pick_up_preconds = operators.pick_up_preconditions(s, cube)
put_down_preconds = operators.put_down_preconditions(s, cube)
if type(pick_up_preconds) == list:
result.append((operators.pick_up, (s, cube), ... | This function updates a delta table by applying positive effects of applicable actions to a state's universe (U). It iterates through possible actions, computes their effects, updates U with new elements, and adjusts delta_table entries for each new effect. The delta values are minimized based on preconditions and effe... | def update_delta_2(s, delta_table, U, all_cubes):
result = delta_table.copy()
options = applicable_options(U, all_cubes)
for action_function, action_args, actions_preconds in options:
positive_effects = action_function(*action_args, just_positive=True)
before_len = len(U)
U += positi... |
def initialize_delta_table(s, all_cubes):
s = tuple(s)
result = create_all_p(s, all_cubes)
level_2_result = {}
for k, v in result.items():
for k1, v1 in result.items():
temp_list = [k[1]]
if k1[1] != k[1]:
temp_list.append(k1[1])
if (s, tu... | The code iteratively updates a delta table using `update_delta_2` until it stabilizes, then computes and returns the goal distance between states `s` and `g` based on the stabilized table. It initializes the table, tracks iterations, and halts when consecutive updates yield identical results, ensuring convergence befor... | def delta_2(s, g, all_cubes):
initial_data_table = initialize_delta_table(s, all_cubes)
U = s.copy()
counter = 1
while True:
new_U, new_result = update_delta_2(s, initial_data_table, U, all_cubes)
counter += 1
if initial_data_table == new_result:
goal_distance = get_s... |
def satisfies(s, g):
for goal_atom in g:
if goal_atom not in s:
return False
return True
def applicable_options(s, all_cubes):
result = []
for cube in all_cubes:
pick_up_preconds = operators.pick_up_preconditions(s, cube)
put_down_preconds = operators.put_down_precon... | The function `heuristic_forward_search` explores paths from an initial state `s` to a goal `g` using a heuristic that selects actions minimizing a `delta_2` metric, which measures progress toward the goal. It avoids revisiting states via `seen_states`, recursively applies actions, and returns a valid plan (`pi`) if the... | def heuristic_forward_search(pi, s, g, all_cubes, seen_states):
s = sorted(s)
stuple = tuple(s)
if stuple in seen_states:
return False
seen_states.add(tuple(s))
print('len(seen_states):', len(seen_states))
show_state(s)
if satisfies(s, g):
return pi
# options = actions
... |
def calculate_tf_idf_of_docs_field(query):
query = query.lower()
field_dict = get_field_list(query)
field_results = []
docs = {}
for key in field_dict.keys():
key_list = []
lst = field_dict[key]
for word in lst:
word = Pstemmer.stem(word)
posting = get... | The main task of the code is to process a search query by calculating TF-IDF scores for documents, either field-specific (if the query contains a colon) or general. It sorts documents by their TF-IDF scores in descending order and returns the titles of the top-ranked documents using the `get_titles` function. | def search_helper(query):
dict_={}
if ":" in query:
dict_ = calculate_tf_idf_of_docs_field(query)
else:
dict_ = calculate_tf_idf_of_docs_normal(query)
sorted_x = sorted(dict_.items(), key=lambda kv: kv[1],reverse=True)
return get_titles([a[0] for a in sorted_x]) |
def sendLogoutToServer(self):
temp_pickle_string = pickle.dumps(self.local_user)
self.client_socket.send("EXIT".encode())
self.client_socket.send(temp_pickle_string)
def handleAdd(self):
name = input(' Enter Full Name: ')
email = input(' Enter Email Address: ')
# ensure... | This code implements a command-line UI for a secure file transfer application. It processes user commands like adding contacts, listing online contacts, sending/receiving files, and exiting. The 'send' command requires a contact and file path, with validation for insufficient arguments. It interacts with server methods... | def handleUI(self):
while True:
data = input("secure_drop> ").split(' ')
choice = data[0].lower()
if len(data) > 1:
args = data[1:]
if choice == "help":
print(' "add" -> Add a new contact')
print(' "list" -> List a... |
def createUser(self):
name = input('Enter Full Name: ')
email = input('Enter Email Address: ')
password = pwinput.pwinput()
reenter = pwinput.pwinput('Re-enter Password: ')
if password != reenter:
print("Passwords Do Not Match.")
else:
print("Passw... | The main task of the code is to initiate a client application by checking for user registration, connecting to a server, authenticating via login, and launching the user interface. It handles user registration if none exists, establishes a socket connection, sends login credentials, and transitions to the interactive U... | def startClient(self):
if self.local_user is None:
create = input('No users are registered with this client.\nDo you want to register a new user (y/n)? ').lower()
# only do anything if the user inputs yes
if create == 'y':
self.createUser()
print("... |
def extract_features(x, style_layers,net,ctx,in_size = 224):
B,C,H,W = x.shape
Img = (x + 1.0)*127.5
Img_chanells = [nd.expand_dims(Img[:,i,:,:],axis=1) for i in range(3)]
Img_chanells[0] = (Img_chanells[0]/255 - 0.485)/ 0.229 #subtracted by [103.939, 116.779, 123.68]
Img_chanells[1] = (Img_ch... | The code trains a GAN (Generative Adversarial Network) for image-to-image translation, using adversarial loss (GAN), L1 reconstruction loss, and perceptual/style losses derived from VGG features. It alternates between updating the discriminator and generator, employs an image pool for historical samples, and adjusts le... | def train(args):
use_gpu = args.gpu
ctx = mx.gpu(0) if use_gpu else mx.cpu()
pool_size = 50
lambda1 = 100
img_wd = args.img_size
img_ht = args.img_size
style_layers = [4,9,16]
my_train = MyDataSet(args.trainset_path, '')
train_loader = DataLoader(my_train, batch_size=args.batch_size,... |
def remove(self):
""" Delete the service if it exists """
logger.debug("Removing existing %s service.", self.service_name)
_reset_failed = "systemctl reset-failed"
_stop = "systemctl stop " + self.service_name
self.disable()
actions.run_subprocess([_stop])
self.service_path.unlink(missing_ok=True)
lib_... | The main task of the code is to create a systemd service by generating a service file, setting permissions, enabling, and starting the service. It checks for existing services, removes them if present, executes necessary commands, and returns True if the service starts successfully, otherwise False with error logging. | def create(self) -> bool:
""" Create a systemd service """
_start = "systemctl start " + self.service_name
_enable = "systemctl enable " + self.service_name
_chmod = "chmod " + str(self.service_mode) + " " + str(self.service_path)
_exists = "systemctl list-unit-files | grep " + self.service_name
_service = ... |
def train_load(self, base_dir):
self.base_dir = os.path.join(base_dir, "training_set")
self.idx_to_name = []
self.idx_to_label = []
self.name_to_idx = defaultdict(list)
meta = json.load(open(os.path.join(self.base_dir, "bb.json"), 'r'))
names = json.load... | This code initializes a data loader for image processing tasks, setting parameters like batch size, image dimensions, and mode (train/valid/test). It configures data loading strategies based on the 'train_extractor' type (triplet, pair, single) and loads corresponding datasets. The class prepares aligned images, rectan... | def __init__(self,
base_dir,
batch_size=16, H=128, W=128,
mode='train', train_extractor='triplet',
lazy=False, device='cpu'
):
super().__init__()
self.lazy = lazy
# The amount of positive/negative p... |
def execute(self):
# self.operation is referring to the the operation we are going to do
if (self.operation == "add" or self.operation == "and" or self.operation == "or" or self.operation == "sll"):
self.executeMuskan(self.operation, self.rs1, self.rs2, self.rd)
elif (self.operatio... | This function handles pipeline stalling in a CPU simulation by managing instruction fetching, decoding, and execution stages. It updates register arrays, tracks branch instructions, adjusts the program counter (PC) for jumps, and increments cycle counters. Special handling for branch formats (sb) ensures correct PC adj... | def stalling_case3(self):
self.stalling1 = False
if (len(self.rd_array1) == 2):
self.rd_array2.append(self.rd_array1[0])
if (len(self.rd_array2) == 2):
self.rd_array2.pop(0)
self.rd_array1.pop(0)
if (len(self.rd_array2) == 2):
self.... |
def execute(self):
# self.operation is referring to the the operation we are going to do
if (self.operation == "add" or self.operation == "and" or self.operation == "or" or self.operation == "sll"):
self.executeMuskan(self.operation, self.rs1, self.rs2, self.rd)
elif (self.operatio... | This function handles data forwarding in a pipeline processor by checking for register hazards between stages, updating pipeline buffers (rd_array1/rd_array2), and managing instruction execution stages (fetch, decode, execute). It tracks data hazards, classifies instruction types (load/store, control, ALU), updates the... | def data_forwarding_case1(self):
if (self.rd_array1[0] == self.rs1): # data_forwarding
self.rs1_bool = True
self.rs1_a = pipelining.jot
self.data_hazards += 1
if (self.rd_array1[0] == pipelining.rs2):
self.rs2_bool = True
self.rs2_b = self.jot... |
def execute(self):
# self.operation is referring to the the operation we are going to do
if (self.operation == "add" or self.operation == "and" or self.operation == "or" or self.operation == "sll"):
self.executeMuskan(self.operation, self.rs1, self.rs2, self.rd)
elif (self.operatio... | This method handles data forwarding by checking register matches (rd_array1[0] with rs1/rs2), increments data hazards when matches occur, manages instruction execution/decode/fetch stages, updates PC based on control flow (branch instructions), counts different instruction types (DT, control, ALU), and adjusts PC for b... | def data_forwarding_case2(self):
if (self.rd_array1[0] == self.rs1): # data_forwarding
self.rs1_bool = True
self.rs1_a = self.jot
self.data_hazards += 1
if (self.rd_array1[0] == self.rs2):
self.rs2_bool = True
self.rs2_b = self.jot
... |
def execute(self):
# self.operation is referring to the the operation we are going to do
if (self.operation == "add" or self.operation == "and" or self.operation == "or" or self.operation == "sll"):
self.executeMuskan(self.operation, self.rs1, self.rs2, self.rd)
elif (self.operatio... | This function manages data forwarding in a pipelined CPU by handling register array operations (rd_array1/rd_array2), updating the program counter (PC) based on instruction execution stages, and categorizing instruction types (ALU, data transfer, control). It processes instruction fetching, decoding, execution, and bra... | def data_forwarding_case3(self):
if (len(self.rd_array1) == 2):
self.rd_array2.append(self.rd_array1[0])
if (len(self.rd_array2) == 2):
self.rd_array2.pop(0)
self.rd_array1.pop(0)
if (len(self.rd_array2) == 2):
self.rd_array2.pop(0)
... |
def R_Format(binaryInstruction, PC): # MUSKAN GUPTA 2019CSB1100
# add, and, or, sll, slt, sra, srl, sub, xor, mul, div, rem
funct7 = binaryInstruction[0:7]
rs2 = binaryInstruction[7:12]
rs1 = binaryInstruction[12:17]
funct3 = binaryInstruction[17:20]
rd = binaryInstruction[20:25]
opcode = b... | The code decodes a 32-bit binary instruction by extracting the opcode (bits 25-32) and categorizing it into instruction formats (R, I, S, SB, U, UJ). Depending on the opcode, it calls corresponding formatting functions (e.g., R_Format, I_Format) to process the instruction. The program counter (PC) is updated based on t... | def decode(binaryno, PC):
opcode = binaryno[25:32]
R_oper = ["0110011"]
I_oper = ["0010011", "0000011", "1100111"]
S_oper = ["0100011"]
SB_oper = ["1100011"]
U_oper = ["0110111", "0010111"]
UJ_oper = ["1101111"]
if opcode in R_oper:
# decode
R_Format(binaryno,... |
def create_board() -> List[List[str]]:
"""create and return a 3X3 Tic-Tac-Toe board"""
return [[" " for _ in range(3)] for _ in range(3)]
def print_board(board: List[List[str]]) -> None:
"""prints the Tic-Tac-Toe Board"""
for row in board:
print("|".join(row))
print("----")
def is_game_o... | The code implements a Tic-Tac-Toe game where a human player ('x') competes against an AI ('0'). It initializes the board, alternates turns, validates moves, checks for wins, and declares outcomes. The AI selects optimal moves via find_best_move, while the human inputs coordinates. The loop continues until a win or tie,... | def play_game() -> None:
""" Main function"""
board = create_board()
current_player= 'x'
print_board(board)
while not is_game_over(board):
if current_player == 'x':
row , col = map(int, input("Enter row and col (0,2) seperated by space: ").split())
else: #AI's turn
... |
def buildPath(path):
if not os.path.exists(path):
os.mkdir(path)
def list_images(dir):
images = []
if os.path.isdir(dir):
files = os.listdir(dir)
for fname in files:
if is_image_file(fname):
images.append(os.path.join(dir,fname))
else:
if os.pa... | The code loads pre-trained models for emotion and facial expression analysis, processes input images to detect landmarks, estimates expression priors using either FAC features or emotion-based inference, generates 3D facial reconstructions, and outputs texture maps, displacement maps, and normal maps. It supports both ... | def main(args):
global BFMexp,dictionaryFAC,dictionaryEmotion
if args.emotion:
from keras.models import Model
from keras.models import model_from_json
json_file = open(args.json_file, 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model... |
def get_flex_index(lineup_indexes):
"""
Return the flex index
"""
for i in lineup_indexes['RB']:
if FLEX['name'][lineup_indexes['FLEX'][0]] == RBS['name'][i]:
lineup_indexes['FLEX'][0] += 1
return get_flex_index(lineup_indexes)
for i in lineup_indexes['WR']:
... | The code generates the next set of player indexes for a sports lineup by identifying the least valuable players using a comparator, removing them, and replacing their indexes with the next available index for each position (QB, RB, WR, TE, FLEX, DEFS), ensuring indices stay within valid bounds. | def get_new_lineup_indexes(lineup_indexes, comparator):
"""
Return the indexes for the next lineup
"""
flex_lineup = {
'QB': lineup_indexes['QB'],
'RB': lineup_indexes['RB'],
'WR': lineup_indexes['WR'],
'TE': lineup_indexes['TE'],
'FLEX': [lineup_indexes['FLEX'][0... |
def get_position(player_list, index):
"""
Shortcut function to return the lineup position dict
"""
return {
'name': player_list['name'][index],
'salary': player_list['salary'][index].item(),
'points': player_list['points'][index],
'ceiling': player_list['ceiling'][index],... | The function `create_lineup` constructs a sports lineup by selecting players based on given indexes, aggregates their statistics (cost, points, projections), and ensures the total salary does not exceed a maximum limit. If the salary exceeds the threshold, it recursively generates a new lineup using a comparator. The f... | def create_lineup(lineup_indexes, comparator):
"""
Create a valid lineup
"""
lineup = {
'players': {
'qb': get_position(QBS, lineup_indexes['QB'][0]),
'rb1': get_position(RBS, lineup_indexes['RB'][0]),
'rb2': get_position(RBS, lineup_indexes['RB'][1]),
... |
def add_point_per_dollar(dataframe):
"""
Add the points per salary values
"""
dataframe['ceiling_per_salary'] = (dataframe['ceiling']*1000)/dataframe['salary']
dataframe['floor_per_salary'] = (dataframe['floor']*1000)/dataframe['salary']
dataframe['points_per_salary'] = (dataframe['points']*1000... | The main task of the code is to generate and save the projected best NFL lineups for fantasy sports (DraftKings/FanDuel) based on statistical metrics like points, ceiling, and floor per salary. It reads position-specific CSV data, sorts players by salary and a custom key, combines position groups (FLEX), creates optimi... | def main(argv):
"""
Write the Projected best lineup
"""
global QBS, RBS, WRS, TES, FLEX, DEFS, SITE
output_file_name, ending, key = '', '', ''
try:
opts, args = getopt.getopt(argv, "hs:e:o:k:", ["site="])
except getopt.GetoptError:
print('write-projections.py -s <Site | Dr... |
def _random_flag(prob):
return np.random.uniform(0, 1) < prob
def add_reverberation(signal):
room = random.choices([
"small_absorbent",
"small_reflective",
"medium_absorbent",
"medium_reflective",
"large_absorbent",
"large_reflective",
], [0.2, 0.2, 0.2, 0.2, ... | This function applies audio augmentations to a waveform with predefined probabilities, including polarity inversion, noise addition, reverb, clipping, etc. It ensures the output is normalized and in float32 format, tracking applied augmentations if requested. Augmentations are applied conditionally based on probabiliti... | def wave_augmentation_func(wave, return_name=False):
global augmentations
old_shape = wave.shape
augmentations = []
probabilties = {
"polarity_inversion": 0.1,
"real_noise": 0.2,
"reverb": 0.2,
"resample": 0.001, # slow, so we don't use it often
"telephone": 0.2,
... |
def split_dataset(self, X, y):
num_test = int(self.validation_set_percentage * len(y))
# Shuffle the data (for turb or synt we dont need this but it can be helpfull for other datasets)
indices = np.random.permutation(len(y))
# Split the data
X_train = X[indices[num_test:]]
... | This code trains a neural network using backpropagation. It initializes weights/thresholds, iterates through epochs, processes training patterns via forward propagation, back-propagates errors, updates parameters, and tracks training/validation quadratic errors. The final plot visualizes error evolution during training... | def fit(self, X, y):
# 1. Scale input and/or output patterns, if needed
X_train, X_test, y_train, y_test = self.split_dataset(X, y)
# 2. Initialize all weights and thresholds randomly
for lay in range(1, self.L):
self.w[lay] = np.random.randn(self.n[lay], self.n[lay - 1])
... |
def load_state_dict(self, state : dict) -> None:
"""Sets the state for the context.
Args:
state (dict): The state to load.
"""
for name, item_state in state.items():
if name in vars(self):
setattr(self, name, _set_state_dict(getattr(self, name), i... | The main task of the code is to transform a model according to experiment parameters by loading a checkpoint (if specified), moving the model to CUDA (if enabled), and configuring distributed data parallel training (if enabled). It ensures the model is properly initialized and configured for execution based on the prov... | def autotransform(self):
"""Transforms the context according to the current experiment
parameters. More specifically it; loads a state_dict from the parameter
``checkpoint`` if set, moves to cuda if paramter ``cuda`` is set, moves
to distributed if parameter ``distributed`` is set.
... |
def forgetWidget(widget):
widget.grid_forget()
def wrap(string, length=40):
return '\n'.join(textwrap.wrap(string, length))
def removeAppointment(tree, num):
try:
temp = tree.selection()[0]
temp2 = str(tree.item(temp)['values'][1])
dateTemp = datetime.strptime(temp2, '%Y-%m-%d')
... | The code displays a patient's appointments in a full-screen window by clearing existing UI elements, creating a Treeview with appointment details (ID, date, time, doctor info, etc.), and adding buttons to cancel or remove appointments. It filters appointments based on the current patient's ID and links them to correspo... | def viewAppointments():
w, h = settings.window.winfo_screenwidth(), settings.window.winfo_screenheight()
settings.window.geometry("%dx%d+0+0" % (w, h))
for i in range(0, len(settings.bList)):
forgetWidget(settings.bList[i])
for i in range(0, len(settings.lList)):
forgetWidget(settings.... |
def forgetWidget(widget):
widget.grid_forget()
def wrap(string, length=40):
return '\n'.join(textwrap.wrap(string, length))
def removeAppointment(tree, num):
try:
temp = tree.selection()[0]
temp2 = str(tree.item(temp)['values'][1])
dateTemp = datetime.strptime(temp2, '%Y-%m-%d')
... | The main task of the code is to display a full-screen view of a doctor's appointments using a Treeview widget, listing appointment details like number, date, time, patient name, type, and reason. It clears existing UI elements, populates the Treeview with filtered appointment data linked to the current doctor, and prov... | def viewDoctorAppointments():
w, h = settings.window.winfo_screenwidth(), settings.window.winfo_screenheight()
settings.window.geometry("%dx%d+0+0" % (w, h))
for i in range(0, len(settings.bList)):
forgetWidget(settings.bList[i])
for i in range(0, len(settings.lList)):
forgetWidget(set... |
def forgetWidget(widget):
widget.grid_forget()
def wrap(string, length=40):
return '\n'.join(textwrap.wrap(string, length))
def removeAppointment(tree, num):
try:
temp = tree.selection()[0]
temp2 = str(tree.item(temp)['values'][1])
dateTemp = datetime.strptime(temp2, '%Y-%m-%d')
... | The main task of the code is to display a patient's appointments in a GUI table, clearing prior widgets, configuring a Treeview with appointment details, and adding buttons to cancel or remove appointments. It filters appointments by the current patient, linking data from calendars, doctors, and appointments, then popu... | def viewPatientAppointments():
w, h = settings.window.winfo_screenwidth(), settings.window.winfo_screenheight()
settings.window.geometry("%dx%d+0+0" % (w, h))
for i in range(0, len(settings.bList)):
forgetWidget(settings.bList[i])
for i in range(0, len(settings.lList)):
forgetWidget(se... |
def _updateHyperparameters(self):
print('')
print('size of initial generation:')
self.n_parents = int(input())
print('')
print('number of children:')
self.n_children = int(input())
print('')
print('number of generations:')
self.n_generations = i... | The code provides a menu-driven interface allowing users to choose between entering custom hyperparameters, using default ones, or quitting. It repeatedly prompts for input, processes the selection by updating parameters or executing a key-finding operation on the input text, until the user quits. | def launch(self, text):
while True:
print('')
print('1 - enter hyperparameters')
print('2 - use default hyperparameters')
print('q - quit')
print('')
print('your input:')
inp = input()
if inp == 'q':
... |
def parseConnections(self, content):
"""
parses the link lines of a circuit file with the given name and stores the connections between nodes in self.connections,
and self.reverseConnections
:param content: the contents of the file as read by :func:`~Parser.parseCircuit`
"""
... | (The code parses a circuit file to construct a node-based representation, utilizing provided weight functions and domains. It reads the file, initializes connection and node dictionaries, processes connections and nodes, adjusts constant nodes, identifies the root node from the file's first line, establishes node links... | def parseCircuit(self, name, weights, domains):
"""
parses a circuit file with the given name and creates nodes using data on the weight functions and domains
:param name: the path to the circuit file to be parsed
:param weights: the weights dictionary as returned by the :func:`~Parser.... |
def find_all_for_variable_list(func, func_dict):
# all_for_variable_arr_list Structure:- List of array in for variable in given function
# [{"variable_name": "a", type: "int"}]
argument_variable,argument_array_variable = find_function_args_variable_type(func, func_dict)
all_function_variable,all_function_array_v... | The function analyzes a given Python function to identify and process all `for` and `while` loops. It collects loop variables, line numbers, and invokes handlers (`for_loop_handle`, `while_loop_handle`) for each loop type. The results include loop variables, line numbers, and processed data, aiding in code analysis or ... | def convert_function_handler(func, func_dict,func_count,banres,file_name):
func_for_loop_var_list = find_all_for_variable_list(func, func_dict)
func_while_loop_var_list = find_all_while_variable_list(func, func_dict)
#print(func_for_loop_var_list)
#print(func_while_loop_var_list)
func_for_loop_line_number_arr =... |
def comment_pre_processor(file_name):
f = open(file_name, 'r')
line_arr = []
for line in f:
line_arr.append(line)
f.close()
file = open(file_name,'w+')
for line in line_arr:
if "#" in line:
file.write("//" + line)
else:
file.write(line)
file.close()
def remove_pre_processor(file_name, write_file_name... | This code analyzes C/C++ source files by parsing their abstract syntax tree (AST), identifying function definitions, and checking loop constructs (For/While/DoWhile) for dependencies. It processes preprocessor directives, extracts loop structures, and returns lists indicating dependency status and generated loop repres... | def test_dependency(file_name):
comment_pre_processor(file_name)
ast = parse_file(file_name, use_cpp=True)
#print(ast)
# print(type(ast))
remove_pre_processor(file_name, file_name)
banres = []
forstmt = []
# print(ast)
func_count = 0
for func in ast.ext:
func_dict = ast_utilities.to_dict(func)
#prin... |
def _icon_themed(light_icon: Path, dark_icon: Path, alt: str, tooltip: str) -> str:
base = _icon_img(dark_icon, alt, tooltip)
if not light_icon.exists():
raise ValueError(f"""The icon "{light_icon}" does not exist.""")
return f"""<picture><source media="(prefers-color-scheme: dark)" srcset="{dark_... | The code generates an HTML component displaying icons for tools in a stack, including tooltips and links. It dynamically constructs a `<div>` with icons, using themed icons if specified, and adds hover info instructions. | def generate(stack: Mapping[str, Any]) -> str:
component = """<div id="tools">"""
for tool, info in stack.items():
name, desc = info["name"], info.get("description")
if not desc:
tooltip = name
else:
tooltip = "\n".join([name, desc])
use_themed_icons = ... |
def get_neigs(self, sample):
"""
return array of neighbors of sample
including sample
it means all elements of X with distance less than eps
"""
neighbors = [i for i,s in enumerate(self.X) if (dist(self.X[sample], s) <self.eps) ]
return np.array(neighbors)
def expand(self, sample, neighbors):
"""
m... | This code performs clustering on input data X by identifying dense regions (clusters) and noise. It iterates through samples, finds neighbors, and forms clusters if a sample has sufficient neighbors (≥minSamples). Isolated samples are labeled as noise (-1). Cluster labels are then assigned to each data point and return... | def predict(self, X):
"""
based a dataset returns labels to X
"""
self.X = X
self.clusters = {}
self.visited = []
self.neighbors = {}
n_samples = np.shape(self.X)[0]
for sample in range(n_samples):
if not (sample in self.visited):
self.neighbors[sample] = self.get_neigs(sample)
self.visite... |
def get_neigs(self, sample):
"""
return array of neighbors of sample
including sample
it means all elements of X with distance less than eps
"""
neighbors = [i for i,s in enumerate(self.X) if (dist(self.X[sample], s) <self.eps) ]
return np.array(neighbors)
def expand(self, sample, neighbors):
"""
m... | The code performs density-based clustering on input dataset X, grouping samples into clusters based on neighbor density. It identifies core samples with sufficient neighbors, expands clusters from them, and labels noise points as -1. The function returns cluster labels for each data point in X. | def predict(self, X):
"""
based a dataset returns labels to X
"""
self.X = X
self.clusters = {}
self.visited = []
self.neighbors = {}
n_samples = np.shape(self.X)[0]
for sample in range(n_samples):
if not (sample in self.visited):
self.neighbors[sample] = self.get_neigs(sample)
self.visite... |
def get_neigs(self, sample):
"""
return array of neighbors
"""
ID = np.arange(len(self.X))
neighbors = [i for i,s in enumerate(self.X[ID != sample]) if (dist(self.X[sample], s) <self.eps) ]
return np.array(neighbors)
def expand(self, sample, neighbors):
cluster = [sample]
for neighbor in neighbors:
... | The code performs clustering on input data X by identifying dense regions of samples. It iterates through each sample, finds neighboring points, and forms clusters if a minimum number of neighbors are met. The `expand` method grows clusters from dense areas, and `get_labels` assigns cluster identities. The function ret... | def predict(self, X):
"""
based a dataset returns labels to X
"""
self.X = X
self.clusters = []
self.visited = []
self.neighbors = {}
n_samples = np.shape(self.X)[0]
for sample in range(n_samples):
if not sample in self.visited:
self.neighbors[sample] = self.get_neigs(sample)
if len(self.n... |
def get_neigs(self, sample):
"""
return array of neighbors of sample
including sample
it means all elements of X with distance less than eps
input sample, outputs array of neighbors
"""
neighbors = [i for i,s in enumerate(self.X) if (dist(self.X[sample], s) <self.eps) ]
return np.array(neighbor... | This code performs density-based clustering on input data X, assigning cluster labels by identifying core points with sufficient neighbors, expanding clusters from these points, and labeling noise points as outliers. It returns predicted clustering labels for each sample in X. | def predict(self, X):
"""
based a dataset returns labels to X
inputs database, outputs the predicted clustering labels.
"""
self.X = X
self.clusters = {}
self.visited = []
self.neighbors = {}
n_samples = np.shape(self.X)[0]
for sample in range(n_samples):
if not (sample in self.visited):
... |
def get_neigs(self, sample):
"""
return array of neighbors of sample
including sample
it means all elements of X with distance less than eps
"""
neighbors = [i for i,s in enumerate(self.X) if (dist(self.X[sample], s) <self.eps) ]
return np.array(neighbors)
def expand(self, sample, neighbors):
"""
m... | The main task of the code is to perform density-based clustering on input data X, assigning cluster labels by identifying dense regions of samples and separating noise. It iterates through each sample, determines neighbors, forms clusters if sufficient neighbors exist, and labels outliers as noise. The result is a set ... | def predict(self, X):
"""
based a dataset returns labels to X
"""
self.X = X
self.clusters = {}
self.visited = []
self.neighbors = {}
n_samples = np.shape(self.X)[0]
for sample in range(n_samples):
if not (sample in self.visited):
self.neighbors[sample] = self.get_neigs(sample)
self.visite... |
def join(fromDir, toFile):
"""Assembles a file from its fragments (created by `split`)"""
print(f"Joining file fragments. {len(os.listdir(fromDir))} fragments found")
output = open(toFile, 'wb')
fromDir = fromDir + "\\" + os.listdir(fromDir)[0]
parts = os.listdir(f"{fromDir}")
parts.sort()
... | The main task of the code is to upload a zip file to a GitHub repository, creating a new branch named after the zip file. It extracts the zip into a temporary directory, uploads its contents to the specified branch, waits briefly, and then deletes the temporary folder. The function handles path manipulation, temporary ... | def upload_zip(zip_path, branch=None):
"""Uploads a zip file to a Github repository (creates a new branch with the name of the zip file)"""
zipName = zip_path.split("/")[-1]
zipPath = zip_path.replace("/"+zipName, '')
zipName = zipName.replace(".zip", '')
temp = f"temp-{random.randint(10000, 99999)}... |
def select(self, table:list, fields:list, where:list, sorting:str)->list:
data = self.data[table[0]] if table else self.data
if where:
data = self.where(data, where)()
if '*' in fields:
output = (doc for doc in data)
else:
... | This method executes database operations based on the 'method' attribute, handling subqueries, joins, selects, aggregations, and grouping. It initializes data from tables or subqueries, applies filters, sorting, and aggregation functions, then returns processed results via corresponding methods like select(), join(), a... | def run(self)->list:
where = self.kwargs.get('where')
subq = self.kwargs.get('subq')
tables = self.kwargs.get('tables')
if subq:
if callable(subq) and self.method != 'group_by':
self.data = subq()
else:
self.data = self.kwargs['sub... |
def show_unknown_request_error(self):
"""Send error respond when there is unknown request occurs."""
self.send_response(404)
self.end_headers()
self.wfile.write(b"Server cannot handle unknown request. Please use only appropriate ones.")
def show_no_necessary_attr(self):
"""Send e... | This code handles POST requests to add a new post to a MongoDB database. It checks if a post with the given unique ID already exists. If not, it generates a new post number, stores the data, and returns a 201 response with the post ID and number. Errors are raised for invalid paths, missing IDs, or duplicate entries. | def do_POST(self):
"""Handle POST requests.
Adds a new post to the database. Check for existing one's before adding.
"""
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
data = json.loads(body)
if not self.path.startswi... |
def get_variants_grouped(eccs_perchrom):
ecc_withvariants = {}
for i in range(len(eccs_perchrom)):
ecc = eccs_perchrom[i]
variants = []
# rolling grouping of eccs by proximity
for k in range(len(eccs_perchrom)):
start_coordinate1 = eccs_perchrom[k][1] - 20
start_c... | The function `ecc_merge` processes genetic variants by grouping them, selecting representative variants from these groups, merging the original data with these representatives, and returning both the merged variants and the representative variants for further analysis or processing. | def ecc_merge(eccs_perchrom):
variants_grouped = get_variants_grouped(eccs_perchrom)
representative_variants = get_representative_variants(variants_grouped)
variants_merged = merge_variants(eccs_perchrom, representative_variants)
return variants_merged, representative_variants |
def get_variants_grouped(eccs_perchrom):
ecc_withvariants = {}
for i in range(len(eccs_perchrom)):
ecc = eccs_perchrom[i]
variants = []
# rolling grouping of eccs by proximity
for k in range(len(eccs_perchrom)):
start_coordinate1 = eccs_perchrom[k][1] - 20
start_c... | The code merges variants by first grouping them, selecting representative variants from each group, and then combining the variants using these representatives, returning both the merged variants and the selected representatives. | def ecc_merge(eccs_perchrom):
variants_grouped = get_variants_grouped(eccs_perchrom)
representative_variants = get_representative_variants(variants_grouped)
variants_merged = merge_variants(eccs_perchrom, representative_variants)
return variants_merged, representative_variants |
def get_variants_grouped(eccs_perchrom):
ecc_withvariants = {}
for i in range(len(eccs_perchrom)):
ecc = eccs_perchrom[i]
variants = []
## this likely isnt ideal because of its rolling nature but this will be replaced by repeat/junction based later
for k in range(len(eccs_perchrom)):
... | The code merges variants by grouping them, selecting representative variants from each group, and then merging these representatives with the original variants. It returns both the merged variants and the selected representatives for further analysis or processing. | def ecc_merge(eccs_perchrom):
variants_grouped = get_variants_grouped(eccs_perchrom)
representative_variants = get_representative_variants(variants_grouped)
variants_merged = merge_variants(eccs_perchrom, representative_variants)
return variants_merged, representative_variants |
def needs_auth(session):
if session.uid in auth_sessions:
return False
return True
def custom402(request):
request.setHeader('Content-Type', 'text/html; charset=utf-8')
request.setResponseCode(402)
template['header']['title'] = app_name + ' - Not Authorized'
template['content']['message'... | The code handles a POST request by first checking if authentication is required. If so, it returns a custom 402 error. Otherwise, it configures the POST request and returns the result of configuring a GET request, likely rendering a response based on the setup. | def render_POST(self, request):
if needs_auth(request.getSession()): return custom402(request)
configure_post(request)
return configure_get(request) |
def LoadVolumes(volumes):
"""Process a "volumes" block of config and return a list of volumes."""
# TODO(thockin): could be a map of name -> Volume
all_vol_names = []
for vol_index, vol in enumerate(volumes):
# Get the container name.
if 'name' not in vol:
raise ConfigExcept... | The main task of the code is to continuously monitor and apply container configurations from YAML files matching a given pattern. It loads container and volume definitions, resolves conflicts, and runs containers in a specified namespace, repeating this process at regular intervals defined by `reload_interval` to ensur... | def RunContainersFromConfigFiles(config_glob, reload_interval, namespace):
while True:
try:
files = glob(config_glob)
log.debug('loading config files: %s', files)
containers = []
volumes = {}
for filename in files:
with open(filenam... |
def checkToken(self, kind):
return kind == self.curToken.kind
def nextToken(self):
self.curToken = self.peekToken
self.peekToken = self.lexer.getToken()
def newLine(self):
#print("NEW LINE")
self.match(TokenType.NEWLINE)
while self.checkToken(TokenType.NEWLINE):
... | This code parses and validates PRINT and VARIABLE statements in a token stream. It checks for PRINT followed by LESS, STRING/VAR_NAME, and GREATER to confirm valid print syntax. For variables, it identifies VAR_NAME tokens and checks for EQ to detect variable assignments. The method advances tokens and prints diagnosti... | def statement(self):
if self.checkToken(TokenType.PRINT):
print("PRINT STATEMENT")
self.nextToken()
if self.checkToken(TokenType.LESS):
self.nextToken()
if self.checkToken(TokenType.STRING) or self.checkToken(TokenType.VAR_NAME):
... |
def checkToken(self, kind):
return kind == self.curToken.kind
def nextToken(self):
self.curToken = self.peekToken
self.peekToken = self.lexer.getToken()
def statement(self):
if self.checkToken(TokenType.PRINT):
print("PRINT STATEMENT")
self.nextToken()
... | The main task of the code is to process a sequence of statements by iterating through tokens until EOF, skipping newlines, and executing the `statement()` method for each token. It begins by printing "PRGRAM" and includes commented-out lines for potential C header generation. The core functionality involves token valid... | def program(self):
print("PRGRAM")
#self.emitter.headerLine("#include <stdio.h>")
#self.emitter.headerLine("int main(void){")
while self.checkToken(TokenType.NEWLINE):
self.nextToken()
while not self.checkToken(TokenType.EOF):
self.statement() |
def has_catastrophic_error(self):
"""Returns bool value indicating whether the DRBG is in a catastrophic error state."""
return self.__health_state.is_catastrophic_error()
def __load_state(self, state_handle):
"""Loads an instantiation of this DRBG."""
if state_handle not in self.__sta... | This code generates pseudo-random bits using a Deterministic Random Bit Generator (DRBG) while enforcing security constraints, input validation, and reseeding. It checks for catastrophic errors, validates parameters like bit count and security strength against state limits, handles optional additional input, and ensure... | def generate(self, state_handle, requested_number_of_bits, requested_security_strength=None,
prediction_resistance_request=None, additional_input=None):
"""Generates pseudo-random bits using an instantiation.
Parameters
----------
state_handle : int
A handle... |
def draw_detections(self, frame, detections):
for roi, landmarks, identity in zip(*detections):
self.draw_detection_roi(frame, roi, identity)
self.draw_detection_keypoints(frame, roi, landmarks)
def draw_status(self, frame, detections):
origin = np.array([10, 10])
color =... | This method processes video frames from an input stream by detecting objects, drawing detection results and status information on each frame, and writing the processed frames to an output stream if provided. It also supports real-time display in an interactive window, handles frame cropping if specified, tracks FPS, an... | def process(self, input_stream, output_stream):
self.input_stream = input_stream
self.output_stream = output_stream
while input_stream.isOpened():
has_frame, frame = input_stream.read()
if not has_frame:
break
if self.input_crop is not None:
... |
def set_conflicting_corners(self):
# ans = []
# self.print_cube_with_faces()
adjacent_corner = {0:8,2:6,6:2,8:0}
while True:
n_conflicting_corners,conflicting_corners = self.get_conflicting_corners(0)
# print(n_conflicting_corners)
# print(conflicting_corners)
#no conflicting corners
if n_conflic... | The code's main task is to solve a Rubik's cube by adjusting conflicting corners, aligning adjacent corners to be consistent, forming cube sides, and returning the solved state stored in `self.ans` through a series of stepwise operations. | def solve(self):
self.set_conflicting_corners()
#print("--------------------------after adjusting corners-----------------------")
#self.print_cube_with_faces()
self.set_adjacent_corners_same()
#print("-----------------------after adjacent corners are same---------------------")
#self.print_cube_with_faces(... |
def color_verifier(self):
for face in self.faces:
for i in range(0,9):
if face[i] not in self.colors:
return False
return True
def number_of_colors_verifier(self):
color_count = {'b':0,'g':0,'r':0,'o':0,'w':0,'y':0}
for face in self.faces:
for i in range(0,9):
color_count[face[i]]+=1
fo... | The `full_verify` method checks if three verification conditions—color validity, correct number of colors, and cubies (pieces) correctness—are all satisfied. It returns `True` if all pass, otherwise `False`, ensuring the object's state meets required criteria. | def full_verify(self):
if self.color_verifier() and self.number_of_colors_verifier() and self.cubies_verifier():
return True
else:
return False |
def is_valid_url(url):
try:
result = urlparse(url)
return all([result.scheme, result.netloc])
except ValueError:
return False
def ready_page(url, count):
driver.get(url)
driver.maximize_window()
time.sleep(3)
scroll(count)
print("Page ready...")
def get_elements(class... | The code's main task is to download images from a Google Search Images result page by extracting thumbnails based on user-provided class names, handling image quality parameters, and saving them to a local folder or Google Cloud Storage. It validates inputs, processes image elements, and uses external parameters for cr... | def scragle(count, params, out='folder'):
try:
full_url = input(
"""Paste the Google Search Images result URL: """
)
if not full_url or not is_valid_url(full_url):
raise ValueError(
"""The value provided is not valid."""
)
ready_pag... |
def gameStart(bird):
bird.__init__()
font = pygame.font.SysFont('consolas', 40)
headingSuface = font.render('monster on run', True, (255, 255, 0))
headingSize = headingSuface.get_size()
font = pygame.font.SysFont('consolas... | The code initializes game components (bird, columns, score) and starts a video thread. It runs a continuous game loop, executing game start, play, and over phases, likely handling interactions and rendering in a separate thread for real-time processing. | def main():
bird = Bird()
columns = Columns()
score = Score()
xyz = threadVideo()
xyz.start()
while True:
gameStart(bird)
gamePlay(bird, columns, scor... |
def _api_req(self, uri: str, body: dict = None, method: str = "get") -> requests.Response:
"""
Calls a request
:param uri: Url of the request e.g "/user"
:param body: Body of the request if not get method
:param method: The method of request ["get", "post"]
:return: reque... | The main task of the code is to refresh the cached tree information from a GitHub repository's API. It fetches the git tree for the main branch recursively, and if the response lacks a "tree" key, it creates a README file and recursively re-calls itself to re-update the SHA, ensuring the cache reflects the latest repos... | def _update_all_sha(self):
"""
Re caches all tree information
:return:
"""
self.__cache = self._api_req(f"/repos/{self._login}/{self._name}/git/trees/main?recursive=1").json()
if "tree" not in self.__cache:
self._create_readme()
self._update_all_sh... |
def _get_tree_from_github(self, path: str, sha: str, recursive=False) -> List[dict]:
"""
Gets children of a tree
:param path: The Path of the tree (to be used in mixing the child and parent path)
:param sha: The sha of the tree
:param recursive: Get everything inside the tree?
... | The main task of the code is to update a cache with parent tree information by traversing from the deepest directory upward. It converts parent paths to a standardized format, reverses the order, and iteratively fetches each parent's subtree from GitHub. For each parent (except the last), it retrieves the next parent's... | def _update_parent_tree(self, path):
# Parents -> [Path(path/path)] -> [path\\path] -> [path/path]
blob_parents = [str(x).replace("\\", "/") for x in list(Path(path).parents)]
# To be used in known if last parent was reached in the loop below
num_parents = len(blob_parents)
# Rev... |
def _api_req(self, uri: str, body: dict = None, method: str = "get") -> requests.Response:
"""
Calls a request
:param uri: Url of the request e.g "/user"
:param body: Body of the request if not get method
:param method: The method of request ["get", "post"]
:return: reque... | This function checks if a file exists in a GitHub repository by querying its API. If the file exists (status ≠ 404), it updates SHA hashes and retrieves the file from a cache; otherwise, it returns None. | def _file_in_github(self, path: str) -> Union[dict, None]:
if self._api_req(f"/repos/{self._login}/{self._name}/contents/{path}").status_code != 404:
self._update_all_sha()
return self._file_in_cache(path)
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.