dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def list_connections(self):
results = ''
for i, conn in enumerate(self.all_connections):
try:
conn.send(str.encode(' '))
conn.recv(20480)
except:
del self.all_connections[i]
del self.all_addresses[i]
... | This code defines a command-line interface for managing network connections. It continuously accepts user input to list connections, select targets, send commands, or shut down the server. The loop processes commands like 'list' (show connections), 'select' (interact with a target), 'shutdown' (terminate the server), a... | def start_turtle(self):
while True:
cmd = input('DimonDRAT > ')
if cmd == 'list':
self.list_connections()
continue
elif 'select' in cmd:
target, conn = self.get_target(cmd)
if conn is not None:
... |
def log_user_data(request):
client_ip = get_client_name(request)
path = request.path_info
time = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
update_user_data_log(client_ip, path, time)
def complete_job(request):
log_user_data(request)
selected_profile = request.session.get('selected_profile', N... | The main task of the code is to handle job details display and completion logic. It processes POST requests to either complete a selected job via `complete_job()` or render job details, including formatting cooldown times and determining if the "Complete" button should be shown. If no job is selected, it redirects with... | def job_details(request):
log_user_data(request)
selected_job_name = request.POST.get('selected_job_name', None)
if request.method == 'POST':
if request.POST.get('complete_button'):
return complete_job(request)
if selected_job_name:
selected_job_details = get_job_details(se... |
def handle400(self):
self.send_response(400)
self.end_headers()
def end_headers(self):
self.sendCookie()
self.send_header("Access-Control-Allow-Origin", self.headers["Origin"])
self.send_header("Access-COntrol-Allow-Credentials", "true")
BaseHTTPRequestHandler.end_headers... | This function authenticates a user by validating provided username and password against a database. It parses request data, checks for required fields, verifies credentials using bcrypt, and sets session data on success. Errors return 400/401 responses. | def handleAuthenticateUser(self):
length = int(self.headers["Content-Length"])
request_body = self.rfile.read(length).decode("utf-8")
parsed_body = parse_qs(request_body)
if "userName" not in parsed_body:
print("missing userName")
self.handle400()
ret... |
def handle400(self):
self.send_response(400)
self.end_headers()
def handle201(self):
self.send_response(201)
self.end_headers()
def handle444(self):
self.send_response(444)
self.end_headers() | This code handles user registration by parsing form data, validating required fields (userName and userPassword), hashing the password with bcrypt, and interacting with a database to create a user. It returns HTTP status codes (201 for success, 400 for missing fields or existing username, 444 for database errors) based... | def createUser(self):
length = int(self.headers["Content-Length"])
request_body = self.rfile.read(length).decode("utf-8")
# print("The request body: ", request_body)
parsed_body = parse_qs(request_body)
print("the parsed body:", parsed_body)
if "userName" not in parsed... |
def isLogin(self):
if "userID" not in self.sessionData:
self.handle401()
return False
else:
return True
def handle400(self):
self.send_response(400)
self.end_headers()
def end_headers(self):
self.sendCookie()
self.send_header("Access-Co... | This code handles user deletion via an API endpoint. It checks authentication, parses request data, validates the userID, interacts with a database to delete the user if found, and returns appropriate HTTP responses (200 on success, 400/401/404 on errors) with JSON data. | def deleteUser(self):
if self.isLogin():
length = int(self.headers["Content-Length"])
request_body = self.rfile.read(length).decode("utf-8")
parsed_body = parse_qs(request_body)
if "userID" not in parsed_body:
print("need userID")
... |
def isLogin(self):
if "userID" not in self.sessionData:
self.handle401()
return False
else:
return True
def handle400(self):
self.send_response(400)
self.end_headers()
def end_headers(self):
self.sendCookie()
self.send_header("Access-Co... | This code handles an HTTP request to update a user's name. It verifies the user is logged in, retrieves the user record by ID, checks for a provided new name in the request body, updates the name in the database if valid, and returns 200 success or 400/401/404 errors for invalid inputs, missing data, or authentication ... | def updateUserName(self, userID):
if self.isLogin():
db = Database()
userRecord = db.getUserByID(userID)
if userRecord != None:
length = int(self.headers["Content-Length"])
request_body = self.rfile.read(length).decode("utf-8")
... |
def isLogin(self):
if "userID" not in self.sessionData:
self.handle401()
return False
else:
return True
def handle400(self):
self.send_response(400)
self.end_headers()
def end_headers(self):
self.sendCookie()
self.send_header("Access-Co... | This code updates a user's password in a database if the user is logged in. It verifies the request contains a new password, hashes it using bcrypt, and updates the user's record. It handles errors for missing data, unauthorized access, and non-existent users. | def updateUserPwd(self, userID):
if self.isLogin():
db = Database()
userRecord = db.getUserByID(userID)
if userRecord != None:
length = int(self.headers["Content-Length"])
request_body = self.rfile.read(length).decode("utf-8")
p... |
def isLogin(self):
if "userID" not in self.sessionData:
self.handle401()
return False
else:
return True
def handle400(self):
self.send_response(400)
self.end_headers()
def end_headers(self):
self.sendCookie()
self.send_header("Access-Co... | This code handles a chat conversation by processing query parameters from a URL, validating user input, generating a response using a robot model, storing the interaction in a database, and returning the response in JSON format. It checks user authentication, extracts userID and userInput, handles errors for missing da... | def chatConversation(self):
if self.isLogin():
if len(self.path.split("?")) > 1:
dataPart = self.path.split("?")
else:
self.handle400()
print("there is not data")
return
data = dataPart[1].split("&... |
def isLogin(self):
if "userID" not in self.sessionData:
self.handle401()
return False
else:
return True
def handle204(self):
print("Ok but not content")
self.send_response(204)
self.end_headers()
def end_headers(self):
self.sendCookie()... | The function retrieves a user's chat history from the database if authenticated. It returns the history as JSON with a 200 status if found, or 204 if empty. If the user is not logged in, it handles unauthorized access with a 401 error. | def getChatHistory(self, userID):
if self.isLogin():
db = Database()
history = db.getChatHistory(userID)
if history == None:
self.handle204()
else:
self.send_response(200)
self.send_header("Content-type", "applicatio... |
def loadSession(self):
self.loadCookie()
if "sessionID" in self.cookie:
sessionID = self.cookie["sessionID"].value
self.sessionData = gSessionStore.getSessionData(sessionID)
if self.sessionData == None:
sessionID = gSessionStore.createSession()
... | The main task of the code is to handle POST requests by routing them based on the request path. It loads a session, checks the path, and executes corresponding actions: authenticating a user for "/sessions", creating a user for "/users", or handling not-found errors for other paths. It logs the request path and uses sp... | def do_POST(self):
self.loadSession()
print("the request path is :", self.path)
if self.path == "/sessions":
self.handleAuthenticateUser()
elif self.path == "/users":
self.createUser()
else:
print("do_POST not found")
self.handleN... |
def loadSession(self):
self.loadCookie()
if "sessionID" in self.cookie:
sessionID = self.cookie["sessionID"].value
self.sessionData = gSessionStore.getSessionData(sessionID)
if self.sessionData == None:
sessionID = gSessionStore.createSession()
... | This code handles DELETE HTTP requests by determining the resource path, loading a session, and either deleting a user if the path matches "user" or returning a not-found response for other paths. | def do_DELETE(self):
self.loadSession()
print("the request path is :", self.path)
path_parts = self.path.split("/")
collection = path_parts[1]
if collection == "user":
self.deleteUser()
else:
self.handleNotFound() |
def handle400(self):
self.send_response(400)
self.end_headers()
def updateUserName(self, userID):
if self.isLogin():
db = Database()
userRecord = db.getUserByID(userID)
if userRecord != None:
length = int(self.headers["Content-Length"])
... | The code processes an HTTP request to update user information. It reads the request body, parses URL-encoded form data, validates the presence of "userID" and "type" parameters, converts "userID" to an integer, and executes either `updateUserName` or `updateUserPwd` based on the "type" value. Errors like missing parame... | def update(self):
length = int(self.headers["Content-Length"])
request_body = self.rfile.read(length).decode("utf-8")
parsed_body = parse_qs(request_body)
if "userID" not in parsed_body:
print("need userID")
self.handle400()
return
userID = pa... |
def loadSession(self):
self.loadCookie()
if "sessionID" in self.cookie:
sessionID = self.cookie["sessionID"].value
self.sessionData = gSessionStore.getSessionData(sessionID)
if self.sessionData == None:
sessionID = gSessionStore.createSession()
... | This code handles HTTP GET requests by routing them based on URL paths and query parameters. It processes user data retrieval, chat history access, and logout actions. It parses query parameters to extract user IDs, validates inputs, and calls corresponding methods like getUserS(), getOneUser(), getChatHistory(), or ch... | def do_GET(self):
self.loadSession()
print("the request path is :", self.path)
path_parts = self.path.split("/")
collection = path_parts[1]
if collection == "users":
self.getUserS()
elif collection.split("?")[0] == "user":
if len(self.path.split("... |
def loadSession(self):
self.loadCookie()
if "sessionID" in self.cookie:
sessionID = self.cookie["sessionID"].value
self.sessionData = gSessionStore.getSessionData(sessionID)
if self.sessionData == None:
sessionID = gSessionStore.createSession()
... | The main task of the code is to handle HTTP PUT requests by loading a session, parsing the request path to identify a collection (e.g., "users"), and updating the specified collection if it matches "users"; otherwise, it logs an error and handles a "not found" response. | def do_PUT(self):
self.loadSession()
print("the request path is :", self.path)
path_parts = self.path.split("/")
collection = path_parts[1]
if collection == "users":
self.update()
else:
print('No collection')
self.handleNotFound() |
def createArray(n):
a = []
for i in range(n):
a.append(random.randint(0, 100))
return a
def countInversions(a):
# copy of a
return impl([e for e in a], 0, len(a))
def impl(a, start, end):
if end - start <= 1:
return 0 # all elements in order
# sort a for the caller... | The main task of the code is to count the number of inversions in an array, print the result, sort the array using a recursive implementation (likely a sorting algorithm like merge sort or quicksort), and display the sorted array. The code tests inversion counting and sorting functionality on a randomly generated array... | def test():
a = createArray(10)
i = countInversions(a)
print(f'{a} contains {i} inversions')
d = [e for e in a]
impl(d, 0, len(d))
print(f'Sorted: {d}') |
def learnMeans(inputList):
meansOut = dict()
inputArray1 = np.array(inputList[0])
inputArray2 = np.array(inputList[1])
for class_name in inputList[0]:
if class_name in meansOut:
continue
else:
index = np.where(inputArray1[:] == class_name)
meansOut[cl... | The function performs k-fold cross-validation (k=5) on input data, splitting it into training and test sets iteratively. For each fold, it trains models to compute means and priors, evaluates accuracy on the test set, and aggregates results. Finally, it returns the average accuracy across folds, along with the mean of ... | def crossValidOrder(dataIn):
k = 5
num = len(dataIn[0])
accuracyList = []
meanListDict = {data: [] for data in dataIn[0]}
priorListDict = {data: [] for data in dataIn[0]}
for i in range(k):
start = int(i * num / k)
end = int((i + 1) * num / k)
test = [dataIn[0][start: en... |
def learnMeans(inputList):
meansOut = dict()
inputArray1 = np.array(inputList[0])
inputArray2 = np.array(inputList[1])
for class_name in inputList[0]:
if class_name in meansOut:
continue
else:
index = np.where(inputArray1[:] == class_name)
meansOut[cl... | The function performs k-fold cross-validation on shuffled input data to evaluate a probabilistic model. It shuffles features and labels using a fixed random seed, splits data into 5 folds, trains a model (via learnMeans and learnPriors) on each training set, evaluates accuracy on the test set, and aggregates results. I... | def crossValidStoch(dataIn):
randnum = np.random.randint(100)
dataInShuffle = [dataIn[0][:], dataIn[1][:]]
np.random.seed(randnum)
dataInShuffle[0] = np.random.permutation(dataInShuffle[0]).tolist()
np.random.seed(randnum)
dataInShuffle[1] = np.random.permutation(dataInShuffle[1]).tolist()
... |
def weight_update(self, data_array, true_target, learning_rate, recurrent_time=10,
pruning=False, mask=None):
"""
Update weights given samples
:param data_array: input training samples
:param true_target: the true target of training samples
:param learning_... | The main task of the code is to train a neural network model using input data and target labels, with options for pruning hidden layer neurons. It performs iterative weight updates over specified epochs, supports multi-class and binary classification, and optionally applies pruning after a defined epoch, adjusting weig... | def fit_model(self, data_array, target, learning_epochs=10, learning_rate=0.2, re_time=10,
pruning=False, pruning_threshold=0.01, pruning_norm='L1', pruning_epoch=5,
verbose=True):
"""
Fit the model according to the given training data
:param data_array: inp... |
def conv_block(
input_tensor,
kernel_size,
filters,
stage,
block,
strides=(2, 2),
dilation_rate=1,
multigrid=[1, 2, 1],
use_se=True,
):
# conv filters
filters1, filters2, filters3 = filters
# compute dataformat
if K.image_data_format() == "channels_last":
bn_... | The code defines a PSPNet50 model for semantic segmentation, incorporating a ResNet-50 backbone with residual blocks, pyramid pooling for multi-scale context aggregation, and configurable upsampling (deconv, bilinear, or DUC). It processes input images to predict class labels using softmax activation, with parameters c... | def PSPNet50(
input_shape=(512, 512, 3),
n_labels=20,
output_stride=16,
num_blocks=4,
multigrid=[1, 1, 1],
levels=[6, 3, 2, 1],
use_se=True,
output_mode="softmax",
upsample_type="deconv",
):
# Input shape
img_input = Input(shape=input_shape)
# compute input shape
... |
def validate_datasets(self):
"""
Runs the validation script provided to the class upon initialization
using the user's dataset files as standard input.
"""
if self.validation_script is None:
return
dataset_files = self.identify_dataset_files()
valid... | The main task of the code is to export a user's dataset to VEuPathDB by packaging dataset files, metadata, and configuration into a tarball. It validates the data first, creates a temporary directory, generates required JSON files, and compresses everything into a `.tgz` file, which is then moved to the original workin... | def export(self):
"""
Does the work of exporting to VEuPathDB, a tarball consisting of the
user's dataset files along with dataset and metadata json files.
"""
# Apply the validation first. If it fails, exit with a data error.
self.validate_datasets()
# We need... |
def inverse(a, m):
gcd, x, y = extended_gcd(a, m)
if gcd != 1:
raise ValueError("Modular inverse does not exist")
return (x % m + m) % m
def process(matrix, k):
for i in range(k):
for j in range(k):
matrix[i][j] = (((matrix[i][j] % 26) + 26) % 26)
return matrix
def encryp... | The main task of the code is to decrypt a cipher text using a matrix-based encryption scheme. It calculates the modular inverse of the matrix determinant, computes the adjugate matrix, adjusts it modulo 26, and applies it to the cipher text via an encryption function, effectively performing decryption by transforming t... | def decrypt(cipher, k, matrix):
ans = ""
det = int(np.linalg.det(matrix))
det = ((det % 26) + 26) % 26
det = inverse(det, 26)
adj = np.linalg.inv(matrix) * np.linalg.det(matrix)
adj = np.round(adj, decimals=3)
adj = process(adj, k)
for i in range(k):
for j in range(k):
... |
def serv_updates(self):
upsidatesi = twirp_reqs.game_state_req(self.room, self.player_name)
print(type(upsidatesi), "UPSIDATESI")
if upsidatesi == True:
self.game_on = False
if len(upsidatesi) >= 0:
self.less_line()
def create_box(self, x, y, box_w, box_h, color):... | The code's main task is to check if the user's guess matches the target word, then visually indicate correct/misplaced/incorrect letters by creating colored boxes and updating the keyboard. If correct, it displays an end-game message; if not, it processes each letter's status, updates the GUI with corresponding colors,... | def check_guess(self):
self.serv_updates()
if self.guess == self.word:
for i, v in enumerate(self.guess):
if v == self.word[i]: # letters in a correct position
new_pos_x = self.pos_x + ((self.box_width + self.gap) * i)
new_pos_y = self... |
def check_guess(self):
self.serv_updates()
if self.guess == self.word:
for i, v in enumerate(self.guess):
if v == self.word[i]: # letters in a correct position
new_pos_x = self.pos_x + ((self.box_width + self.gap) * i)
new_pos_y = self... | This code handles user input in a word game by checking if the current guess is valid. If valid, it processes the guess, updates the game state, and checks for win/loss conditions. If invalid, it displays an error message, pauses, then resets the UI. The function manages turn progression, game termination, and feedback... | def kb_enter(self, event):
if self.guess in self.words:
if self.game_on:
if self.column_counter == 5 and self.row_counter == self.max_rows:
self.check_guess()
# print('game over')
if self.row_counter >= self.max_... |
def _is_initial_loss(self, data, idx):
if idx + 1 >= len(data):
return False
median = self._median_of_next_items(data, idx)
if median < self.__qos_threshold:
return True
return False
def _get_start_index(self, data, idx):
if idx > 0:
return id... | This function identifies transient behavior intervals in time-series data where Quality of Service (QoS) drops below expected levels. It detects initial loss events, calculates recovery endpoints, and records start/end indices of transient periods that meet time-based recovery criteria, excluding permanent degradation. | def _find_transient_behavior(self, data):
specification_endpoint = -1.0
transient_behavior_endpoint = -1.0
transient_behavior_indices = []
for i, item in enumerate(data):
if item.time > specification_endpoint and item.time > transient_behavior_endpoint:
if i... |
def _reset_loss(self):
data = ServiceData.objects.filter(service_id=self.service.id)
if self.cause == TbCause.FAILURE:
data.update(failureLoss=0.0)
elif self.cause == TbCause.DEPLOYMENT:
data.update(deploymentLoss=0.0)
elif self.cause == TbCause.LOAD_BALANCING:
... | The code computes resilience loss by iterating over call IDs, fetching service data, identifying transient behaviors, calculating expected and actual integrals for each behavior, determining the loss as their difference, and updating data objects with the computed resilience loss. | def compute_resilience_loss(self):
self._reset_loss()
call_ids = self._get_call_ids()
for call_id in call_ids:
data = ServiceData.objects.filter(service_id=self.service.id, callId=call_id).order_by('time')
tb_occurrences = self._find_transient_behavior(data)
... |
def get_name(self) -> str:
return self._name
def format_financial_figure(val):
"""
:type val: int
"""
return "£{:,.2f}".format(val)
def get_personal_allowance(self):
return self._personal_allowance
def get_taxable_income(self, gross_income) -> int:
if gross_income > self.get_per... | This method prints a detailed tax calculation breakdown for a given gross income, including the tax year, gross salary, personal allowance, taxable income, and individual tax rates with their respective calculations, culminating in the total tax due. | def print_calculation(self, gross_income: int):
print("Tax Year: {}".format(self.get_name()))
print("")
print("Gross Salary: {}".format(format_financial_figure(gross_income)))
print("")
print("Personal Allowance: {}".format(format_financial_figure(self.get_personal_allowance())))... |
def checktype(first_list):
status=True
for i in first_list:
if(isinstance(i,(int,float))==False):
status=False
break
return status
def check_length(first_list,second_list):
if(len(first_list)==len(second_list)):
return True
else:
return False
def mean(... | This code calculates the Nash-Sutcliffe Efficiency (NSE) between two lists. It validates input types and lengths, computes squared deviations between corresponding elements, divides by the variance of the first list, subtracts from 1, and rounds to 6 decimal places. | def nse(first_list, second_list):
# nse Logic
if(checktype(first_list)==False):
return 0
if(checktype(second_list)==False):
return 0
if(check_length(first_list,second_list)==False):
return 0
square_deviation_sum= 0
first_list_sorted=first_list
second_list_so... |
def checktype(first_list):
status=True
for i in first_list:
if(isinstance(i,(int,float))==False):
status=False
break
return status
def check_length(first_list,second_list):
if(len(first_list)==len(second_list)):
return True
else:
return False
def mean(... | This function calculates the Pearson Correlation Coefficient (PCC) between two lists. It first validates input types and lengths, then computes means, covariance-like sum, and divides by the product of list length and standard deviations. The result is rounded to six decimal places. | def pcc(first_list, second_list):
# nse Logic
if(checktype(first_list)==False):
return 0
if(checktype(second_list)==False):
return 0
if(check_length(first_list,second_list)==False):
return 0
mean_x= mean(first_list)
mean_y=mean(second_list)
sigma=0
for i in rang... |
def checktype(first_list):
status=True
for i in first_list:
if(isinstance(i,(int,float))==False):
status=False
break
return status
def mean(first_list):
# mean Logic
if(checktype(first_list)==False):
return 0
addition_of_rows= summation(first_list)
me... | This code calculates the skewness of a given list of numerical data by computing the sum of cubed deviations from the mean, dividing it by the product of the standard deviation cubed and the list length, then rounding the result to six decimal places. It first validates the input type, returning 0 if invalid. | def skewness(first_list):
# Skewness Logic
if(checktype(first_list)==False):
return 0
mean_x= mean(first_list)
sigma=0
for i in range(len(first_list)):
sigma+= (first_list[i]-mean_x)*(first_list[i]-mean_x)*(first_list[i]-mean_x)
sd= standard_deviation(first_list)
skewness_val... |
def checktype(first_list):
status=True
for i in first_list:
if(isinstance(i,(int,float))==False):
status=False
break
return status
def mean(first_list):
# mean Logic
if(checktype(first_list)==False):
return 0
addition_of_rows= summation(first_list)
me... | The code calculates the kurtosis of a given list by computing the fourth standardized moment. It first validates the input, computes the mean, sums the fourth powers of deviations from the mean, divides by the fourth power of the standard deviation and the list length, then rounds the result to six decimal places. | def kurtosis(first_list):
# Kurtosis Logic
if(checktype(first_list)==False):
return 0
kurtosis_value=0
mean_x= mean(first_list)
sigma=0
for i in range(len(first_list)):
sigma+= (first_list[i]-mean_x)*(first_list[i]-mean_x)*(first_list[i]-mean_x)*(first_list[i]-mean_x)
sd... |
def rv(vls: list[str]):
pr = ""
if vls[4] <= 2:
pr = f'-{PR[vls[4]]}.{vls[5]}'
return ".".join([str(i) for i in vls[0:4]]) + pr
def _bump(v: str):
idx = VERSIONS.index(v)
_vls = list(VLS)
match v:
case "pri":
match _vls[idx]:
case 0:
... | This code allows a user to interactively select a version to bump, confirm the change, and update relevant files (version file and smp/__init__.py) with the new version. It handles user input via prompts, applies version changes using regex, writes updated versions, generates scripts, and pushes changes if confirmed. | def bump():
while True:
choices = []
for k, v in VERSIONS_NAME.items():
choices.append([f'{k.ljust(23)}(bump to {rv(_bump(k))})', k])
v = inquirer.list_input(
message=f"What version do you want to bump? (Current version: {rv(VLS)})",
choices=choices,
... |
def cp():
for k, v in META_YML["cp"].items():
with open(
path.join("constants", *[str(_) for _ in VLS[0:2]], f'{k}.yml'),
"r"
) as f:
fc = yaml.safe_load(f.read())
if v.get("mp", True):
with open(f'{v["dir"]}.mp', "wb") as f:
f.... | The code presents a menu-driven interface using `inquirer` to let users select actions like copying constants, formatting code, generating documentation/scripts, pushing to GitHub, or version control. Each choice triggers specific functions, with "docs" also building documentation and offering a GitHub push confirmatio... | def main():
match inquirer.list_input(
message="What action do you want to take",
choices=[
["Copy constants to project folder", "cp"],
["Format code", "f"],
["Generate documentation", "docs"],
["Generate scripts", "gs"],
["Push to github",... |
def base_analysis(self):
result = '\nBase Analysis:\n'
average_bmi = round(self.__calc_average_bmi(),2)
average_children = round(self.__calc_average_children(),2)
average_cost = round(self.__calc_average_cost(),2)
result += f'There are {self.total_patients} total patients, {sel... | The main task of the code is to print aggregated analytical results by sequentially calling and displaying outputs from multiple methods: base analysis, age, sex, smoker, regions analysis, data description, and data correlation. It serves as a centralized function to visualize diverse dataset insights in a structured m... | def analysis_results(self):
print(self.base_analysis())
print(self.age_analysis())
print(self.sex_analysis())
print(self.smoker_analysis())
print(self.regions_analysis())
print(self.data_description())
print(self.data_correlation()) |
def load_uci_data(dataset,data_size = None):
"""Loads data from UCI repository.
@param dataset: UCI dataset name
@return: feature vectors, labels
@rtype: Tuple[np.array, np.array]
"""
x = []
y = []
ids = {
"zoo": (1, 17, -1),
"iris": (0, 4, -1),
"glass": (1, 10, ... | The function `load_data` loads a specified dataset (UCI or HYPBC), normalizes feature vectors if requested, and computes pairwise cosine similarities between samples. It returns feature vectors, labels, and a symmetric similarity matrix adjusted to the range [0, 1], with diagonal elements set to 1.0. The matrix is visu... | def load_data(dataset, normalize=True, data_size = None):
"""Load dataset.
@param dataset: dataset name
@type dataset: str
@param data_size: number of samples in dataset
@type data_size: int
@param normalize: whether to normalize features or not
@type normalize: boolean
@return: feature... |
def add_adjacent_to_dict():
for address in list(addresses_dict.keys()):
for direction in ['e','ne','nw','w','sw','se']:
new_address = simplify(convert_address_to_list(address+direction))
if not addresses_dict.get(new_address):
addresses_dict[new_address] = False
def process_tile(address):
num_black = get_... | This function simulates a cellular automaton over a specified number of days. Each day, it expands the grid by adding adjacent tiles, processes each tile (likely updating its state), prunes tiles without black neighbors, and prints the total count of remaining tiles. The simulation iteratively updates the grid state ba... | def simulate_flipping(days):
global addresses_dict
for i in range(days):
# Spawning tiles adjacent to all currently considered tiles
add_adjacent_to_dict()
new_addresses_dict = addresses_dict.copy()
# Calculating each tile
for address in new_addresses_dict:
new_addresses_dict[address] = process_tile(a... |
def parse_auth_proxy(proxy):
proxy = proxy.replace("@", ":")
colons_hit = 0
ip_username = ""
ip_password = ""
ip_ip = ""
ip_port = ""
for character in proxy:
if character == ":":
colons_hit = colons_hit + 1
else:
if colons_hit == 0:
ip_... | This code automates Discord account creation using proxies. It checks proxy availability, generates credentials, solves CAPTCHA, and sends registration requests. It handles both authenticated and unauthenticated proxies, saves generated tokens, and optionally verifies emails/phones. The main task is mass account creati... | def create_account(proxy):
if proxy in IPS_in_use:
return
IPS_in_use.append(proxy)
if if_ip_auth == True:
ip_username, ip_password, ip_ip, ip_port = parse_auth_proxy(proxy)
if gen_passwords == True:
password = "NicedayzONTOp!@#"
fingerprint, dcfduid, sdcfduid = get_fingerprin... |
def evaluate():
# check rows for victory
for row in range(3):
if board[row][0] == board[row][1] == board[row][2]:
if board[row][0] == PLAYER:
return 10
elif board[row][0] == OPPONENT_AI:
return -10
# check columns for victory
for col in ra... | The function `ai_move()` checks if the game is not in a terminal state (`evaluate() == 0`) and if there's an empty cell. If so, it determines the optimal move using `find_best_move()`, updates the game board with the opponent's AI marker, and disables the corresponding UI element to prevent further interaction. | def ai_move():
if evaluate() == 0 and is_empty_cell():
move = find_best_move()
row, col = move
board[row][col] = OPPONENT_AI
labels[row][col]['text'] = OPPONENT_AI
labels[row][col]['state'] = 'disabled' |
def preambula(name: str):
len_eq = 70 - len(name)
print('='*(len_eq // 2), end=' ')
cprint(name, attrs=["bold"], end=' ')
print('='*(len_eq - len_eq // 2))
def get_version(name: str):
app_version = subprocess.run([name, "--version"], capture_output=True)
version_out = app_version.stdout.decode("... | The function checks if a specified package meets a minimum version requirement. It retrieves the package's version, compares it to the minimum, and prints the version in green if up-to-date or red if outdated. If the package is not installed or raises an error, it warns the user in red. It also checks if the package is... | def print_version(
name: str,
min_version: Tuple[int],
how_to_install: str = '',
not_def_name: str = '',
how_to_change_def: str = '') -> None:
preambula(name)
is_all_good = True
is_not_installed = False
is_not_updated = False
try:
major_version, vers... |
def print_version(
name: str,
min_version: Tuple[int],
how_to_install: str = '',
not_def_name: str = '',
how_to_change_def: str = '') -> None:
preambula(name)
is_all_good = True
is_not_installed = False
is_not_updated = False
try:
major_version, vers... | The code checks and installs specific versions of development tools (Python 3.11, Clang 17, GCC 13, Bazel 6.4, CMake 3.24, etc.) by verifying their presence and providing installation instructions. If `all_info` is True, it also checks system details, Git repository status, and installs additional tools like lldb. The ... | def main(all_info: bool) -> None:
how_to_fix_default = """
sudo rm -rf /usr/bin/{0} && sudo ln -s /usr/bin/{1} /usr/bin/{0} && {0} --version
"""
print_version('python3', (3, 11, 0), 'python3.11', how_to_fix_default, '')
clang_version = (17, 0, 0)
how_to_install_clang = """
wget https://apt.... |
def urlsafeencode(value):
if isinstance(value, str):
return base64.urlsafe_b64encode(value.encode()).rstrip(b'=').decode()
elif isinstance(value, bytes):
return base64.urlsafe_b64encode(value).rstrip(b'=').decode()
else:
raise Exception('Input type not supported')
def integer_to_byte... | This function generates a JWT (JSON Web Token) with X.509 certificate information, including headers, claims, and a signature. It uses a provided PEM private key to sign the token, embedding the public key components (n, e), certificate thumbprints (x5t, x5t#s256), and the certificate itself (x5c). The token includes c... | def make_token_x5c(pem, kid, target_service, cert_hostname=None, padding=emsa_pkcs1_v1_5_encode, hash_algorithm=sha256):
hn = cert_hostname if cert_hostname else target_service
privkey = crypto.load_privatekey(crypto.FILETYPE_PEM, pem).to_cryptography_key()
e = urlsafeencode(integer_to_bytes(privkey.public_... |
def urlsafeencode(value):
if isinstance(value, str):
return base64.urlsafe_b64encode(value.encode()).rstrip(b'=').decode()
elif isinstance(value, bytes):
return base64.urlsafe_b64encode(value).rstrip(b'=').decode()
else:
raise Exception('Input type not supported')
def integer_to_byte... | The main task of the code is to generate a signed JSON Web Token (JWT) using an RSA private key. It constructs a JWK (JSON Web Key) from the public key, creates JWT headers and claims with metadata like target service, issuer, and timestamps, encodes them, signs the token with the private key, and returns the final JWT... | def make_token_jwk(pem, kid, target_service, padding=emsa_pkcs1_v1_5_encode, hash_algorithm=sha256):
privkey = crypto.load_privatekey(crypto.FILETYPE_PEM, pem).to_cryptography_key()
e = urlsafeencode(integer_to_bytes(privkey.public_key().public_numbers().e))
n = urlsafeencode(integer_to_bytes(privkey.public... |
def slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None],
xy_window=(64, 64), xy_overlap=(0.5, 0.5)):
# If x and/or y start/stop positions not defined, set to image size
if x_start_stop[0] == None:
x_start_stop[0] = 0
if x_start_stop[1] == None:
x_start... | The code detects cars in an image using sliding windows and HOG features. It processes the image in specified color spaces, extracts HOG, spatial, and histogram features, and applies a pre-trained classifier (svc) to identify potential car regions (hot windows). Multiple window sizes and positions are tested, and detec... | def car_image(image):
color_space = 'YCrCb' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb
orient = 9
pix_per_cell = 8
cell_per_block = 2
hog_channel = 'ALL' # Can be 0, 1, 2, or "ALL"
spatial_size = (16, 16)
hist_bins = 32
spatial_feat = True
hist_feat = True
hog_feat = True... |
def get_arguments(args):
desc = f'{APP_NAME} v.{__version__}'
parser = argparse.ArgumentParser(description=desc, add_help=False)
p = parser.add_argument_group('Positional arguments (required)')
p.add_argument('in_dir',
help='Input directory with genome assemblies')
p.add_argument... | The main task of the code is to dereplicate a set of genome sequences by clustering highly similar genomes using ANI (Average Nucleotide Identity) and other parameters. It processes genomes in batches, iteratively removing redundant sequences, and retains representative genomes per cluster. The script calculates N50 st... | def main(args=None):
args = get_arguments(args)
random.seed(0)
# Set paths to working directories (input, output, and temp)
in_dir = pathlib.Path(args.in_dir)
out_dir = pathlib.Path(args.out_dir)
out_subdir = out_dir / 'fasta'
out_subdir.mkdir(parents=True, exist_ok=True)
temp_dir =... |
def print_menu(self):
title("Welcome to PetZzZzZzZzZzZzZzZzZzZzZzZzZzZzZzZzZ")
option("1 - Adopt a pet")
option("2 - Care for pet")
option("q - Quit")
def title(text):
style = "underline white on blue"
rich_print(text, style=style, justify="center")
def print_pets(self):
... | The main task of the code is to implement a menu-driven application for pet adoption and care. It allows users to adopt a pet by creating an Owner instance, navigate to a pet care menu, or exit. The loop processes user selections, validates inputs, and executes corresponding actions like owner creation, pet management,... | def start(self):
exit = False
from models.owner import Owner
while not exit:
self.print_menu()
selection = input("Select option to continue... ")
if selection == '1':
console.print("Adopting a pet...")
... |
def resample_audios(audio_dir, outputdir, sr=8000):
'''
down sampling all the audio in a given speaker's directory
and save the new file in the output directory
:param audio_directory:
:return:
'''
speakers = mylistdir(audio_dir)
for speaker in speakers:
audios = mylistdir(os.p... | The code processes audio files according to specified treatments (control, convolve, white_noise, bg_noise) for enrollment or verification tasks. It applies transformations like resampling, impulse response convolution, or noise addition based on configuration parameters, saving processed audio to designated output dir... | def audio_manipulation(audio_directory, use, config):
'''manipulate audio to create data for enrolment or vertification'''
sr = config['sampling_rate']
channel = config['channel']
# set up the input and output directory url
audio_dir = os.path.join(config['audio_directory'] + '/' + channel, use)
... |
def split_train(self, train_x,train_y):
#shuffle for splitting train set and dataset
n = train_x.shape[0]
ind = np.arange(n)
np.random.shuffle(ind) #shuffle the train set
#split train set into train set and validation set
valid_x = train_x[ind[0:int(0.2 * n)]]
... | The code trains a machine learning model for time series classification using data augmentation (slicing, moving average, downsampling) and early stopping. It preprocesses training/validation/test data, constructs a model with dynamic input shapes, trains it with validation-based stopping, and evaluates performance. Me... | def train(self, x_train, y_train, x_test, y_test,y_true, pool_factor, filter_size):
window_size = 0.2
n_train_batch = 10
n_epochs = 200
max_train_batch_size = 256
# print('Original train shape: ', x_train.shape)
# print('Original test shape: ', x_test.shape)
# s... |
def initial_folders(directory):
'''initialise the folder in the directory and create if the directory does not exist'''
if not os.path.exists(directory):
os.makedirs(directory)
print(directory + ' is created')
else:
for root, dirs, files in os.walk(directory, topdown=False):
... | The function prepares audio data for enrollment and verification by downloading audio files from specified directories, handling impulse responses if required, and manipulating audio data based on configuration flags. It creates structured output directories, redownloads audio if instructed, and processes enrollment/ve... | def data_prep(config):
audio_directory = config['audio_directory']
impulse_directory = config['impulse_directory']
output_directory = config['output_directory']
channel = config['channel']
enrol_dir = os.path.join(output_directory, channel+'/'+'enrol')
enrol_audio_dir = os.path.join(audio_dir... |
def is_done(self):
return self.is_win(self.enemy_pieces) or self.is_draw() or self.is_win(self.pieces)
def is_win(self, pieces):
if pieces[0] == 1 and pieces[1] == 1 and pieces[2] == 1:
return True
if pieces[3] == 1 and pieces[4] == 1 and pieces[5] == 1:
return True
if pieces[6] == 1 and pie... | This function determines the game's outcome by checking if the game is done. If so, it checks if the enemy has won (return 'lose'), if the player has won (return 'win'), or if it's a draw (return 'draw'). If the game isn't done, it returns 'not finished'. | def is_win_or_lose(self):
if self.is_done():
if self.is_win(self.enemy_pieces):
return 'lose'
elif self.is_win(self.pieces):
return 'win'
elif self.is_draw():
return 'draw'
return 'not finished' |
def fen_to_planes(self, to_move, fen):
planes = self.populate_piece_planes(fen)
to_move = torch.full((1, 8, 8), to_move)
planes = torch.cat((planes, to_move))
return planes
def elo_to_plane(elo):
AVG = 1500 # Approximate values, worth taking another
STDDEV = 350 # look at once a ... | This function converts chess game data into a concatenated tensor representation. It first transforms the FEN string into planes, then appends Elo ratings (white or black based on turn), time control info, and evaluation data into a single tensor for neural network input. | def to_planes(self, to_move, fen, welo, belo, tc, eval):
planes = self.fen_to_planes(to_move, fen)
planes = torch.cat((planes, elo_to_plane(welo if to_move == 1.0 else belo)))
planes = torch.cat((planes, tc_to_plane(tc)))
planes = torch.cat((planes, eval_to_plane(eval)))
return p... |
def side_to_move(self):
return 1.0 if self.fen.split(' ')[1] == "w" else -1.0
def fen_to_planes(self):
planes = self.populate_piece_planes()
to_move = torch.full((1, 8, 8), self.side_to_move())
planes = torch.cat((planes, to_move))
return planes
def elo_to_plane(elo):
AVG = 1... | The function `to_planes` converts a game state into a tensor representation by concatenating multiple feature planes. It first generates base planes from the FEN, then appends planes for Elo rating (depending on the side to move), time control, and evaluation. The result is a combined tensor encoding the game's strateg... | def to_planes(self):
to_move = self.side_to_move()
planes = self.fen_to_planes()
planes = torch.cat((planes, elo_to_plane(self.game.welo if to_move == 1.0 else self.game.belo)))
planes = torch.cat((planes, tc_to_plane(self.game.tc)))
planes = torch.cat((planes, eval_to_plane(self... |
def seed_to_data(seed):
return seed_to_alpha(int(to_hex(96, 16, seed), 36)), to_hex(10, 96, str(int(to_hex(96, 16, seed), 36)))
def pass_to_seed(password, salt):
salt = sha512(sha512(b85encode(salt.encode())).hexdigest().encode()).hexdigest()
inp = f"{salt[:64]}{password}{salt[64:]}"
return to_hex(16, 9... | The main task of the code is to encrypt a given `text` using a `key` and `salt`. It generates encryption parameters (`alpha`, `shift_num`) from the key and salt via `pass_to_seed` and `seed_to_data`, then applies the `encrypt` function with these parameters and the salt to produce the encrypted output. | def encrypt_key(text, key, salt):
alpha, shift_num = seed_to_data(pass_to_seed(key, salt))
return encrypt("enc", text, alpha, shift_num, salt) |
def get_file_size(file):
file_size_kb = path.getsize(file)/1024
if file_size_kb > 9999:
file_size_mb = file_size_kb/1024
if file_size_mb > 2999:
return f"{round(file_size_mb/1024,2)}GB"
else:
return f"{round(file_size_mb,2)}MB"
else:
return f"{round(fi... | The code encrypts or decrypts a file using a key and salt, writing the result to an output file. It checks if the input file exists, processes the encryption/decryption logic based on the 'enc' parameter, and handles both binary and text outputs. The function also estimates processing time and validates the encryption ... | def encrypt_file(enc, file, key, salt, file_output):
start = time()
if enc.lower() in ["e", "en", "enc", "encrypt", "d", "de", "dec", "decrypt"]:
if path.exists(file):
file_name = file.split("/")[-1].split(".")[:-1] # file_type = file.split("/")[-1].split(".")[-1:]
print(f"{file... |
def seed_to_data(seed):
return seed_to_alpha(int(to_hex(96, 16, seed), 36)), to_hex(10, 96, str(int(to_hex(96, 16, seed), 36)))
def pass_to_seed(password, salt):
salt = sha512(sha512(b85encode(salt.encode())).hexdigest().encode()).hexdigest()
inp = f"{salt[:64]}{password}{salt[64:]}"
return to_hex(16, 9... | The code decrypts an encrypted text `e_text` using a `key` and `salt` by generating transformation parameters (`alpha1`, `shift_num`) from the key and salt, then invoking an `encrypt` function with a "dec" flag to reverse the encryption process, outputting the decrypted result. | def decrypt_key(e_text, key, salt):
alpha1, shift_num = seed_to_data(pass_to_seed(key, salt))
return encrypt("dec", e_text, alpha1, shift_num, salt, "join_dec") |
def distances() -> defaultdict[Point, dict[Point, int]]:
dists = defaultdict(dict)
for point in ALL_POINTS:
d = deque([(point, 0)])
seen = set([point])
while d:
current, dist = d.popleft()
for adj in adjacent(current):
if adj in ALL_POINTS and adj ... | This code solves a pathfinding problem where amphipods must move to their designated rooms with minimal energy cost. It uses Dijkstra's algorithm, tracking states with a priority queue, and calculates energy based on movement distances and type-specific values. The goal is to find the minimum energy required to reach a... | def part_2(loc: str = DEFAULT_INPUT) -> int:
init_open_points = set()
init_a_s = set()
init_b_s = set()
init_c_s = set()
init_d_s = set()
energy = {'A': 1, 'B': 10, 'C': 100, 'D': 1000}
with open(loc) as f:
for y, row in enumerate(f.readlines()):
if y >= 3:
... |
def gradient(img):
# kernely = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])
# kernelx = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])
laplacian = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])
edges = cv.filter2D(img, cv.CV_8U, laplacian)
# cv.imshow('dst', edges)
# cv.waitKey(0)
# cv.de... | This code performs image inpainting using the Criminisi algorithm. It identifies boundary regions in a mask, calculates confidence and data terms for candidate patches, selects the best matching patch via SSD comparison, and iteratively fills missing regions. The process continues until the mask boundary is fully fille... | def criminisi_similar_regions(img, mask, dimension_global):
lines = img.shape[0]
cols = img.shape[1]
mask = cv.resize(mask, (cols, lines))
contour_image = gradient(img)
# b = np.where(mask != 0)
# for i in range(len(b[0])):
# for pixel in range(3):
# x = b[0][i]
# ... |
def gradient(img):
# kernely = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])
# kernelx = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])
laplacian = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])
edges = cv.filter2D(img, cv.CV_8U, laplacian)
# cv.imshow('dst', edges)
# cv.waitKey(0)
# cv.de... | The code enhances an image by iteratively detecting boundaries using a mask, calculating data terms for boundary points, sorting them, and applying a patch-filling algorithm (fill_olivera) to refine regions. After processing all patches, it applies anisotropic diffusion to smooth the image, returning the enhanced resul... | def DD(img, mask, dimension_global):
lines = img.shape[0]
cols = img.shape[1]
mask = cv.resize(mask, (cols, lines))
contour_image = gradient(img)
while True:
boundary = get_boundary(mask)
if len(boundary[0]) == 0:
break
# print(len(boundary[0]), len(boundary[1]... |
def gradient(img):
# kernely = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])
# kernelx = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])
laplacian = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])
edges = cv.filter2D(img, cv.CV_8U, laplacian)
# cv.imshow('dst', edges)
# cv.waitKey(0)
# cv.de... | This code performs image inpainting by iteratively identifying boundary regions, selecting optimal patches via SSD matching, and filling missing areas using gradient and mask information, followed by anisotropic diffusion for smoothing. | def DS(img, mask, dimension_global):
lines = img.shape[0]
cols = img.shape[1]
mask = cv.resize(mask, (cols, lines))
contour_image = gradient(img)
dim = dimension_global * 2 + 1
patches = split(img, mask, dim, dim)
Cp = np.ones([lines, cols])
count = 0
while True:
count +=... |
def gradient(img):
# kernely = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])
# kernelx = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])
laplacian = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]])
edges = cv.filter2D(img, cv.CV_8U, laplacian)
# cv.imshow('dst', edges)
# cv.waitKey(0)
# cv.de... | The code performs image enhancement by iteratively processing image boundaries using confidence and data terms, sorting boundary points, applying a filling algorithm, and applying anisotropic diffusion to smooth the result. It uses a mask to guide boundary detection and prioritizes regions based on calculated confidenc... | def CDD(img, mask, dimension_global):
lines = img.shape[0]
cols = img.shape[1]
mask = cv.resize(mask, (cols, lines))
contour_image = gradient(img)
Cp = np.ones([lines, cols])
while True:
boundary = get_boundary(mask)
if len(boundary[0]) == 0:
break
# print... |
def get_gt(img_name):
for ind, cls in enumerate(cf.Class_label):
if cls in img_name:
return ind
raise Exception("Class label Error {}".format(img_name))
def display_gt_statistic(self):
print(' -*- Training label -*-')
print(' Total data: {}'.format(len(self.datas)))
... | The main task of the code is to load and prepare image datasets for training or testing by collecting image paths and their corresponding ground truths from specified directories. It filters valid images, counts ground truth classes, applies data augmentation for training, and optionally shuffles the dataset. The funct... | def prepare_datas(self, shuffle=True):
if self.phase == 'Train':
dir_paths = cf.Train_dirs
elif self.phase == 'Test':
dir_paths = cf.Test_dirs
print('------------\nData Load (phase: {})'.format(self.phase))
for dir_path in dir_paths:
files = []
... |
def print_stats():
os.system('cls')
rpgfunc.header()
print(' '.join('STATS'))
print("*" * 88)
print('Player' + ' ' * 28 + 'Unknown_Big_Guy')
print()
for item in stats:
print(item + ' : ' + str(stats[item]) + ' ' * (22 - len(str(stats[item]))) + '|', end='')
print(item + ... | This function simulates a turn-based RPG battle where the player and enemy take turns attacking, dodging, or using skills. It initializes health stats, displays game state, processes user input for actions, applies damage, and checks for victory/defeat when either health reaches zero. The loop continues until a winner ... | def fight():
stats["Health"] , enemy_stats["Health"] = 100, 150
a = True
while True:
os.system('cls')
rpgfunc.header()
print_stats()
print(">>| What would you do\n[1] Attack\n[2] Dodge\n[3] Use skill")
user_choice = input("\n\nEnter: ")
if user_choice... |
def analyze(artist_json):
# Query the database to check the gender of the artist
id = artist_json['id']
artist = artist_json['name']
result = analyze_from_database(id)
artist_image = ""
if(len(artist_json['images']) > 0):
artist_image = artist_json['images'][0]['url']
popularity = s... | This code authenticates with Spotify's API, analyzes a playlist's artist diversity by gender, categorizes artists into gender groups, calculates underrepresentation statistics, and generates recommendations while excluding existing artists. It tracks top genres, updates a database for underrepresented artists, and comp... | def run(self):
CLIENT_ID = os.getenv('CLIENT_ID')
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
AUTH_URL = 'https://accounts.spotify.com/api/token'
# POST
auth_response = requests.post(AUTH_URL, {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
... |
def _lang_token_index(dictionary, lang: str) -> int:
return dictionary.index(_lang_token(lang))
def _langpair_dataset(
self, src: FairseqDataset, tgt: FairseqDataset
) -> LanguagePairDataset:
return LanguagePairDataset(
src,
src.sizes,
self.dictionary,
... | The function loads a monolingual dataset, appends a language token, creates a language pair dataset (tgt, tgt), and prepends a language BOS token to the target. It returns a modified FairseqDataset for training, where (generated_src, tgt) pairs are dynamically created during training, enabling multilingual modeling wit... | def load_bt_dataset(self, data_path: str, lang: str) -> FairseqDataset:
"""The BT dataset is generated with (tgt, tgt) pairs.
The actual translation to a (generated_src, tgt) pair
is done on the fly during training.
"""
mono_dataset = data_utils.load_indexed_dataset(
... |
def get_other_lang(self, lang):
select_from_langs = [l for l in self.mono_langs if l != lang]
num_candidates = len(select_from_langs)
assert num_candidates in [1, 2]
if num_candidates == 1:
return select_from_langs[0]
else:
# TODO: should we sample based ... | The main task of this code is to perform a training step for a backtranslation model, handling multiple datasets. It conducts backtranslation between language pairs, computes loss using a given criterion, performs backpropagation with an optimizer, and aggregates results including loss, sample size, and logging outputs... | def train_step(
self, sample, model, criterion, optimizer, update_num, ignore_grad=False
):
model.train()
model.set_num_updates(update_num)
agg_loss, agg_sample_size, agg_logging_output = 0.0, 0.0, defaultdict(float)
dataset_keys = self.datasets["train"].datasets.keys()
... |
def oneFile(self):
Core().MainCore(translateThat=self.path, From=self.src, To=self.dest, name=re.split(r"(/|\\)", self.path)[-1][:-4], total=1, progrss=100)
self.moving(re.split(r"(/|\\)", self.path)[-1], 0)
def onlyPath(self):
theCore = Core()
the_self_path = self.getSrt(self.path)
l = len(the_self... | This code initializes an object to handle file or path operations based on the 'type' parameter. It sets attributes like path, destination, source, and file lists, then triggers specific methods (`oneFile`, `onlyPath`, `fullPath`) depending on the 'type' value, enabling flexible file/path processing with error handling... | def __init__(self, path, type, dest, src) -> None:
global TheRand
self.random = TheRand
#region Variables
self.path = path
self.dest = dest
self.src = src
self.FilesWithPaths = []
self.names = []
self.foldersName = []
#endregion
if type == "file":
self.oneFile()
e... |
def update_hourly_road_time(self, h_index):
''' For each _out to _in edge in the graph update edge time '''
for edge in self.station_g.edges:
self.change_hourly_road_time(edge[0], edge[1], h_index)
def step(self, h_step, i_step):
''' one simulation step '''
hour = h_step%24... | The code runs a simulation over a specified number of hours, updating hourly road times and simulating discrete time intervals. It iterates through each interval, executing simulation steps, recording data, updating charging times, and performing validation checks. After each hour, it increments the hour counter. Final... | def run(self):
''' Run the simulation; return the statistics '''
for h_step in tqdm(range(self.simulation_length)): # go for simulation_length in hours
self.update_hourly_road_time(h_step)
for i_step in range(int(1/self.time_interval)): # go in interval segments
s... |
def _calculate_timedelta(self, completed, last_completed):
"""
Is called if there is at least one completion entry in the completions table. Calculates the timespan between
the last completion and the current completion event according to the periodicity of the habit.
:param completed: t... | The function `complete_habit` determines if a habit should be marked as completed, broken, or ignored based on the time since its last completion. It retrieves the last completion date from the database, calculates the time difference between the current and last completion, and updates the habit’s status using helper ... | def complete_habit(self, db, completed=datetime.today()):
"""
Fetches the last completion date from the completions table and compares the current completion date against it.
Calls the corresponding functions to either break the habit, check off the habit or do nothing when the habit is
... |
def _parse_time(
years=150, climate=True, nodrift=False, skipna=False, **constraints
):
"""
Parse variables related to time standardization and create a file suffix.
Parameters
----------
constraints : bool, optional
Whether to allow constraint keyword arguments.
**kwargs
Se... | The function `process_files` standardizes and averages climate model data by repairing files, aligning time dimensions, and harmonizing vertical and horizontal grids. It processes input files to ensure consistent formatting, handles dependencies, and outputs structured data in specified directories. The task involves r... | def process_files(
*paths,
output='~/data',
constants='~/data/cmip-constants',
facets=None,
vertical=True,
horizontal=True,
overwrite=False,
logging=False,
dryrun=False,
nowarn=False,
**kwargs,
):
"""
Average and standardize files downloaded with a wget script.
P... |
def makeGraph(file):
edges = []
with open(file) as file:
for line in file: #Loop through file
if(line != "END"):
try:
splitted = line.split()
edges.append([splitted[0],splitted[1],splitted[2]]) ... | The main task of the code is to perform graph traversal or pathfinding using specified algorithms (BFS, DFS, UCS, or A*). It reads a graph from a file, constructs it, and applies the chosen algorithm to find a path from a start node to an end node. The 'heuristic' parameter is specifically used by the A* algorithm to g... | def main(typeG, file, start, end, heuristic):
graph = makeGraph(file) #Create the graph
if(typeG == "bfs"):
bfs(graph, start, end)
elif(typeG == "dfs"):
dfs(graph, start, end)
elif(typeG == "ucs"):
ucs(graph, start, end)
elif(typeG == "astar"):
astar(graph, start... |
def add_not_sure_edge(self):
for src, adj in self.Gp.E.items():
src_connected = self.config.get_vehicle_by_id(src[0]).connected
for *dst, edge_type in adj:
dst = tuple(dst)
dst_connected = self.config.get_vehicle_by_id(dst[0]).connected
if ... | The main task of the code is to process a graph by adding uncertain edges, constructing a wait-for graph, removing special cycles, and returning the configurations of removed elements. | def run(self):
self.add_not_sure_edge()
self.build_wait_for_graph()
self.special_cycle_removal()
return self.removed_config |
def checkWaterStandStatus(self):
if(self.customer.waterColumn.bottleInStand != None):
if(self.customer.waterColumn.bottleInStand.bottleStatus < self.customer.consumptionRate):
self.customer.robotGrabBottleFromStand()
self.customer.robotGrabBottleFullShelf()
def checkReplenish(self):
... | The method performs water level checks, replenishment checks, triggers leak replenishment with 2% probability, and executes water control operations to maintain system stability. | def aips(self):
self.checkWaterStandStatus()
self.checkReplenish()
if(random.randint(1,30) < 2):
self.replenishLeak()
self.waterControl() |
def resample(self, path, n):
if n <= 1:
return path
interval = self.path_length(path) / (n - 1)
## fix undershot paths
interval *= 0.975
dist = 0
## create a copy path
copy = path
## create return path
new_path = pth.Path()
... | The code preprocesses a path by resampling points, optionally applying protractor vectorization, rotating to a zero angle, scaling to a standardized square size, and translating to the origin, returning the normalized path for consistent gesture recognition or analysis. | def preprocess(self, path):
## resample the points
new_path = self.resample(path, dollar.Dollar.prefs["n_points"])
## performing protractor preprocessing
if self.use_protractor:
return self.vectorize(new_path, False)
## rotate to indicative angle
new_path = ... |
def preprocess(self, path):
## resample the points
new_path = self.resample(path, dollar.Dollar.prefs["n_points"])
## performing protractor preprocessing
if self.use_protractor:
return self.vectorize(new_path, False)
## rotate to indicative angle
new_path = ... | This function recognizes a given path by comparing it against preprocessed templates using either cosine distance (if protractor is enabled) or a custom distance metric. It calculates similarity scores for each template, sorts them in descending order, and returns the ranked list of scores. Preprocessing is optional, a... | def recognize(self, path, templates={}, preprocess=False):
## if no specified template dict, set to preprocessed dictionary formed at instantiation
if templates == {}:
templates = self.preprocessed
## scores array
scores = []
if len(path) < 1:
return
... |
def calculate_entropy(d: Data, data : []):
result = 0
map_class = {}
for value in data:
class_value = value[d.attributes.index(d.class_variable)]
if class_value not in map_class:
map_class[class_value] = 1
else:
map_class[class_value] += 1
total_size = l... | This function selects the optimal attribute for splitting in a decision tree using information gain. It calculates entropy for each attribute, compares gains against a threshold, and returns the attribute with the highest gain (if exceeding the threshold), along with its split value and type. If no valid attribute is f... | def selectSplittingAttribute_information_gain(d: Data, data: [], a: [],threshold: float):
total_enthropy = calculate_entropy(d, data)
enthropy_map = {}
alpha_attribute = {}
for attr in a:
categorical = d.categorical_numerical[attr]
if categorical == 'numerical': #numerical
al... |
def calculate_entropy(d: Data, data : []):
result = 0
map_class = {}
for value in data:
class_value = value[d.attributes.index(d.class_variable)]
if class_value not in map_class:
map_class[class_value] = 1
else:
map_class[class_value] += 1
total_size = l... | This function selects the optimal attribute for splitting in a decision tree using the information gain ratio. It calculates total entropy, computes information gain and intrinsic information for each attribute, and determines the attribute with the highest gain ratio. If the selected attribute's entropy exceeds a give... | def selectSplittingAttribute_information_gain_ratio(d: Data, data: [],a: [],threshold: float):
total_enthropy = calculate_entropy(d, data)
enthropy_map = {}
gain_ratio = {}
alpha_attribute = {}
for attr in a:
categorical = d.categorical_numerical[attr]
if categorical == 'numerical':
... |
def find_most_frequent_label(d):
map_class = {}
for value in d:
if value not in map_class:
map_class[value] = 1
else:
map_class[value] += 1
return max(map_class, key=map_class.get)
def selectSplittingAttribute_information_gain_ratio(d: Data, data: [],a: [],threshold:... | This function implements the C4.5 decision tree algorithm to recursively construct a classification tree. It checks for homogeneous data to create leaf nodes, selects splitting attributes using information gain/gain ratio, and handles both categorical (splitting by domain values) and numerical (splitting by threshold) ... | def algorithm_c45(d: Data, data: [], a: [], threshold: float, t: Node, gain_ratio : bool, ground_truth: dict):
d_value = data
documents = list(map(lambda x: x[d.index_class_variable], d_value))
d_class = [ground_truth[x] for x in documents]
#homogenous
if len(set(d_class)) == 1:
leaf_node ... |
def layer_T1(input_tensor, num_filters):
# Convolutional layer
x = conv_layer(input_tensor,
num_filters=num_filters,
kernel_size=(3, 3),
strides=1)
# Batch normalization layer
x = layers.BatchNormalization(momentum=0.9)(x)
# ReLU acti... | This code defines a neural network model called SRNet for image processing. It takes a 256x256 grayscale input and applies a sequence of custom layers (T1-T4) with increasing filter sizes to extract hierarchical features. The model processes the input through multiple convolutional blocks, progressively refining featur... | def create_SRNet(input_image_size):
# The input layer has the shape (256, 256, 1)
input_layer = layers.Input(shape=input_image_size)
x = layer_T1(input_layer, 64)
x = layer_T1(x, 16)
x = layer_T2(x, 16)
x = layer_T2(x, 16)
x = layer_T2(x, 16)
x = layer_T2(x, 16)
x = layer_T2(x,... |
def layer_T1(input_tensor, num_filters):
# Convolutional layer
x = conv_layer(input_tensor,
num_filters=num_filters,
kernel_size=(3, 3),
strides=1)
# Batch normalization layer
x = layers.BatchNormalization(momentum=0.9)(x)
# ReLU acti... | The main task of the code is to construct a regularized SRNet model for image processing. It defines a neural network with convolutional layers (layer_T1-T4) of increasing complexity, starting with input size (256, 256, 1), followed by feature extraction through multiple convolutional blocks, and ending with a fully co... | def create_regularized_SRNet(input_image_size):
# The input layer has the shape (256, 256, 1)
input_layer = layers.Input(shape=input_image_size)
x = layer_T1(input_layer, 64)
x = layer_T1(x, 16)
x = layer_T2(x, 16)
x = layer_T2(x, 16)
x = layer_T2(x, 16)
x = layer_T2(x, 16)
x =... |
def fill_username(self):
return self.find_and_fill_element(self.config.auth_username,
self.config.auth_username_field_name,
"input",
"(//input[((@type='text' or @type='email') and contai... | The code automates a login process using Selenium by navigating to a URL, handling proxy errors, dynamically locating and filling username/password fields, managing OTP if provided, and submitting the form while checking for success elements. It includes error handling for missing elements, proxy blocks, and login flow... | def login(self):
proxy_error = "This category is blocked: Private IP Addresses."
logging.info('authenticate using webdriver against URL: %s',
self.config.auth_login_url)
self.driver.get(self.config.auth_login_url)
# wait for the page to load
time.sleep(5)
... |
def setup_context(self, zap, target):
# Set an X-Scanner header so requests can be identified in logs
zap.replacer.add_rule(description='Scanner', enabled=True, matchtype='REQ_HEADER',
matchregex=False, matchstring='X-Scanner', replacement="ZAP")
context_name = 'ct... | The code authenticates to a target application using ZAP (Zed Attack Proxy) via multiple methods: 1) Selenium-based login if a URL is provided, 2) Bearer token authentication if specified, 3) Token endpoint authentication if configured. It sets up authentication context, handles exceptions, and ensures cleanup. If no a... | def authenticate(self, zap, target):
try:
# setup the zap context
if zap:
self.setup_context(zap, target)
# perform authentication using selenium
if self.config.auth_login_url:
# setup the webdriver
self.setup_webdr... |
def _get_distance_model():
model = transformers.AutoModel.from_pretrained('allenai/scibert_scivocab_cased')
tokenizer = transformers.AutoTokenizer.from_pretrained('allenai/scibert_scivocab_cased')
model.cuda()
return model, tokenizer
def _get_target_problems():
problems = ['-x - 3 + sqrt(3)',
'... | The code implements a genetic algorithm to evolve mathematical problems with high fitness. It mutates initial seeds, evaluates their fitness using a model, and stores novel, high-fitness problems in an archive. Selection (fitness/k-means) determines the next seed set, iterating until the archive reaches a size limit or... | def genetic_algorithm(
env, encoder, decoder, device, output_dir, mutation_params, fitness_type, ops,
seed_selection='kmeans',
basis='polynomial',
tau=0.1,
archive_size_terminate=1000,
generation_size=200,
seed_size=20,
max_generations=100,
target_... |
def refresh_users(self):
self.users = read_json(self.users_path)
def sort_inventory(self, user_id):
try:
self.refresh_users()
self.users[user_id] = dict(sorted(self.users[user_id].items(),key = lambda x:x))
self.update_users()
return True, 'Shop sorted suc... | The main task of the code is to retrieve and return a user's inventory after refreshing user data, sorting the inventory, and updating user information. It handles exceptions by returning an error response with details. | def get_user_inventory(self,user_id):
try:
self.refresh_users()
self.sort_inventory(str(user_id))
self.update_users()
return True, self.users[str(user_id)]['inventory']
except Exception as e:
return self.error_response('get_user_inventory',e) |
def get_interested_agents(track_index_to_predict, obj_trajs_full, current_time_index):
center_objects_list = []
for k in range(len(track_index_to_predict)):
obj_idx = track_index_to_predict[k]
center_objects_list.append(obj_trajs_full[obj_idx, current_time_index])
center_objects = np.stack(c... | The function prepares input data for a neural network by extracting and processing historical/future trajectories of agents, filtering relevant objects, generating masks, and structuring map polylines. It constructs a batch dictionary containing trajectory data, object types, traffic light info, and map features for mo... | def feed_data(cur_timestep,all_agent_trajs,dynamic_info,track_index_to_predict,sdc_track_index,obj_types,
obj_ids,scenario_id,all_polylines,dataset_cfg ):
obj_trajs_full = all_agent_trajs
obj_trajs_past = obj_trajs_full[:, cur_timestep-10:cur_timestep + 1]
obj_trajs_future = obj_trajs_full[:, ... |
def train_one_epoch(model, optimizer, train_loader, accumulated_iter, optim_cfg,
tbar, total_it_each_epoch, dataloader_iter, tb_log=None, leave_pbar=False, scheduler=None, show_grad_curve=False,
logger=None, logger_iter_interval=50, cur_epoch=None, total_epochs=None, ckpt_save_di... | The code trains a deep learning model over multiple epochs using a specified optimizer and data loader. It saves model checkpoints periodically, removes older ones to limit storage, evaluates model performance on a test set, and retains the best-performing model based on metrics like mAP. The function also logs trainin... | def train_model(model, optimizer, train_loader, optim_cfg,
start_epoch, total_epochs, start_iter, ckpt_save_dir,
ckpt_save_interval=1, max_ckpt_save_num=50, tb_log=None,
scheduler=None, test_loader=None, logger=None, eval_output_dir=None, cfg=None,
logger... |
def get_interested_agents(track_index_to_predict, obj_trajs_full, current_time_index):
center_objects_list = []
for k in range(len(track_index_to_predict)):
obj_idx = track_index_to_predict[k]
center_objects_list.append(obj_trajs_full[obj_idx, current_time_index])
center_objects = np.stack(c... | The `feed_data` method prepares input data for a model by extracting and processing agent and map information around a specified time step. It slices historical and future trajectories, identifies central agents, generates masked trajectory data, traffic light information, and map polylines. The processed data, includi... | def feed_data(self, cur_timestep, override=False):
obj_trajs_full = self.all_agent_trajs
obj_trajs_past = obj_trajs_full[:, cur_timestep-10:cur_timestep + 1]
obj_trajs_future = obj_trajs_full[:, cur_timestep + 1:]
traffic_lights = self.dynamic_info
center_objects, track_index_to... |
def get_delete_list(wd: str, all_files: list):
"""[summary]
Args:
wd (str): the lambda python project working directory
all_files (list): [description]
Returns:
[type]: [description]
"""
slim_patterns = get_slim_pattern(wd)
bad_files = {}
for pattern in slim_pattern... | The main task of the code is to reduce the size of a Python package by identifying and deleting unnecessary files from a temporary directory. It processes a list of files, checks each for safe deletion, removes eligible files, and returns the updated list of remaining files in the directory. | def slim_down_package(wd: str, pip_tmp_dir: str, all_files: list):
"""[summary]
Args:
wd (str): the lambda python project working directory
all_files (list): [description]
"""
logger.info(
"starting packages slim down for {} files ...".format(len(all_files)))
files_to_delete... |
def list_all_files(dir_name: str, recursive: bool = True):
"""[summary]
Args:
dir_name (str): [description]
recursive (bool, optional): [description]. Defaults to True.
Returns:
[type]: [description]
"""
files = _list_all_files(dir_name, recursive)
new_files = [remove_p... | The main task of the code is to finalize a list of Python packages by writing their filenames to a file, copying them from a temporary directory to the working directory, and cleaning up the temporary directory. It logs the process, lists non-recursive files in the temporary directory, writes them to a file, copies spe... | def finalize_packages_list_as_files(wd: str, pip_tmp_dir: str, files: list):
"""[summary]
Args:
wd (str): the lambda python project working directory
files (list): [description]
"""
global _globals
logger.info(
"starting package finalization as zip in({}) for: {} files".form... |
def install_pip_requirements(wd: str, pip_tmp_dir: str):
"""[summary]
Args:
wd ([type]): [description]
Raises:
PIPInstall: [description]
"""
p_dir = os.path.join(wd, pip_tmp_dir)
clean_up_pip(wd, pip_tmp_dir)
logger.info("starting pip requirements installation in({})".forma... | The function prepares a Lambda package by installing Python dependencies in a temporary directory, reducing the package size by retaining only necessary files, and finalizing the output as either individual files or a ZIP archive based on the specified format. | def prepare_lambda_package(wd: str, output_format: str):
"""Preparation steps such as pip install requirements
Args:
wd (str): the lambda python project working directory
"""
logger.info(
"starting lambda_package finalization for({}) as ({}) format".format(wd, output_format))
pip_tm... |
def check_db_return(result):
"""Use to close program if the database returns an error
Keyword arguments:
result -- return value from DBManager function
"""
if (result == -1):
print("Database error, check errors.txt for problem.")
exit(1)
def choice_is_valid(choice, max):
"""... | The main task of the code is to present a menu of quiz options (all quizzes, marked questions, or return to the main menu) to the user, validate their input, and return a Quiz object containing the selected questions. If no valid quiz is chosen or marked questions are unavailable, it returns None. It interacts with a d... | def select_quiz():
"""Outputs a numbered list of all the quiz options the user can pick
from including a category for all quizzes, marked questions, and an
optiont to return to the main main_menu.
Returns:
A Quiz object containing all the quiz questions or None
if the user does not sele... |
def reset_checks():
global track_list
for a in range(9):
track_list[0][a] = [[],[],[]]
for b in range(3):
track_list[0][a][b] = [1,1,1]
for a in range(9):
track_list[1][a] = [[],[],[]]
for b in range(3):
track_list[1][a][b] = [2,2,2]
for a in range... | The main task of the code is to solve a Sudoku puzzle by iteratively checking constraints, filling cells, and halting when no further progress can be made. It uses a loop to repeatedly apply checks and updates until the working Sudoku state stabilizes, at which point it exits the solving loop. | def solve():
reset_checks()
while True:
global output_sudoku
check_all()
fill()
#if it is unable to solve further breaks out of solving loop
if work_sudoku == output_sudoku:
break
output_sudoku = copy.deepcopy(work_sudoku) |
def reset_checks():
global track_list
for a in range(9):
track_list[0][a] = [[],[],[]]
for b in range(3):
track_list[0][a][b] = [1,1,1]
for a in range(9):
track_list[1][a] = [[],[],[]]
for b in range(3):
track_list[1][a][b] = [2,2,2]
for a in range... | The code's main task is to solve a Sudoku puzzle using a brute-force recursive approach. It initializes checks, generates possible solutions via recursion, and selects the first valid solution. If no solutions exist, it outputs "can't solve it". The function copies the initial Sudoku grid, explores all potential number... | def brute_force():
reset_checks()
check_all()
global work_sudoku
global output_sudoku
possible_solves = recursion_check(work_sudoku, copy.deepcopy(empty_sudoku), 0)
if len(possible_solves) == 0:
print("cant solve it")
return
output_sudoku = copy.deepcopy(possible_solves[0]) |
def build_graph(edus, tree_infos):
print("going to building graph ")
G = nx.DiGraph()
edus_ob = {}
for i, edu in enumerate(edus):
edus_ob[str(i + 1)] = re.sub('\s+', ' ', edu.strip())
edus_ob_id = [int(key) for key in edus_ob]
print("edus_ob_id ", edus_ob_id)
print("len edus , edus... | The function constructs a discourse structure (ddt) from educational units (edus) using a graph, linking nodes based on relations. It extracts top-level nodes at varying depths (1–3) related to claims, returning the graph, ddt, and hierarchical node sets for analysis of discourse organization and claim connectivity. | def li_structure(edu_file, bracket_file, article_text, id_ind, claim_edus_list):
# print("LIST of EDUS")
# for j, edu in enumerate(edu_file):
# print(j + 1, edu)
if len(bracket_file) == 1:
print("bracket length 1")
return edu_file[0], edu_file[0], edu_file[0], edu_file[0]
ddt = ... |
def GetPlayerID(self, player_types=['picture', 'audio', 'video']):
data = self.SendCommand(RPCString("Player.GetActivePlayers"))
result = data.get("result", [])
if result:
for r in result:
if r.get("type") in player_types:
return r.get("playerid")
... | The main task of the code is to stop a player's action by retrieving their ID and sending an RPC command. It first gets the player's ID using `GetPlayerID()`, checks if it exists, and if valid, sends a "Player.Stop" RPC request with the player ID as a parameter to halt their activity. | def PlayerStop(self):
playerid = self.GetPlayerID()
if playerid is not None:
return self.SendCommand(RPCString("Player.Stop", {"playerid": playerid})) |
def GetArtistAlbums(self, artist_id):
return self.SendCommand(RPCString("AudioLibrary.GetAlbums", filters=[{"artistid": int(artist_id)}]))
def GetAlbums(self, sort=None, filters=None, filtertype=None, limits=None):
return self.SendCommand(RPCString("AudioLibrary.GetAlbums", sort=sort, filters=filters, f... | This function searches for an album by name, optionally filtered by an artist ID. It retrieves album data via `GetArtistAlbums` or `GetAlbums`, checks for valid results, and uses `search_db` to find matches. If found, it returns a list of tuples containing album IDs and labels. | def FindAlbum(self, album, artist_id=None):
self.logger.info(f'Searching for album: {album}')
located = []
if artist_id:
albums = self.GetArtistAlbums(artist_id)
else:
albums = self.GetAlbums()
if 'result' in albums and 'albums' in albums['result']:
... |
def get_latest_NASA_news():
NASA_MARS_url = "https://mars.nasa.gov/news/"
news_soup = get_soup_object(NASA_MARS_url)
latest_news = news_soup.find_all("div",{"class":"list_text"})[0]
return {
"title":latest_news.find("div",{"class":"content_title"}).text,
"content":latest_news.find("div",... | The code's main task is to aggregate Mars-related data by calling multiple functions to retrieve the latest NASA news, Mars images, facts, temperature, and hemisphere data, then compiling them into a dictionary with a timestamp for structured output. | def scrape():
mars_news = get_latest_NASA_news()
mars_img = get_MARS_img()
mars_facts = get_MARS_facts()
mars_temp = get_MARS_temperature()
mars_hm_data = get_MARS_hemisphere_data()
return {
"date":datetime.now(),
"news":mars_news,
"featured_img":mars_img,
"facts"... |
def expectPeek(self, tt: TokenType):
"""Check if next token is a given TokenType
without advancing the internal state"""
if self.nextTokenIs(tt):
return True
return False
def readToken(self):
"""Advance internal state of the parser."""
self.currTok = self.next... | The main task of the code is to parse a datetime string enclosed in square brackets, verifying the presence of a date, a space separator, and a time component. It sequentially checks for required tokens (LSQUARE, DATE, SPACE, TIME, RSQUARE), consuming them upon successful validation, and returns True if all components ... | def parseDateTime(self):
"""Parse dates in datetime format"""
if not self.expectPeek(TokenType.LSQUARE):
return False
self.readToken()
if not self.eatDate():
return False
if not self.expectPeek(TokenType.SPACE):
return False
self.read... |
def parseIP(self):
""""""
while not self.currTokenIs(TokenType.HYPHEN) and not\
self.currTokenIs(TokenType.EOF):
self.readToken()
if self.expectPeek(TokenType.SPACE):
self.readToken()
return True
def parseDateTime(self):
"""Parse dates in... | The main task of the code is to parse a structured statement by sequentially validating and extracting components like IP address, date-time, header, status, and file size from a token stream. It ensures proper spacing between tokens and checks for an EOF terminator, returning True if all parsing steps succeed or False... | def parseStatement(self, out):
""""""
self.parseIP()
if not self.parseDateTime():
return False
if not self.expectPeek(TokenType.SPACE):
return False
self.readToken()
if not self.parseHeader(out):
return False
if not self.exp... |
def emoji_selection(snow_level):
'''
Select the right emoji for the snow level.
'''
# create ranges to choose emoji
emojis = ["heart-eyes", "cool-face", "light-smile", "unamused"]
if snow_level <= 20:
emoji = emojis[3]
elif snow_level > 20 and snow_level <= 40:
emoji = emojis... | The function generates visual elements for a Huggingface app by creating snow-level emojis from predictions, saving them locally, and uploading to Hopsworks. It also produces and uploads a bar chart of predictions and a historical accuracy plot. The main task is to prepare and store these images for app use. | def build_pictures_for_app(project, pred_snow):
'''
Create a plot and six emojis to store in Hopsworks
for later use in the Huggingface app
'''
dataset_api = project.get_dataset_api()
# create emoji for each prediction day
for index in range(1,len(pred_snow)+1):
snow = pred_snow... |
def add_entry_fields(self, x, y):
"""Add the 3 fields for filename, filepath and id"""
filepath = Label(self.root, text='Path', font = ("bold", 10))
filepath.place(x=x,y=y)
self.root.update()
filename = Label(self.root, text="Filename", font = ("bold", 10))
filename.plac... | This code initializes a PDF administrator GUI using Tkinter, setting up a main window with input fields, list boxes, scroll bars, buttons, and checkboxes. It configures the window's layout, dynamically positions UI elements, integrates a model to update data, and launches the GUI event loop for interaction. | def __init__(self, model):
"""init the main window"""
self.flags = None
self.sel = None
self.model = model
self.root = Tk()
self.root.geometry("700x400")
self.root.title("PDF administrator")
self.model.update_numbers()
controlsX = 10
con... |
def _get_cluster(self, name):
args = [
'k3d',
'cluster',
'ls',
'-o=json',
name]
result = subprocess.run(args, check=False, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode == 0:
clusters = json.loads(result.stdout)
if len(clusters) > 1... | The main task of the code is to manage a Kubernetes cluster by either starting an existing cluster or creating a new one. It retrieves the network CIDR from the Docker network associated with the cluster and returns the result along with a status indicating if changes were made. The function uses parameters to determin... | def main(self):
name = self.params['name']
cluster = self._get_cluster(name)
if cluster:
changed = self._start_cluster(cluster)
else:
changed = self._create_cluster()
network_cidr = self.docker_client.networks.get(f'k3d-{name}').attrs['IPAM']['Config'][0]['Subnet']
self.exit_json(cha... |
def create_student_answers(file_name, question_counts, target, id_col='Student ID'):
"""
Parses the given excel to get student numbers and links of the files of
submissions. Contains more code than required as remainder for xlrd package
that has been used in this function.
Args:
:param file... | The code processes student answer files by parsing Excel data, downloading files from a server, cleaning up existing outputs, executing R scripts to generate answer keys and grades, and publishing results to an admin spreadsheet. | def main(args):
if args.file_locs is not None:
# Parse xlsx file
student_answers = [create_student_answers(SA_location, q_counts,
args.target, args.id_col)
for q_counts, SA_location in zip(args.counts,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.