dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def wait(self, timeout=None):
if timeout is None:
timeout = 10
return WebDriverWait(self.driver, timeout=timeout)
def click(self, locator, timeout=None) -> WebElement:
self.find(locator, timeout=timeout)
elem = self.wait(timeout).until(EC.element_to_be_clickable(locator))
... | This code logs out a user by waiting for the page content to load, clicking the profile button, locating the logout button, and using JavaScript to trigger the logout action. | def logout(self):
self.wait().until(EC.visibility_of_element_located(BL.PAGE_CONTENT))
self.click(BL.PROFILE_BTN)
right_menu = self.find(BL.LOGOUT_BTN)
self.driver.execute_script("arguments[0].click()", right_menu) |
def clearUnderlying():
global underlying
underlying = []
def setLines(l):
global curlines
curlines = l
channelsToExportVar.set(l)
def getDm():
a = [*getDmPeople(), *getDmGroups()]
return a | The function `loadDm` clears existing underlying data and sets lines based on data retrieved by `getDm`, likely preparing or updating a data structure or visualization. | def loadDm(*a):
clearUnderlying()
setLines(getDm()) |
def Get_InputData():
df = pd.read_excel('kdd_small.xlsx')
df = handle_non_numeric_data(df)
data = df.to_numpy()
return data
def initialize_network(n_inputs, n_hidden, n_outputs):
network = list()
hidden_layer = [{'weights':[random() for i in range(n_inputs + 1)]} for i in range(n_hidden)]
network.app... | The code defines a neural network prediction function that initializes a model with two hidden layers, trains it on input data using a specified learning rate and epochs, and evaluates performance by comparing predicted outputs to actual labels in the dataset. | def Prediction():
seed(1)
dataset = Get_InputData()
n_inputs = len(dataset[0]) - 1
n_outputs = len(set([row[-1] for row in dataset]))
network = initialize_network(n_inputs, 2, n_outputs)
train_network(network, dataset, 0.5, 20, n_outputs)
for row in dataset:
prediction = predict(net... |
def convertTrendToNum(trend):
'''
converts a trend to a ranked number
'''
if trend == 'None':
return 0
elif trend == 'pair':
return 1
elif trend == 'twoPair':
return 2
elif trend == 'trips':
return 3
elif trend == 'str8':
return 4
elif trend == 'flush':
return 5
elif trend ==... | The main task of the code is to determine the winning index from a list of hands based on their trend/value outcomes. It first identifies the maximum trend value, filters hands with that trend, and then sequentially compares pairs of hands using the `compareHands` function to eliminate weaker hands until a single winne... | def determineWinner(valueList):
'''
value list is the list of each hand's trend/value outcome.
will return the winning index of valueList
'''
tempDict = {}
for x in range(len(valueList)):
tempDict[x] = convertTrendToNum(valueList[x][0])
maxi = max(tempDict.values())
indexList = []
for x in tempDic... |
def giveShuffledDeck():
import random
deck = ['2H', '2S', '2C', '2D', '3H', '3S', '3C', '3D', '4H', '4S', '4C', '4D', '5H', '5S', '5C', '5D', '6H', '6S', '6C', '6D', '7H', '7S', '7C', '7D', '8H', '8S', '8C', '8D', '9H', '9S', '9C', '9D', '0H', '0S', '0C', '0D', 'JH', 'JS', 'JC', 'JD', 'QH', 'QS', 'QC', 'QD', 'KH', ... | The code simulates a poker game by dealing cards to players, generating community cards (river), evaluating hands against the river, determining the winner, and returning the winning hand or 'tie'. It also appends all hands to a data document for record-keeping. | def runGame(playerCount):
'''
Returns the winning hand; appends all hands to appropriate data doc
'''
deck = giveShuffledDeck()
playerList = []
for x in range(playerCount):
playerList.append([])
for y in range(2):
for x in range(playerCount):
card = deck.pop(0)
playerList[x].append(car... |
def getInputTwo():
while True:
inp = input("How many trials? (At least ten) ")
try:
if int(inp) > 9 and int(inp) != 0:
return int(inp)
else:
print("Invalid Input")
except:
print("Invalid Input")
def getInput():
while True:
inp = input("How many players are there? (M... | The main task of the code is to simulate multiple trials of a game with a specified number of players, record the winning hands in a file, sort the results, and calculate/win rate statistics. It collects data across trials, stores outcomes, and generates sorted output files for analysis. | def dataSide():
import time
trialCount = getInputTwo()
playerCount = getInput()
fileName = "data/" + str(playerCount) + "players.txt"
allHandsName = "data/" + str(playerCount) + "playersAllHands.txt"
winRateName = "data/" + str(playerCount) + "handWRs.txt"
for x in range(trialCount):
#time.sleep(.01)
... |
def make_secret_key():
"""
find secret key
I refered to this document for the size of key bits.
https://csrc.nist.gov/publications/detail/sp/800-57-part-1/rev-5/final, 54p
returns secret key:integer. secure secret key.
"""
key_bits = 256
secret_key = secrets.randbits(ke... | The code generates a secret key using `make_secret_key()`, stores it with `write_secret_key()`, then derives public key components `y`, `b`, and `prime` from the secret key via `make_public_key()`, finally writing these public key parameters with `write_public_key()`. The main task is to create and persist cryptographi... | def make_key():
secret_key = make_secret_key()
write_secret_key(secret_key)
y, b, prime = make_public_key(secret_key)
write_public_key(y, b, prime) |
def read_secret_key(secret_key_path):
with secret_key_path.open() as f:
f.readline()
secret_key = int(f.readline())
return secret_key
def make_secret_key():
"""
find secret key
I refered to this document for the size of key bits.
https://csrc.nist.gov/publications/de... | The function encrypts a message using the ElGamal cryptosystem by generating keys if necessary, converting the message to integers, and computing ciphertext components $ c_1 $ and $ c_2 $ via modular exponentiation and multiplication. It returns the encrypted message as a tuple $ (c_1, c_2) $, handling key file creatio... | def ElGamal_encrypt(message, public_key_path, secret_key_path):
"""
Encrypt a text with ElGamal cryptsystem.
Args:
message: string.we encrypt this string.
random: integer.random number
public_key_path: Path object. the path of a file
... |
def string_extract(cell, split_char):
cell_string = cell.value
if split_char in cell_string:
return_val = cell_string.split(split_char)
return "".join(return_val).strip()
else:
print(split_char + " not found in cell A1\n")
def drug_check(wkst, col_number):
for j in reversed(range... | This method processes Excel worksheets by extracting technician names, dates, and drug counts from specified cells, then initializes ExcelSheet objects with these details. It iterates through each sheet, populating data structures with drug, control, and treatment information using helper methods. | def get_worksheets(self):
ws = self.imported_wkbk[self.sheet_names[0]]
self.technician = string_extract(ws['A1'], 'Name:')
for sheet in range(len(self.sheet_names)):
ws = self.imported_wkbk[self.sheet_names[sheet]]
self.sheets.append(
ExcelSheet(
... |
def get_bucket_urls(channel, iw_datetime, max_timedelta, time_step):
time_steps = range(-max_timedelta, max_timedelta + 1, time_step)
dates = [iw_datetime + timedelta(minutes=x) for x in time_steps]
urls = {channel: {}}
for date in dates:
urls[channel][date] = get_urls(channel, date)
return... | The main task of the code is to process multiple requests for downloading and reprojecting NEXRAD weather radar data onto a Sentinel-1 satellite grid. It identifies the closest NEXRAD station for each request, retrieves and extracts data, reprojects it spatially, saves the results, and optionally generates animated GIF... | def main(
sentinel1_key=None,
sentinel1_keys_filename=None,
requests_filename=None,
sensor_operational_mode=None,
data='NEXRAD_L3',
channel=None,
max_timedelta=None,
time_step=5,
create_gif=None,
verbose=None,
delta_factor=None):
... |
def extract_text_tokens(self, text, attention_mask):
x = self.text_token_proj(text)
x = self.text_norm_layer(x)
x, attention_mask, nonempty_input_mask = self._check_and_fix_if_input_empty(x, attention_mask)
special_token_mask = attention_mask == 0
return {'all_tokens': x, 'atten... | The code processes multimodal inputs (text, video, audio) by extracting embeddings, applying positional encoding, and projecting them. It generates modality-specific embeddings and cross-modal fused embeddings (text-video, text-audio, video-audio) via a fusion module. Outputs include individual embeddings and normalize... | def forward(self, data, force_cross_modal=False):
output = {}
text_raw_embed = self.extract_text_tokens(data['text'], data['text_mask'])
video_raw_embed = self.extract_video_tokens(data['video'], data['video_mask'])
audio_raw_embed = self.extract_audio_tokens(data['audio'], data['audio_... |
def receive_string(self, buffer_size=4096):
received = ''
try:
received = self.sock.recv(buffer_size)
except (socket.error, AttributeError):
self._reconnect()
received_str = received.decode()
return received_str
def print_msg(msg: str):
logger.info(msg... | This method receives data from a socket until 'OK' or 'ERROR' is detected, buffers the input, handles errors, and returns the processed data or True. It attempts up to 'iterations' times, closes the connection if specified, and truncates the buffer before 'OK' if requested. | def receive_ok(self, buffer_size=2048, close=True, iterations=10, return_all=False):
self.recv_buffer = []
received = ''
tries = 0
while received.find('OK\n') == -1 and received.find('ERROR') == -1 and tries < iterations:
received = self.receive_string(buffer_size)
... |
def query_acquire(self):
self.net_client.send_string('ISRUNNING')
re = self.net_client.receive_ok()
if int(re) == 1:
self.acquiring = True
elif int(re) == 0:
self.acquiring = False
return self.acquiring
def get_scancount(self, close=True):
if not s... | The main task of the code is to check if data acquisition is active, calculate the number of new samples since the last acquisition, limit the read size to `max_read`, and retrieve data using `get_daq_data` if available. If no new samples are detected, it returns `None`. The function ensures controlled data retrieval, ... | def get_next_data(self, channels, max_read=5000):
# times = time.time()
if self.acquiring or self.query_acquire():
self.acquiring = True
else:
return False
current_sample = self.get_scancount(close=False)
num_samples = current_sample - self.last_sample_re... |
def resize(self, image, width, mask = False):
dim = None
h, w = image.shape[:2]
dim = (width, int(h * width / float(w)))
if mask == True:
retain_mask = image.astype(float)
resized = cv2.resize(retain_mask, dsize=dim, interpolation=cv2.INTER_CUBIC)
else:
... | This code performs image resizing via seam carving or object removal, handling input masks, adjusting dimensions, and normalizing output. It converts grayscale images to RGB, resizes large images, adjusts seam counts, applies removal/carving based on masks, and ensures correct output format. | def __call__(self, image: typing.Union[str, np.ndarray], vertical_seams: int = 0, horizontal_seams: int = 0, retain_mask: typing.Union[str, np.ndarray] = None, remove_mask: typing.Union[str, np.ndarray] = None) -> np.ndarray:
#print(image.shape)
self.ctr = 0
self.maskctr = 0
if(... |
def yes_or_no(tower, new_brick, discard):
"""
This function returns true and false. If the minimum of the sum of the indices is less than that of the original, change will take place.
If the two numbers are equal, we would calculate their deviation to a benchmark value. If the new brick has a lower deviatio... | The code's main task is to determine the computer's move in a game by deciding whether to take a brick from the discard pile, main pile, or take none. It evaluates options using the `yes_or_no` function to minimize the sum of indices. If taking from the discard pile is optimal, it removes the top brick; otherwise, it c... | def computer_play(tower, main_pile, discard):
"""
This function is where the computer's action takes place. It uses a series of functions describe below and it also decides whether
to take brick from the discard pile, the main pile, or not to take bricks at all. It works by determining by whether making th... |
def setup_bricks():
"""
Created a main pile of 60 bricks, represented as a list containing the integers 1 – 60. Created a discard pile of 0 bricks,
represented as an empty list. This function returns both lists.
"""
main_pile = []
for i in range(1,61):
main_pile.append(i)
discard = ... | The main task of the code is to implement a turn-based card game called "Tower Blaster," where players and a computer compete to build a tower by selecting bricks from a main pile or discard pile. The game involves setup, turn alternation, user input validation, and win condition checks when either the player or comput... | def main():
print('**************************************')
print('**************************************')
print('')
print("*** It's time to blast some TOWERS ***")
print('')
print('**************************************')
print('**************************************')
game_over =... |
def run_data_prep(
raw_data_path: str, dest_path: str, filename: str = "loan_approval_dataset"
):
# Load parquet files
df = read_dataframe(os.path.join(raw_data_path, f"{filename}.csv"))
# Extract the target
X = df.drop([' loan_status'], axis=1)
y = df[' loan_status']
# split train and val... | The main task of the code is to automate a machine learning workflow: preparing data, optimizing models, registering the best model, transitioning model versions to "Staging" phase, promoting version 1 to "Production", and sending success/failure emails. It uses MLflow for tracking and version control, ensuring model d... | def main_flow():
try:
print("Start ..")
run_data_prep(raw_data_path=raw_data_path, dest_path=dest_path)
run_optimization(dest_path, 5)
run_register_model(dest_path, 5, HPO_EXPERIMENT_NAME, EXPERIMENT_NAME)
client = MlflowClient(tracking_uri=MLFLOW_TRACKING_URI)
latest... |
def GetReferences(self, text):
text = text.split('==references==')
if(len(text)<=1):
return []
text = text[1].split('\n')
refs = ""
for line in text:
if line and ((line[0]=='{' and line[1]=='{') or line[0]=='*'):
tmr=3
if '... | The main task of the code is to extract structured information from input text and title by processing them into components like references, external links, categories, infobox data, body content, and a standardized title. The function converts text to lowercase, invokes specialized methods to parse each element, and r... | def processText(self, text, title):
text = text.lower()
references = self.GetReferences(text)
links = self.GetExternalLinks(text)
categories = self.GetCategory(text)
info = self.GetInfobox(text)
body = self.GetBody(text)
title = self.GetTitle(title.lower())
... |
def GetReferences(self, text):
text = text.split('==references==')
if(len(text) <= 1):
return []
text = text[1].split('\n')
refs = ""
for line in text:
if line and ((len(line) > 1 and line[0] == '{' and line[1] == '{') or line[0] == '*'):
... | The code processes input text and title by extracting structured information using helper methods. It converts text to lowercase, retrieves references, external links, categories, infobox data, body content, and processes the title. The function returns these extracted elements as a tuple for further use in data organi... | def processText(self, text, title):
text = text.lower()
references = self.GetReferences(text)
links = self.GetExternalLinks(text)
categories = self.GetCategory(text)
info = self.GetInfobox(text)
body = self.GetBody(text)
title = self.GetTitle(title.lower())
... |
def update_config_file(self) -> None:
"""
Create the config file if it doesn't exist and open it with notepad for editing.
:return: None
"""
if not os.path.exists(os.path.dirname(self.config_fp)):
os.mkdir(os.path.dirname(self.config_fp))
os.system(f"notepad {... | The method updates the `sync_config_dirs` attribute by reading from a configuration file, displaying the current configuration, and repeatedly updating the config and re-displaying until the user approves. It also creates any missing backup directories after the final configuration is confirmed. | def update_sync_config_dirs(self) -> None:
"""
Update the sync_config_dirs attribute by the config file and update the config file, until the user is happy.
:return: None
"""
if not os.path.exists(self.config_fp):
self.update_config_file()
self.sync_config_di... |
def tree_depth(tree):
if len(tree) == 1:
return 1
elif len(tree) == 2:
return tree_depth(tree[1]) + 1
elif len(tree) == 3:
return max(tree_depth(tree[1]), tree_depth(tree[2])) + 1
else:
raise ValueError("All trees are at most binary, but it has {} childs".format(len(tree) - 1))
def tree_full_bin... | This function processes a list of trees by determining the maximum depth, converting each tree into a full binary tree of that depth, performing postorder traversal on each, and converting the traversal results into sparse lists for output. | def batch_postorder(trees):
max_depth = -1
for tree in trees:
depth = tree_depth(tree)
if depth > max_depth:
max_depth = depth
filled = [tree_full_binary(tree, max_depth) for tree in trees]
postordered = [tree_postorder(tree) for tree in filled]
sparsed = [symb_to_sparse_list(traverse) for tr... |
def establish_sftp_connection(self,connection_dto):
transport = paramiko.Transport((connection_dto['host'], int(connection_dto['port'])))
transport.connect(username=connection_dto['username'], password=connection_dto['password'])
sftp = transport.open_sftp_client()
return sftp
def get_re... | The code processes CSV files from SFTP, FTP, or local storage by establishing connections, retrieving files, reading data with pandas, generating metadata (schema/table info), and returning a list of metadata. It handles encoding errors, closes connections, and aggregates metadata from both remote and local files. | def process_file(self, connection_dto):
schema_table_map = {}
file_path = connection_dto['filePath']
sftp = None
ftp = None
local_files = []
if connection_dto['connectionType'] == 'SFTP':
sftp = self.establish_sftp_connection(connection_dto)
remote... |
def init_b_bounds(G,q):
global b_upper
global b_lower
global e_upper
global e_lower
global rho_0
e_lower,e_upper = e_bounds(G,q)
l = graph_l(G)
b_lower = np.zeros(l)
b_upper = np.zeros(l)
d = G['d']
for k in range(l):
eiju = e_upper[k]
eijl = e_lower[k]
b_upper[k] = (((eiju*eiju)) + ((2*eiju*d[k... | The function computes a diagonal matrix where each entry is derived from a formula involving graph properties (G), parameters (q, t), and bounds (b_lower, b_upper). It initializes bounds, calculates intermediate values (neta_c, rho, l), and applies the formula to generate diagonal entries, returning the resulting matri... | def zeta(G,q,t):
global b_upper
global b_lower
b_lower,b_upper = init_b_bounds(G,q)
neta_c = neta_cap(G,q,t)
rho = performance(t)
l = graph_l(G)
zeta_value = np.zeros(l)
for k in range(l):
zeta_value[k] = ((1/(neta_c[k] + b_lower[k])) - (1/(neta_c[k] - b_upper[k])))/(rho)
return np.diag(zeta_value) |
def init_b_bounds(G,q):
global b_upper
global b_lower
global e_upper
global e_lower
global rho_0
e_lower,e_upper = e_bounds(G,q)
l = graph_l(G)
b_lower = np.zeros(l)
b_upper = np.zeros(l)
d = G['d']
for k in range(l):
eiju = e_upper[k]
eijl = e_lower[k]
b_upper[k] = (((eiju*eiju)) + ((2*eiju*d[k... | This function computes a logarithmic transformation of a ratio derived from upper and lower bounds (b_upper, b_lower) and a capacity term (neta_c) for each element in a graph. It initializes bounds, calculates a graph length (l), and iterates over each element to compute a value using the formula: log[(b_upper*neta_c +... | def sigma(G,q,t):
global b_upper
global b_lower
b_lower,b_upper = init_b_bounds(G,q)
l = graph_l(G)
neta_c = neta_cap(G,q,t)
# print("------------------------")
# print(b_upper,b_lower,neta_c)
# print("------------------------")
sig = np.zeros(l)
print(b_upper,neta_c,"aoao")
for k in range(l):
valu... |
def rigidity(p,G):
P = P_diag(p,G)
H = H_bar(G)
R = np.matmul(P.T,H)
return R
def zeta(G,q,t):
global b_upper
global b_lower
b_lower,b_upper = init_b_bounds(G,q)
neta_c = neta_cap(G,q,t)
rho = performance(t)
l = graph_l(G)
zeta_value = np.zeros(l)
for k in range(l):
zeta_value[k] = ((1/(neta_c[k] + b_lowe... | This function computes a control input $ u $ for a graph-based system by combining rigidity matrix $ R $, stiffness matrix $ K_v $, and graph Laplacian $ l $. It calculates intermediate terms $ \zeta_v $, $ \sigma_v $, and applies matrix operations to derive $ u $, which is negated before returning. The input $ u $ dep... | def control_input(G,q,t):
R = rigidity(q,G)
zeta_v = zeta(G,q,t)
sigma_v = sigma(G,q,t)
K_v = K(G)
l = graph_l(G)
# print('pppp',R,'zeta','\n',zeta_v,'\n',sigma_v,'\n',K_v,'\n','inputs')
u = np.matmul(R.T,zeta_v)
u = np.matmul(u,K_v)
u = np.matmul(u,sigma_v.reshape(l,1))
u = -u
return u |
def _check_events(self):
"""Respond to keypress and mouse events."""
# Watch for keyboard and mouse events
for event in pygame.event.get(): # make changes in a screen acording list of event collected by event.get() function (list of events)
if event.typ... | The code defines a game loop that continuously checks for events, updates the player's ship, manages bullets, creates enemy fleets, and updates the screen to render the game state in real-time until the game exits. | def run_game(self):
"""Start the main loop for the game."""
while True: # repeatedly display a screen
self._check_events()
self.ship.update()
self._update_bullets()
self._create_fleet()
se... |
def get_notification_transfer_done(connection, buffer_size, recv_timeout, target, verbose):
"""
Function for getting notification that the transfer of files between the Server and the Client is done.
Server receives message from the Client in the following format:
{data}
where
{da... | The main task of the code is to receive a zipped global model file from a Cloud Server, unzip it, verify its size against the expected value, and repeatedly resend the file if the size mismatch occurs until a successful transfer is confirmed. The function ensures reliable transmission by sending "Confirm" upon success ... | def receive_file(connection, target, target_ip, dev_path, buffer_size, recv_timeout, verbose, msg="zip"):
"""
Function for receiving the global model from the Cloud Server. Until a successful file transfer, the
Device tries again to get the global model weight file.
"""
if verbose:
print(f"... |
def colortree_as_binary_string(l:list) -> BinaryString:
# here None empty value is goint to be a 24 bit
# this is the coding that we are going to use
# "00" prefix indicates a 10 bits index signaling certain amounts of None
# "01" prefix indicates a 3 bit index signaling certain amounts of None
... | The code tests Huffman coding by generating a codebook from a histogram, converting it to a binary string, decoding it back into a code tree, and verifying if the original and decoded codes match. It also prints the reverse codebook derived from the binary string to validate correctness. | def test():
histogram = {(255,8,1):32, (1,255,1):15, (1,1,255):18}
code = huffman_code(histogram)
codebook = get_codebook(code)
code = code.to_list()
binary_code = colortree_as_binary_string(code)
code2 = decode_binary_string_as_codetree(binary_code)
print(codebook)
print(code)
pri... |
def get_quantization_multilpier():
global quantization_multilpier
return quantization_multilpier
def set_quantization_multilpier(x):
global quantization_multilpier
quantization_multilpier = x
def expand(array,is_luminance):
q = get_quantization_matrix(is_luminance)
blocks = array_as_blocks(array... | The code performs JPEG-like image compression by quantizing the image using a specified multiplier. It converts the image to YCbCr color space, applies Discrete Cosine Transform (DCT) on each channel, quantizes the transformed data, inverse transforms it, and converts back to RGB. The quantization multiplier is tempora... | def get_quantized_image(image, multiplier):
previous_multiplier = get_quantization_multilpier()
set_quantization_multilpier(multiplier)
res = YCbCrTransform(image)
for k in range(3):
transform = cosine_transform(res[:,:,k])
q_transform = expand(quantize(transform,k==0),k==0)
res... |
def parse_transcript(episode_title):
'''
Given a Mad Men episode title string, returns a list of sentences
Each sentence is lower case and has no punctuation
Each sentence ought to be able to be extended to one big sting with whitespace in between
'''
with open(f'transcripts/{episode_title}') as... | The code initializes an object to process a script by parsing its transcript into lines, collecting words, counting their occurrences, and storing character names for analysis. | def __init__(self, episode_title):
self.title = episode_title
self.lines = parse_transcript(self.title)
self.words = collect_words_in_script(self.title)
self.word_counts = count_words_in_script(self.title)
self.char_names = names |
def waitAndSendKeys(xpath, *keys):
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))).send_keys(keys)
def waitAndClick(xpath):
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath))).click()
def metamaskMainPageConfirmButton():
switchToMetamask()
... | This code automates unlocking MetaMask by navigating to its unlock page, inputting a predefined password, clicking the unlock button, and confirming access. It handles exceptions silently to ensure the process continues without interruption. | def openMetamask():
try:
print("opening metamask")
driver.get(f"{METAMASK_HOME_URL}#unlock")
waitAndSendKeys("/html/body/div[1]/div/div[3]/div/div/form/div/div/input", METAMASK_PASSWORD)
waitAndClick("/html/body/div[1]/div/div[3]/div/div/button")
metamaskMainPageConfirmButton... |
def printn(*text):
print("\n", *text)
def zeroHex(num):
return Hex(num).rjust(64,"0")
def sendTx(address, dataInput="", value=0):
w3 = Web3(Web3.HTTPProvider(RPC_URL))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
account = w3.eth.account.from_key(PRIVATE_KEYS[address])
nonce = w3.eth... | The main task of the code is to initiate a game session for a specific team by constructing and sending a blockchain transaction. The function combines a predefined method identifier with the team ID converted to a hexadecimal string, then executes a transaction using the provided address and data input to trigger the ... | def startGame(address, teamId):
printn(f"Starting game with team {teamId}")
dataInput = METHODS["startGame"] + zeroHex(teamId)
sendTx(address=address, dataInput=dataInput) |
def printn(*text):
print("\n", *text)
def zeroHex(num):
return Hex(num).rjust(64,"0")
def sendTx(address, dataInput="", value=0):
w3 = Web3(Web3.HTTPProvider(RPC_URL))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
account = w3.eth.account.from_key(PRIVATE_KEYS[address])
nonce = w3.eth... | The main task of the code is to initiate a settlement process for a game identified by `gameId` at a specified `address`. It constructs a transaction data input by concatenating the method identifier `METHODS["settle"]` with a zero-padded hexadecimal representation of `gameId`, then sends this transaction using the `se... | def settle(address, gameId):
printn("Settling...")
dataInput = METHODS["settle"] + zeroHex(gameId)
sendTx(address=address, dataInput=dataInput) |
def parseSignature(signature):
lastPart = signature[-2:]
signature = signature[2:-2]
signaturePart1 = signature[:64]
signaturePart2 = signature[64:]
return lastPart, signaturePart1, signaturePart2
def zeroHex(num):
return Hex(num).rjust(64,"0")
def sendTx(address, dataInput="", value=0):
w3 ... | The function constructs a transaction data input for an attack action by combining game parameters (game ID, team ID, expiration time) and a parsed signature into a hexadecimal string with zero-padding, then sends the transaction to the specified address. | def sendAttackTx(address, game):
gameId, teamId, expireTime, signature= int(game["game_id"]), int(game["team_id"]), int(game["expire_time"]), game["signature"]
lastPart, signaturePart1, signaturePart2 = parseSignature(signature)
dataInput = METHODS["attack"] + zeroHex(gameId) + zeroHex(teamId) + zeroHex(exp... |
def openMetamask():
try:
print("opening metamask")
driver.get(f"{METAMASK_HOME_URL}#unlock")
waitAndSendKeys("/html/body/div[1]/div/div[3]/div/div/form/div/div/input", METAMASK_PASSWORD)
waitAndClick("/html/body/div[1]/div/div[3]/div/div/button")
metamaskMainPageConfirmButton... | The code automates switching MetaMask accounts by simulating UI interactions: opening MetaMask, confirming/signing actions, waiting, and clicking on a specific account element via XPath based on the provided account number. | def changeAccountOnMetamask(accountNum: int):
openMetamask()
metamaskMainPageConfirmButton()
metamaskMainPageSignButton()
sleepy(3)
clickByAltWay("/html/body/div[1]/div/div[1]/div/div[2]/div[2]/div", 0.3)
clickByAltWay(f"/html/body/div[1]/div/div[3]/div[4]/div[3]/div[{accountNum}]", 0.3) |
def openCrabada():
driver.get(START_LOOTING_URL) #go to crabada
sleep(5)
clickLogOutButton()
connectWalletButton()
clickSignButton()
driver.get(START_LOOTING_URL)
def goToPageNum(pageNum):
sendKeysByXpath("//*[@id='root']/div/div/section/main/div[1]/ul/li[1]/input", Keys.BACKSPACE, Keys.B... | This code automates attacking a specific mine in a game by opening the Crabada platform, selecting a target mine, solving CAPTCHA, and initiating an attack within a 5-minute window. It handles errors, checks for available teams, avoids concurrent attacks, and redirects to looting after completion. | def attack():
openCrabada()
now = time.time()
expireTime = now + 300
stop = False
while expireTime > now and not stop:
now = time.time()
teamsInfo = getTeamsInfo(ADDRESS)
try:
selectedMine = chooseMine(teamsInfo, data="WithHistory")
except Exception as e:
... |
def printn(*text):
print("\n", *text)
def isSettled(gameId):
mineUrl = f"https://idle-game-api.crabada.com/public/idle/mine/{str(gameId)}"
mine = requests.get(mineUrl, headers= HEADERS).json()
process = mine["result"]["process"]
lastProcessAction = process[-1]["action"]
if lastProcessAction == ... | The main task of the code is to close a game by first checking if it's settled; if not, it settles the game using the provided address and game ID. It then constructs a transaction data input by combining the "closeGame" method with the game ID in hexadecimal format and sends this transaction to finalize the game closu... | def closeGame(address, gameId):
printn(f"Closing game id {gameId}")
if not isSettled(gameId):
printn(f"game {gameId} is not settled.")
settle(address=address, game=gameId)
dataInput = METHODS["closeGame"] + zeroHex(gameId)
sendTx(address=address, dataInput=dataInput) |
def openChrome():
global driver, mainPage
chromeProfilePath = f"chromeProfiles/{ADDRESS}"
service = Service(ChromeDriverManager().install())
chromeOptions = Options()
chromeOptions.add_argument(f'user-data-dir={chromeProfilePath}')
chromeOptions.add_argument("--profile-directory=Default")
... | The main task of the code is to automate interactions with Chrome and Metamask by opening the browser, confirming the Metamask main page, checking for available accounts, switching accounts when available, and executing an "attack" function in a continuous loop. It handles exceptions by printing error classes and retry... | def main():
openChrome()
openMetamask()
while True:
try:
metamaskMainPageConfirmButton()
availableAccount = isAccountAvailable()
if not availableAccount:
print("no available team...")
sleepy(20)
continue
... |
def checkfirsttoken(self,token):
if(self.run):
pass
else:
if(self.alreadyvar(token)):
self.initial=True
if(self.variables[token]=="point"):
self.point=True
else:
self.nopoint=True
... | This code validates each line of tokenized input by checking syntax rules: it verifies first tokens are valid keywords/variables, handles variable declarations with '!', checks for proper assignment operators, processes 'run' commands, and ensures correct use of syntax elements like '=' and '}'. It raises errors for in... | def main(self):
flag = True
for self.line in range(len(self.tokens)):
for token_num in range(len(self.tokens[self.line])):
token = self.tokens[self.line][token_num]
if(token_num == 0 and not self.run):
if(self.checkfirsttoken(token)):#first... |
def rmse(self, X, X_hat):
return np.sqrt(1 / X.size * ((X - X_hat) ** 2).sum())
def denoise_one_itr(self, win_size, tau):
H, W, D = self.imgs[0].shape
counter = 0
if self.notebook:
from tqdm.notebook import trange
else:
from tqdm import trange
# ... | The main task of the code is to iteratively denoise an image using varying window sizes and tau values, tracking intermediate results (images and RMSE metrics) in a document. It randomly selects a slice for visualization, updates the denoised image in each iteration, calculates RMSE against a reference image if provide... | def denoise(self, plot=True):
slice_num = np.random.randint(self.denoised_img.shape[-1])
doc = {"imgs": [self.denoised_img.copy()]}
if self.ref_img is not None:
doc["rmse"] = [self.rmse(self.ref_img, self.denoised_img)]
for win_size, tau in zip(config_win_size_grid, config_... |
def get_teams():
# find all team names
team_elems = browser.find_elements_by_css_selector(
"ul>li[role='treeitem']>div[sv-element]")
team_names = [team_elem.get_attribute(
"data-tid") for team_elem in team_elems]
team_names = [team_name[team_name.find(
'team-') + 5:team_name.rfin... | This code automates logging into Microsoft Teams using provided credentials, switches between organizations if configured, navigates to the Teams app, retrieves team/channel data, checks blacklists, and periodically updates/Joins meetings. It handles element re-finding to avoid exceptions, offers user interaction optio... | def main():
global browser, config
window_size = browser.get_window_size()
if window_size['width'] < 950:
print("Resized window")
browser.set_window_size(950, window_size['height'])
browser.get("https://teams.microsoft.com")
input_type_email = "input[type='email']"
input_type_p... |
def get_url_by_slug(slug):
return animeUrl + episodeUrlSulfix + slug
def get_page_by_url(url):
page = requests.get(url)
soap = BeautifulSoup(page.content, 'html.parser')
return soap
def get_all_episode_data(page):
return {
'title': get_episode_title(page),
'image': get_episode_image... | The function retrieves episode data by first obtaining a URL from a given slug, fetching the corresponding web page, and then extracting all episode information from that page. | def get_episode_by_slug(slug):
url = get_url_by_slug(slug)
page = get_page_by_url(url)
return get_all_episode_data(page) |
def get_url_by_slug(slug):
return animeUrl + animeBySlugUrlSulfix + slug
def get_page_by_url(url):
page = requests.get(url)
soap = BeautifulSoup(page.content, 'html.parser')
return soap
def get_anime_title(page):
return page.find_all('h1')[0].contents[0]
def get_anime_year(page):
aboutDiv = pag... | The main task of the code is to retrieve structured anime data (title, year, tags, synopsis, seasons) from a webpage by first resolving a slug to a URL, fetching the page content, and extracting relevant information using helper functions. The result is a dictionary containing key details about the anime. | def get_anime_data_by_slug(slug):
url = get_url_by_slug(slug)
page = get_page_by_url(url)
return {
'title': get_anime_title(page),
'year': get_anime_year(page),
'tags': get_anime_tags(page),
'sinopse': get_sinopse(page),
'seasons': get_all_seasons(page)
} |
def simplest_cb(img, percent):
assert img.shape[2] == 3
assert percent > 0 and percent < 100
half_percent = percent / 200.0
channels = cv2.split(img)
out_channels = []
for channel in channels:
assert len(channel.shape) == 2
# find the low and high precentile values (based on t... | This code processes incoming requests to control a robot's camera, motors, and image capture. Depending on the 'service' parameter, it captures and filters images via OpenCV, uploads them to Imgur, or controls motor movements (forward/backward/left/right) using GPIO. It also handles specific motor commands for directio... | def workflow():
req = json.loads(request.data)
val = req["service"]
print(val)
if val == "camera":
cam = cv2.VideoCapture(0)
ret, image = cam.read()
# cv2.imshow('Imagetest', image)
result = simplest_cb(image, 1)
# cv2.imwrite('image2.jpg', image)
cv2.imwr... |
def laf_open_disk(comm):
# Open whole disk in read/write mode
open_cmd = lglaf.make_request(b'OPEN', body=b'\0')
open_header = comm.call(open_cmd)[0]
fd_num = read_uint32(open_header, 4)
try:
yield fd_num
finally:
close_cmd = lglaf.make_request(b'CLSE', args=[fd_num])
com... | The code processes command-line arguments to perform disk partition operations (list, dump, restore, wipe). It validates inputs, auto-detects the device, checks partition existence, and executes the specified action on the target partition using low-level disk communication functions. | def main():
args = parser.parse_args()
logging.basicConfig(format='%(asctime)s %(name)s: %(levelname)s: %(message)s',
level=logging.DEBUG if args.debug else logging.INFO)
actions = (args.list, args.dump, args.restore, args.wipe)
if sum(1 if x else 0 for x in actions) != 1:
parser.er... |
def clear_screen(self):
if name=='nt':system('cls')
else:system('clear')
def enum_list(self,list):
eout=[]
total=0
for i,f in enumerate([x for x in list if Path(x).exists()],start=1):
me=''
try:
mt=time.ctime(Path.stat(f).st_mtime)
... | This function provides a menu-driven interface to manage files by allowing users to archive, copy, move, delete, open, parse with regex, or save a list of files. It processes user input to execute selected operations, handling archives with password protection, file transfers, deletions, and text output, while navigati... | def enum_output(self,list,fpath):
"""
[*]ARCHIVE, COPY, DELETE, MOVE, OPEN, PARSE, SAVE:
1 -> Archive Files In List To Password Protected Archive [Extensions: zip or 7z]
2 -> Copy File/Folder Or Entire List ... |
def clear_screen(self):
if name=='nt':system('cls')
else:system('clear')
def exit(self):
self.clear_screen()
kill(getpid(),signal.SIGTERM)
def enum_output(self,list,fpath):
"""
[*]ARCHIVE, COPY, DELETE, MOVE, OPEN, PARSE, SAVE:
... | This function searches for files in a specified directory using user-defined patterns, supporting wildcards, extensions, and specific commands. It handles input types like exact filenames, extensions, and pattern matches, displaying results or allowing navigation/backtracking. | def search_type(self,fpath):
"""
[*]Search Types [.ext = File Extension Of Choice]:
link.txt -> Find "link.txt" File
*.ext -> Find All Files With .ext Fil... |
def clear_screen(self):
if name=='nt':system('cls')
else:system('clear')
def search_type(self,fpath):
"""
[*]Search Types [.ext = File Extension Of Choice]:
link.txt -> Find "link.txt" File ... | The main task of the code is to continuously prompt the user for a folder path, validate it, and execute a search operation if valid, or exit on input 'e'. It clears the screen, handles exceptions, and maintains a loop for repeated user interaction until termination. | def main(self):
while True:
try:
self.clear_screen()
fpath=input("\033[1;32;40m"+__doc__+"\033[0m\nInput Search Folder=> ") or path.abspath(sep)
if Path(fpath).is_dir():self.search_type(fpath)
elif fpath=='e':self.exit()
exc... |
def get_full_screen(window_info):
x1 = window_info['x']
x2 = window_info['x'] + window_info['width_fullscreen']
y1 = window_info['y']
y2 = window_info['y'] + window_info['height_fullscreen']
return get_screenshot(window_info, x1, y1, x2, y2)
def onHomeMenu(full_screen_img):
return onScreen('... | The code determines the current state of a game by analyzing a captured screen image. It checks for specific visual cues using helper functions to return states like 'HOMESCREEN', 'LOADSCREEN', 'MULLIGAN', etc., or 'INACTIVE' if the screen capture fails or no state matches. | def get_game_state(window_info):
ret, img = get_full_screen(window_info)
if ret:
if onHomeMenu(img):
return 'HOMESCREEN'
elif isLoadingScreen(img):
return 'LOADSCREEN'
elif onKeepHand(img):
return 'MULLIGAN'
elif hasPriority(img):
... |
def show_ship_header(self, ships_count) -> None:
print()
print(" ", end="")
self.show_ships_count(ships_count)
print()
print()
def add_ship(self, ships_count) -> List[int]:
""" Get termination segments from the user and add ship. """
dim = lower = higher = 0
... | The main task of the code is to allow a user to manually add or remove ships on a grid until all required ships are placed. The function displays the current ship count and grid, prompts the user to choose between adding ("a") or removing ("r") ships, and updates the ship counts accordingly using helper methods. The lo... | def set_ships(self):
""" The user sets ships manually. """
ships_count = self.ships_count[:]
while sum(ships_count) > 0:
self.show_ship_header(ships_count)
self.grid.show()
opt = ''
valid_opts = ["a", "r"]
while opt not in valid_opts... |
def show_players(self) -> None:
Game.show_row_prefix()
self.show_spanned_player_name(0)
Game.show_row_middle()
self.show_spanned_player_name(1)
Game.show_row_suffix()
Game.show_row_prefix()
self.show_player_ship_count(0)
Game.show_row_middle()
self... | The main task of the code is to render a game's visual interface by displaying players, grids, and turn information with formatted borders and separators. It uses `Game.show_margin()` to create top, middle, and bottom borders with ASCII characters, then calls `self.show_players()`, `self.show_grids()`, and `self.show_t... | def show(self) -> None:
Game.show_margin("┌", "┬", "┐")
self.show_players()
Game.show_margin("├", "┼", "┤")
self.show_grids()
Game.show_margin("├", "┴", "┤")
self.show_turns()
Game.show_margin("└", "─", "┘") |
def active_player(self) -> Player:
return self.players[self.player]
def strike_ai(self) -> bool:
""" Computer strike. """
row = col = -1
length = len(self.active_player().ship_cells_found)
# no tips, look for a ship
if length == 0:
unknown_cells = self.activ... | This method determines the active player's type (AI or human) and executes either `strike_ai()` or `strike_hi()` accordingly. It returns the result of the chosen method, serving as a workaround for Python's lack of native abstract class support. The boolean output indicates the success or outcome of the strike action b... | def strike(self) -> bool:
""" This method calls either ai_strike or hi_strike based on an active
player type. Such weird implementation is chosen because Python does
not support abstract classes without additional dependencies. """
return self.strike_ai() if self.active_player()... |
def show(self) -> None:
Game.show_margin("┌", "┬", "┐")
self.show_players()
Game.show_margin("├", "┼", "┤")
self.show_grids()
Game.show_margin("├", "┴", "┤")
self.show_turns()
Game.show_margin("└", "─", "┘")
def active_player(self) -> Player:
return self.p... | This code defines the main game loop that alternates turns between two players, handles striking and checking hits, switches players when a miss occurs, reveals all ships after the game ends, and reports the winner based on remaining ships. | def play(self) -> None:
""" Main game loop alternates player turns. """
self.show()
# determine the winner
while self.active_player().has_ships() and self.opponent().has_ships():
hit = self.strike()
self.show()
if not hit:
self.player... |
def get_all_posts(self):
return self.wait_for_presence_of_all_elements(By.XPATH,self.POST_ELEMENTS)
def postMeetsCriteria(self,post,dateOfInterest,usersName):
date = self.get_date_from_post(post)
poster = self.get_name_of_poster(post)
fullTextOfPoster = self.get_name_of_posterFULL(post)
... | This function deletes social media posts meeting specific criteria (date, user name) by iterating through posts, scrolling, and repeating until no new posts are found. It logs post counts, deletions, and loop iterations while adjusting the starting index to avoid reprocessing deleted posts. | def go_through_posts_and_delete(self,dateOfInterest,usersName,startingPostIndex):
if startingPostIndex == -1:
self.log.warning("there are no posts to delete as the search function found no post before the given date")
else:
posts = self.get_all_posts()
totalPosts = le... |
def get_variant_list(gene_id, dataset="gnomad_r2_1"):
"""
In this part of the code, the GraphQL query for the variant
list of the gene will be made. This query will be
formatted into json, which will be pushed to the fetch code.
:param gene_id:ENSEMBL gene id
:param dataset: dataset in which the A... | The main task of the code is to parse a configuration file, extract genetic variant data from GnomAD, and populate a SQLite database with variant details such as rsIDs, positions, transcript consequences, and annotations. It processes a list of variants, reorders them based on rs codes, inserts structured data into a d... | def create_gnomad_db(c_file):
"""
This function creates the database of all the variants of the
ensemble id from GnomAD.
"""
file = open(str(c_file))
data_config = json.load(file)
input_info = data_config["ensemble"]
count = 0
rs_codes = [rs["rs_code"] for item in data_config if
"population" in item for ... |
def extract_mutate_info_per_haplotype(lijst_snp_allele_hap,
data_config, rs_path):
"""
This function uses the list of SNPs and alleles (in dict) per
haplotype to extract information and store it in a 2D list.
The information is either downloaded (XML string) or read... | The function generates a synthetic DNA population by aggregating mutations from specified haplotypes. It calculates the number of sequences per haplotype, extracts mutation data, combines them into a list, and applies mutations to DNA sequences derived from a chromosome file. The output is a 2D list of all mutations fo... | def create_synthetic_DNA_population(population, data_config, nc_file, rs_path):
"""
This function calls all the functions necessary to
initiate the synthetic DNA population.
:param population: The dictionary of population data from the
config file.
:param data_config: The config file.
:param... |
def readData():
df = pd.read_csv ('data1.csv')
df = df.drop(['Product_Name', 'Product_Category', 'User_Location', 'User_Province', 'Cost', 'Date'], axis=1)
df.User_ID = df.User_ID.replace(np.nan, '?')
df['Event'] = df['Event'].replace(['view', 'wishlist', 'cart'],[1, 3, 5])
df.rename(columns={'Produ... | The code's main task is to evaluate a hybrid recommendation system's accuracy by splitting data into training/test sets, handling user-specific data, generating a rating matrix, calculating user/item-based probabilities, combining them, and comparing predicted recommendations against actual test data. It ensures the us... | def start(user_id):
#read in Data from database
df = readData()
#Split data into training and testing
train = df.sample(frac=0.7)
test = df.drop(train.index)
user_in_training = True
if (train[train['users'] == user_id].count()['users'] == 0):
user_in_training = False
... |
def readData():
df = pd.read_csv ('data1.csv')
df = df.drop(['Product_Name', 'Product_Category', 'User_Location', 'User_Province', 'Cost', 'Date'], axis=1)
df.User_ID = df.User_ID.replace(np.nan, '?')
df['Event'] = df['Event'].replace(['view', 'wishlist', 'cart'],[1, 3, 5])
df.rename(columns={'Produ... | The code calculates the hybrid accuracy of a recommendation system by processing each unique user's data, aggregating results, and outputting the accuracy. It reads user data, filters out invalid entries, iterates through users to evaluate performance, computes overall accuracy, and writes the result to a text file. | def main():
df = readData()
people = df["users"].unique()
people = np.delete(people, np.where(people == "?"))
total = 0
for p in tqdm(people):
user_id = p
total = total + start(user_id)
accuracy = total/len(people)
print('Hybrid Accuracy: ', "{:.2%}".format... |
def pravouganik_oko_face(slika, lice, boja, debljina):
x1 = lice.left()
y1 = lice.top()
x2 = lice.right()
y2 = lice.bottom()
cv2.rectangle(slika, (x1,y1), (x2,y2), boja, debljina)
return slika
def krugovi(slika, oznake, bojaa, debljina):
oznake = face_utils.shape_to_np(oznake)
boja = boj... | The main task of the code is to process an image by detecting faces using a detector, extracting facial landmarks with a predictor, drawing rectangles around faces and circles around landmarks, and returning the modified image along with adjusted landmark coordinates (skelet) based on parameter 'z' | def provuci_kroz_ai(detector, predictor, slika, z):
slika = cv2.cvtColor(slika, cv2.COLOR_BGR2RGB)
kopija = cv2.cvtColor(slika, cv2.COLOR_BGR2GRAY)
lica = detector(kopija)
niz = []
for l in lica:
slika = pravouganik_oko_face(slika, l, zelena, 1)
oznake = predictor(kopija,l)
... |
def pravouganik_oko_face(slika, lice, boja, debljina):
x1 = lice.left()
y1 = lice.top()
x2 = lice.right()
y2 = lice.bottom()
cv2.rectangle(slika, (x1,y1), (x2,y2), boja, debljina)
return slika
def koef_krugovi(slika, niz, boja, debljina, koef, adj):
pd = (niz[0][1]+niz[2][1])/2
pl = (niz... | The function processes an image to detect faces, extract facial landmarks using a predictor, apply coefficient-based circular transformations, and generate a 3D-like skeletal coordinate structure. It converts the image to grayscale, draws face rectangles, overlays landmarks as circles, adjusts coordinates with paramete... | def provuci_kroz_ai_koef(detector, predictor, slika, z, koef, ad):
slika = cv2.cvtColor(slika, cv2.COLOR_BGR2RGB)
kopija = cv2.cvtColor(slika, cv2.COLOR_BGR2GRAY)
lica = detector(kopija)
niz = []
for l in lica:
slika = pravouganik_oko_face(slika, l, zelena, 1)
oznake = predictor(kop... |
def find_F1(df: pd.DataFrame, min_sup: int) -> pd.DataFrame:
"""
Finds frequent (support >= min_sup) items or 1-sequences,
e.g. {A}, {B}, returns dataframe with these items and their support.
"""
F1 = dict(tuple(df.groupby('Items')))
atoms_series = df.groupby('Items')['SID'].nunique() #atoms_ser... | The code implements the SPADE algorithm to discover frequent sequences in a dataset. It starts by identifying individual items (atoms) with sufficient support, then iteratively finds longer frequent sequences (2-items, 3+ items) by expanding patterns and calculating their support. The process continues until no more se... | def spade(df: pd.DataFrame, min_sup: int):
# (STEP 1): Find atoms and their support
supports, F1 = find_F1(df, min_sup)
#print(f"Step 1.:\n{supports}\n{F1}\n")
# 2 Find frequent 2-sequences (containing 2 items) e.g. {AB}, {A}->{B}, {B}->{A}
supports, item_tree = find_F2(F1, supports, min_sup)
#p... |
def solve(self): # get solution for one generation
# select best candidates
ls = []
for gene in self.genes:
gene.fitness = -self.problem.get_loss(self.problem.gene_to_solution(gene))
ls.append(gene.fitness)
top_k_idx = np.argsort(ls)[-self.candidate_buffer:]
... | The main task of the code is to implement an evolutionary algorithm (EA) for optimization. It initializes a population of genes, iteratively evolves solutions by evaluating loss, tracking convergence via loss delta thresholds, and records training progress. The algorithm stops when the loss change falls below a specifi... | def fit(self):
# initialisation of gene pool
for i in range(self.population):
self.genes.append(Gene(self.problem.gene_length, self.problem.gene_alphabet_length,
self.problem.gene_alphabet_repeat))
print('Initialized EA: {} population, {} elites, {}... |
def empty_cells(self):
emptyCells = []
for y, row in enumerate(self.board):
for x, cell in enumerate(row):
if cell == '-':
emptyCells.append([x,y])
return emptyCells
def miniMax(self, depth, player = 'COMP'):
i... | The code's main task is for an agent to select a move in a game by evaluating the board's empty cells. If the board is empty (depth 9), it defaults to position (1,1). Otherwise, it uses the miniMax algorithm with a depth parameter and 'COMP' as the player to determine optimal coordinates (x, y). The agent then records ... | def agentTurn(self):
depth = len(self.empty_cells())
print('Agents turn to move')
if depth == 9:
x = 1
y = 1
else:
move = self.miniMax(depth, player = 'COMP')
x, y = move[0], move[1]
self.set_agent_move(x, y)
... |
def find_successor(self, id_to_find):
# Here, no need to write id_to_find <= self.successor_id <= because = will never work as sha1 values are unique
# and the chances of hash collision happening is very rare.
# Here, successor_id is finger table's first entry
# I dont need this check w... | This function processes incoming network requests for a distributed system, handling tasks like node lookup, join/leave operations, stabilization, and message forwarding. It receives serialized data via `pickle`, updates node relationships (successors/predecessors), and manages friend lists and chat messages. Each requ... | def processor_thread(self, inc_conn_obj, inc_address):
try:
inc_data_form = pickle.loads(inc_conn_obj.recv(BUFFER)) # Code Block
request_type = inc_data_form[0]
# print(datetime.datetime.now(), ":", f"req_type = {request_type}")
# Handle all types of requests her... |
def get_test_words(test_file, files, n_words):
test_words = get_words(test_file)
# remove last correct words
for word in test_words:
if not word.active:
test_words.remove(word)
wl = []
for afile in files:
wordslist = get_words(afile)
sl = np.random.choice(wordsl... | The main task of the code is to process a list of files and select a specified number of words using `get_test_words`, then execute a test on these words with `do_test`, and finally save the resulting words to a designated file using `save_words` based on input arguments. | def test_com(args):
files = args.files
n_words = args.nwords
test_words = get_test_words(args.word_file, files, n_words)
save_selected_words = do_test(test_words)
save_words(save_selected_words, args.word_file) |
def _get_all_cards(self):
if self.cards is None:
self.cards = self._get_words()
def _add_card(self, question, answer, active=False):
card = Card(id = self.nextid, question=question, answer=answer, active=active)
self.nextid = self.nextid + 1
self.cards.append(card)
def save(s... | The main task of the code is to add a new question-answer card to a collection, with optional activation status and automatic saving. It retrieves existing cards, adds the new card, and saves changes if specified. | def add_card(self, question, answer, active=False, save=True):
self._get_all_cards()
self._add_card(question, answer,active)
if save:
self.save() |
def _get_all_cards(self):
if self.cards is None:
self.cards = self._get_words()
def _add_card(self, question, answer, active=False):
card = Card(id = self.nextid, question=question, answer=answer, active=active)
self.nextid = self.nextid + 1
self.cards.append(card)
def save(s... | This method imports questions from a CSV file into a card system. It reads the file, processes each row to add cards with stripped text and inactive status, and optionally saves changes and prints a confirmation message. | def import_cards(self, afile, print_msg=True, save=True):
self._get_all_cards()
try:
data = pd.read_csv(afile, header=None)
except Exception as ex:
raise
for row in data.iterrows():
self._add_card(row[1][0].strip(), row[1][1].strip(), active=False)
... |
def is_time_to_add_words(self):
next_due_date = self.get_next_review_day()
seconds_to_next_review = next_due_date-datetime.now()
# check if the time has past 5 hours
return seconds_to_next_review.seconds >= 60*60*5
def get_inactive_cards(self):
self._get_all_cards()
selec... | The main task of the code is to activate up to 2 inactive cards when the time condition is met, set their due dates to 10 minutes from now, and save the updated cards. It checks if it's time to add words, selects inactive cards, limits them to 2, toggles their active status, updates their due dates, and saves the chang... | def check_next_active(self):
num=2 # add 5 words at a time
if not self.is_time_to_add_words():
return
selected_word = self.get_inactive_cards()
if len(selected_word) > num:
selected_word = selected_word[:num]
for word in selected_word:
word.to... |
def init_level(self, lvl):
# randomly generate rooms layout and type and assign no
# then initialize each 1st room
self.currentLevel = Level(lvl)
self.currentLevel.generate()
self.transitionToRoom(0, top_door)
def transitionToRoom(self,roomNo,p1Coords):
self.currentRoom = self.currentLevel.rooms[roomNo]
s... | The code implements a game loop handling player movement, door transitions, and game state updates. It initializes level 1, processes events (QUIT, KEYDOWN), checks key presses for directional movement, transitions between rooms via doors if unlocked, updates sprites, checks player health, renders the game, and maintai... | def game_loop(self):
self.init_level(1)
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
keys_pressed = pygame.key.get_pressed()
if event.key == pygame.K_e:
game_... |
def draw_text(self,size,text,x,y):
largeText = pygame.font.SysFont("Lucida Sans Roman", size)
textSurf, textRect = self.text_object(text, largeText)
textRect.center = (x,y)
self.game_display.blit(textSurf, textRect)
def init_level(self, lvl):
# randomly generate rooms layout and type and assign no
# then in... | This function displays a "GAME OVER" screen, waiting for the player to press the 'E' key to exit to the main menu. It continuously updates the screen with the game over message and exit instructions, then resets the game level and reopens the main menu once 'E' is pressed. | def game_over(self):
gameover = False
while not gameover:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
gameover = True
self.draw_text(200,"GAME OVER",500,200)
self.draw_text(100,"Press E to exit to Main Menu",500,400)
pygame.display.upda... |
def set_drop_down(element, value):
click(element)
click(Paths.valueselect(value))
def setdate(element, date):
click(element)
valueclear(element)
setvalue(element, date)
def click(element):
driver.find_element_by_xpath(element).click() | This function configures sales report parameters by populating dropdowns with test data from Excel based on the provided scenario, setting date ranges, and submitting the report. It automates test setup for sales reporting systems using implicit waits and predefined element paths. | def setsalereportparameter(Scenario):
driver.implicitly_wait(5)
set_drop_down(Paths.Region, ExcelLoad.TestData(Scenario,"Region"))
set_drop_down(Paths.Level, ExcelLoad.TestData(Scenario,"Level"))
set_drop_down(Paths.Application, ExcelLoad.TestData(Scenario,"Application"))
set_drop_down(Paths.Locatio... |
def getBestChoice(queens, q1Index, err):
#returns best choice (row or col) that minimizes num errors
#get list of all rows/cols that dont have a queen
available = [r for r in range(len(queens))]
for q in queens:
if err == QueenError.SAME_ROW:
x=q.row
else:#err==QueenError.SA... | The function `fixError` resolves conflicts in the N-Queens problem by adjusting a queen's position to minimize errors. For same-row/column errors, it selects the optimal row/column via `getBestChoice`. For diagonal conflicts, it randomly chooses a new position ensuring no more than one additional error, avoiding previo... | def fixError(queens, q1Index, q2Index, err, numErrs):
#hill climbing happens here, for same row and same col errors pick new row or col that minimized num errors
#if same diagonal randomly replace q1 without worsening num errors by more than 1
if err == QueenError.SAME_ROW:
bestChoice = getBestChoic... |
def numErrors(queens):
pairsOfQueens = list(combinations(queens, 2))
result=0
for (q1, q2) in pairsOfQueens:
#print(str(q1)+" "+str(q2))
if sameRow(q1,q2) or sameCol(q1,q2) or sameDiagonal(q1,q2):
result+=1
return result
def queensMisplaced(queens):
#RETURNS indices of WH... | The code implements a multi-threaded approach to solve the N-Queens problem by iteratively fixing misplaced queens in a configuration. Each thread attempts to correct errors in the board, restarting if no solution is found within a set number of iterations. If a valid solution is detected, it is stored and signals term... | def worker_thread(thread_id, N):
queens = getFirstListOfQueens(N)
#printQueens(queens)
numErrs = numErrors(queens)
#print("num errors: "+str(numErrs))
x = queensMisplaced(queens)
i = 0
maxIterations=50
while not solution_found_event.is_set():# Check if a solution is found
... |
def update_label(self, string):
length = 50
lines = ''
for i in range(0, len(string), length):
lines = lines + '\n' + string[0+i:length+i]
self.rv.data.append({'text' : lines})
def sign_in(self, auth, user, password):
response = auth.sign_in_with_email_and_password(us... | This code demonstrates Firebase Realtime Database CRUD operations using Pyrebase4. It creates a user account, performs create/read/update/delete operations on database documents, verifies data integrity, saves user information, and stores additional data. The demonstration includes error handling, authentication, and d... | def pyrebase4_demonstration0(self):
self.update_label('\nStarting Realtime Database demonstration.\n')
auth = self.pyre.auth()
db = self.pyre.database()
account_created = False
# Create user
# In real app: add a dialog to get USER, NAME, and PASSWORD
try:
... |
def authorize_actions(self, response):
fail = 'error' in response
if self.refresh_timer:
Clock.unschedule(self.refresh_timer)
if fail:
self.user = {'idToken' : '', 'localId' : '', 'refreshToken' : ''}
self.user_id = ''
self.delete_token_file()
... | The code refreshes a user's authentication token using a refresh token. If the refresh fails, it prompts the user to sign in again, with a note to implement a dialog for re-authentication, potentially using demo credentials. It resets a refresh timer and handles authorization outcomes. | def refresh_user(self,dt):
auth = self.pyre.auth()
response = auth.refresh(self.user['refreshToken'])
self.refresh_timer = None
success = self.authorize_actions(response)
if not success:
self.update_label('Please sign in again')
# In real app: add dialog t... |
def update_label(self, string):
length = 50
lines = ''
for i in range(0, len(string), length):
lines = lines + '\n' + string[0+i:length+i]
self.rv.data.append({'text' : lines})
def authorize_with_token_file(self):
refresh_token = self.read_token_file()
auth = ... | The code demonstrates Pyrebase4 operations by authorizing with a token, reading user data from Firebase Realtime Database, validating stored data, then deleting documents, the token file, and the user account. It checks if previous data meets a condition, performs cleanup, and confirms success. | def pyrebase4_demonstration1(self):
if platform in ['ios', 'android']:
self.update_label('\n------------------------------------------')
else:
self.update_label('\n')
self.update_label('\nResuming Realtime Database demonstration.\n')
auth = self.pyre.auth()
... |
def update_label(self, string):
length = 50
lines = ''
for i in range(0, len(string), length):
lines = lines + '\n' + string[0+i:length+i]
self.rv.data.append({'text' : lines})
def sign_in(self, auth, user, password):
success, response = auth.sign_in_with_email(user, ... | This code demonstrates Firestore CRUD operations (Create, Read, Update, Delete) using a demo account. It creates a user, performs document operations, verifies data integrity, and handles errors. It also creates a shared document with diverse data types and saves user info for future sessions, instructing users to chec... | def rest_firestore_demonstration0(self):
self.update_label('\n\n')
self.update_label('Starting Firestore Database demonstration.\n')
auth = Authorize(APIKEY)
self.db = Firestore(PROJECT_ID)
# Create user
# In real app: add a dialog to get USER, NAME, and PASSWORD... |
def parse_files(in_man, in_ann, out_man, out_ann, read_format):
'''
-- parse full gdc annotation and manifest
-- write select gdc annotation and manifest for download
-- return uuids for download
'''
man, ann = read_inputs(in_man, in_ann)
man, ann = set_selection(man, ann)
write_outputs(... | The main task of the code is to parse UUIDs from input manifest and annotation files, select a subset based on specified formats, and download corresponding files using a token. It configures logging, constructs file paths, checks BAM files, retrieves tokens, and executes downloads with parameters like run type, ensuri... | def main(args):
'''
parse uuids and download selected set
'''
logging.basicConfig(
filename='.'.join([modname,'log']),
format='%(levelname)s:%(asctime)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO
)
in_man = os.environ['ann_dir'] + 'tcga/' + 'man... |
def read_inputs(cohort, tcga, a, b, c):
'''
start with field effect annotations, modify columns for herv study, revise
cohorts A and C based on updated tcga annotations
'''
dftcga = pd.read_csv(tcga, sep='\t')
dfa = pd.read_csv(a, sep='\t')
dfb = pd.read_csv(b, sep='\t')
dfc = pd.read_cs... | The code processes input data to generate a phenotypic file (`pheno_<cohort>.tsv`) for each cohort. It loads annotations, revises cohort data, sets file paths (e.g., tximport paths) in a dataframe, and writes the updated dataframe to a TSV file. Key steps include reading input files (`read_inputs`), modifying paths (`s... | def main(args):
'''
load annotations and revise cohorts, set paths for each cohort, write pheno
file for each cohort with field for tximport path
'''
cohort = args.cohort
tcga = args.tcga_ann
a = args.tsv_a
b = args.tsv_b
c = args.tsv_c
dftcga, dfa, dfb, dfc, dfmain = read_inputs... |
def execute_sql(query_type, **kwargs):
query = None
return_value = None
try:
if query_type not in ('select', 'update', 'insert', 'delete', 'replace'):
return "query type is not valid"
elif query_type != 'select' and type(kwargs['table']) == set and len(kwargs['table']) > 1:
return "only select type can con... | The main task of the code is to update monitored episode ranges for TV shows in a media management system (e.g., Sonarr) based on predefined thresholds. It queries database records, filters by show/plex IDs, retrieves series data, calculates episode thresholds, and adjusts monitoring settings if discrepancies exist. Up... | def update_show(show_id=None, plex_id=None):
updates = execute_sql("select", select={"id", "plex", "title", "last_monitor_season", "last_monitor_episode", "last_watch_season", "last_watch_episode"}, table={"monitor_episodes"}, order_by={"title"})
for update in random.sample(updates, len(updates)):
if show_id is not... |
def add_show(show_id=None):
logger.info("Adding Tagged Show(s) to Database for %s" % (show_id if show_id else "All Shows"))
series = sdr.get_series()
for show in series:
if show_id is not None:
try:
if int(show['id']) != int(show_id):
continue
except TypeError:
continue
try:
all_shows = exe... | The main task of the code is to migrate Sonarr series from a source quality profile to a target profile by updating show metadata, adding tags, disabling monitoring, and synchronizing changes with Plex. It iterates through all series, identifies those matching the source profile, applies profile and tag changes, update... | def modify_new():
from_profile = sdr.get_profile_id(os.environ.get('SONARR_FROM_PROFILE'))
to_profile = sdr.get_profile_id(os.environ.get('SONARR_TO_PROFILE'))
update_total = 0
series = sdr.get_series()
for show in series:
try:
if show['qualityProfileId'] == from_profile:
update_total += 1
logger.inf... |
def refresh_database():
try:
logger.info("Refreshing Database")
global users
global shows
global plex_api
global sdr
os.chmod('/app/logs', 0o777)
try:
plex_api = PlexServer(os.environ.get('PLEX_HOST'), os.environ.get('PLEX_API_KEY'))
except plexapi.exceptions.Unauthorized:
logger.error("Can't C... | The main task of the code is to monitor active Plex sessions, update user watch history in a database when users watch shows, and trigger show updates if users progress further in a series. It checks for active sessions, retrieves session data, compares it with stored history, and updates records accordingly, while han... | def session_search():
if plex_api is None:
refresh_database()
if plex_api:
try:
for x in plex_api.sessions():
logger.info("User: %s is watching %s" % (x.usernames[0], create_plex_title(x)))
try:
plex_id = x.grandparentRatingKey
user_id = [user['id'] for user in users if user['username'] == x... |
def refresh_database():
try:
logger.info("Refreshing Database")
global users
global shows
global plex_api
global sdr
os.chmod('/app/logs', 0o777)
try:
plex_api = PlexServer(os.environ.get('PLEX_HOST'), os.environ.get('PLEX_API_KEY'))
except plexapi.exceptions.Unauthorized:
logger.error("Can't C... | The function updates recently watched shows by fetching Plex history, mapping entries to local shows, and updating their status in the database. It handles user authentication, refreshes the database if needed, and ensures only existing shows are processed, logging errors for exceptions. | def recently_watched():
logger.info("Updating Recently Watched")
try:
if plex_api is None:
refresh_database()
except NameError:
refresh_database()
watched_shows = []
try:
for user in users:
try:
plex_api_user = PlexServer(os.environ.get('PLEX_HOST'), user['token'])
history = plex_api_user.libr... |
def __start_animation(msg):
global __stop
__stop = False
_thread.start_new_thread(__waiting_animation, (msg, ))
def __load_dataset():
properties = pd.read_csv(FOLDER_NAME+"properties_2016.csv", low_memory=False)
train = pd.read_csv(FOLDER_NAME+"train_2016_v2.csv")
return properties, train
def __... | The code processes and saves a dataset by merging training data with properties, applying encoding (OneHotEncoder or LabelEncoder), scaling features, randomizing indices, and serializing the result. It includes progress tracking, memory optimization via garbage collection, and data preprocessing steps for machine learn... | def save_parsed_dataset(dataset_filename, model='OneHotEncoder', min_importance=-1.0):
__start_animation("Loading datasets")
properties, train = __load_dataset()
__stop_animation()
__start_animation("Merge datasets")
merged = pd.merge(train, properties, on=["parcelid"])
del properties, tra... |
def __add_in_list(self, y, x):
# x is an element in a circular doubly-linked list
# insert y into this list at x's left
if x is None or y is None:
return
if y is x:
return
if verbose:
print("(2.) add y [{}] into x[{}]'s list at x left, result:... | The main task of the code is to extract the minimum node from a Fibonacci heap. It removes the node, transfers its children to the root list, updates the heap's minimum pointer, and consolidates the heap if necessary. The operation maintains heap properties and decrements the node count. | def extract_min(self):
z = self.h_min # the node that will be returned
if z:
x = z.child
if x:
while True:
# add x into z's list (H's root list) (at z's left)
temp = x.right
self.__add_in_list(x, z)
... |
def gen_cc_access_token(self):
"""
Generates an oauth token that lasts an hour so we can make our requests
"""
req = requests.post(self.token_url, data=self.get_token_params(),
headers=self.get_token_header())
# Check we got a valid response
i... | This function searches Spotify for a song by name and artist, retrieves the newest version's URI, and adds it to a list if found. It handles token refresh, validates responses, filters tracks by artist, extracts release dates, sorts by newest, and logs errors if no match is found. | def find_song(self, song_name, artist_name):
"""
Searches for a specified song in the spotify API
Params
------
song_name: str
The name of the song
artist_name: str
The name of the artist
"""
if self.access_token_is_expired:
... |
def build_tree(name, instructions):
current = NODE(name, 0, "dir", [])
# instructions I care about:
# \$ cd \.\.$ -> return
# \$ cd .*$ -> dive deeper
# \$ ls -> list nodes
while len(instructions):
instruction = instructions.pop(0)
if instruction == "$ cd ..":
... | The code processes a list of directory navigation and file size commands to build a file system tree rooted at '/'. It calculates the total size of all nodes (files/directories) with sizes under 100,000, summing these values and returning the result. | def part1(instructions):
# Passing lines [1:] because the first is always cd /
root, remaining_instructions = build_tree("/", instructions[1:])
assert len(remaining_instructions) == 0
return sum([calc_size(n) for n in find_max_sized_nodes(root, 100000)]) |
def format_data(lines: list[str]) -> list[list[list[float]]]:
"""
format data to form
[[[...input_data],[...desire_data]],[[...input_data],[...desire_data]],...,[[...input_data],[...desire_data]]]
:rtype: list[list[list[float]]]
:param lines: list of string each line from file
:return: formatte... | The function performs 10-fold cross-validation on a dataset using a neural network defined by `layers`, `bias`, `learning_rate`, and `momentum_rate`. It trains the network for `max_epoch` iterations with a stopping threshold of `epsilon`, splitting the data into training and validation subsets for each fold. The valida... | def cross_validate(layers: list[int], bias: float, learning_rate: float, momentum_rate: float, max_epoch: int, epsilon: float, file_path: str) -> list[list[float]]:
"""
cross validate data
:rtype: list[list[float]]
:param layers: layers of this network
:param bias: bias of this network
:param l... |
def _create_initial_seed_set(self, graph):
"""
Choosing initial seeds randomly.
"""
nodes = self.backend.get_nodes(graph)
self._seeds = random.sample(nodes, self.number_of_seeds)
def _reweight(self, graph):
"""
Create new seed weights.
"""
if self.... | This code samples a subgraph from the input graph by iteratively updating node sets until reaching the specified checkpoint size. It initializes backend components, validates node counts, creates seed nodes, and adjusts weights. The loop expands the node set via updates, then extracts the final subgraph, logging node/e... | def sample(self, graph, args,checkpoint):
self.number_of_nodes = checkpoint
if not self._seeds:
self._deploy_backend(graph)
self._check_number_of_nodes(graph)
self._create_initial_seed_set(graph)
self._reweight(graph)
# self._deploy_backend(graph... |
def _create_initial_seed_set(self, graph):
"""
Choosing initial seeds randomly.
"""
nodes = self.backend.get_nodes(graph)
self._seeds = random.sample(nodes, self.number_of_seeds)
def _reweight(self, graph):
"""
Create new seed weights.
"""
if self.... | The main task of the code is to sample a subgraph from the input graph by iteratively selecting nodes through a backend process. It initializes the backend, checks node counts, creates a seed set, reweights nodes, and repeatedly updates the node set until the required number of nodes is reached. Finally, it retrieves t... | def sample(self, graph, args):
self._nodes = set()
self._edges = set()
self._deploy_backend(graph)
self._check_number_of_nodes(graph)
self._create_initial_seed_set(graph)
self._reweight(graph)
while len(self._nodes) < self.number_of_nodes:
self._do_upd... |
def get_rack(r):
db = connection()
racks = db["Racks"]
rack = racks.find_one({"Name": r})
return rack
def get_image(name):
db = connection()
images = db["Images"]
result = images.find_one({'Name': name})
return result
def remove_image_from_rack_cache(r):
db = connection()
racks =... | The function checks if an image can be stored in a rack's cache. If the rack has sufficient capacity, it ensures the image isn't already cached. If not, it removes existing images until space is available, then updates or creates the image in the rack's cache to accommodate it. | def check_lru(r, img):
rack = get_rack(r)
image = get_image(img)
if rack["Capacity"] >= image["Size"]:
cached_images = []
for images in rack["ImageCache"]:
cached_images.append(images["Name"])
if img not in cached_images:
while rack["AvailableCapacity"] < imag... |
def connection():
conn = MongoClient(MongoDB_Server_IP, MongoDB_Server_Port)
db = conn[MongoDB_Server_Database]
return db
def get_server(name):
db = connection()
servers = db["Servers"]
result = servers.find_one({"Name": name})
return result
def check_lru(r, img):
rack = get_rack(r)
... | The main task of the code is to create a new instance in a database, ensuring its name is unique, validating server compatibility via LRU check, and updating server status. It connects to a database, checks for existing instances, retrieves server details, performs a resource check, inserts the new instance, and update... | def create_instance(new_instance):
db = connection()
instances = db["Instances"]
if instances.find({'Name': new_instance.Name}).count() > 0:
print("Instance \"{}\" already exists".format(new_instance.Name))
return
server = get_server(new_instance.Server)
check_lru(server["Rack"], new... |
def prep(save, d_feature, lamb, tasks, data_path, dataset,
K, Kq, val_batch_size, num_neighbors,
num_iterations, inner_steps, pd_updates,
eta_1, eta_2, eps,radius,meta_eta_1,meta_eta_2,delta,shift_time,eta_1_shift_1,eta_2_shift_1,meta_eta_1_shift_1,meta_eta_2_shift_1,eta_1_shift_2,et... | The code implements a meta-learning approach for fair machine learning, training a neural network across multiple tasks while balancing accuracy and fairness. It iteratively updates the model parameters and fairness constraints (e.g., demographic parity, equalized odds) using task-specific data, active learning (set_U)... | def fairSAOML(d_feature, lamb, tasks, data_path, dataset, save,
K, Kq, val_batch_size, num_neighbors,
num_iterations, inner_steps, pd_updates,
eta_1, eta_2, eps,radius,meta_eta_1,meta_eta_2,delta,net_dim):
val_save_path,save_folder = prep(save, d_feature, lamb, tasks, data_path, ... |
def gen_prefix(distance_limit, train_rate, val_rate, epsilon, self_weight):
return '{}-{}-{}-{}-{}'.format(distance_limit, train_rate, val_rate, epsilon, self_weight)
def load_dataset(fname):
with open(fname, 'r') as f:
data = json.load(f)
feature_tensor = torch.Tensor(data['feature_tensor'])
target = torch.Tens... | This code initializes a dataset for a graph-based model by either loading an existing dataset from a JSON file or generating a new one from a CSV file. It processes the California housing dataset, splits it into training/val/test sets, and transfers tensors/masks to a specified device (e.g., GPU). The dataset includes ... | def __init__(self, dir, distance_limit, train_rate, val_rate, epsilon, self_weight, device):
prefix = gen_prefix(distance_limit, train_rate, val_rate, epsilon, self_weight)
fname = '{}/california-{}.json'.format(dir, prefix)
if os.path.exists(fname):
dataset = load_dataset(fname)
else:
dataframe = pd.read... |
def gen_prefix(distance_limit, train_rate, val_rate, epsilon, self_weight):
return '{}-{}-{}-{}-{}'.format(distance_limit, train_rate, val_rate, epsilon, self_weight)
def load_dataset(fname):
with open(fname, 'r') as f:
data = json.load(f)
feature_tensor = torch.Tensor(data['feature_tensor'])
target = torch.Tens... | This code initializes a dataset for a graph-based model by either loading a preprocessed dataset from a file or generating it from raw CSV data. It processes the Melbourne housing dataset, splits it into training/validation/test sets, and moves tensors to a specified device. The dataset includes node features, edge ind... | def __init__(self, dir, distance_limit, train_rate, val_rate, epsilon, self_weight, device):
prefix = gen_prefix(distance_limit, train_rate, val_rate, epsilon, self_weight)
fname = '{}/melbourne-{}.json'.format(dir, prefix)
if os.path.exists(fname):
dataset = load_dataset(fname)
else:
dataframe = pd.read_... |
def join_elements(page: Page, course_names: dict(), instructor_names: list(), class_numbers: list()):
joined_elements = {}
print(course_names)
print(instructor_names)
print(class_numbers)
print('---')
for key in course_names.keys():
joined_elements[key] = [course_names[key], instructor... | The function `final_joining` consolidates course data from a webpage by joining elements like course names, instructors, and class numbers. It updates a dictionary (`courses_final`) by appending instructor and class number details to corresponding course entries, identified via key extraction from formatted strings. Th... | def final_joining(page: Page):
print('Finalizing values...')
joined = join_elements(page, course_names(page)[0], get_instructor_names(page), get_class_number(page))
courses_final = final_course_names(page)
for value in joined.values():
key = value[0][value[0].find('(') + 1 : value[0].find(')')]... |
def get_seq_no(packet):
_, seq_no, _, _ = parse_packet(decrypt_message(packet))
return int(seq_no)
def send_ack_packet(seq_no, addr):
send_ack_before_data = build_packet_formation('ACK', "", seq_no+1, "")
server.sendto(encrypt_message(send_ack_before_data), addr)
print(f'PACKET SENT[Ionut Server] --... | This function processes incoming data packets by verifying their type and integrity. It sends acknowledgment (ACK) packets for START, DATA (with correct checksum), and END packets. For DATA packets, it stores the message, data, and packet type globally for later use. The main task is to handle packet reception, validat... | def handle_reciving_data(server_data, packet_type, message, addr):
# save packet's sequence number
seq_no = get_seq_no(server_data)
# we send an ack packet if packet type is START
if packet_type == "START":
send_ack_packet(seq_no, addr)
# we send an ack packet if packet type is DATA and chec... |
def send_start_packet(addr, seq_no):
start_pkt = build_packet_formation(
'START', "", seq_no, "")
server.sendto(encrypt_message(start_pkt), addr)
print(f'PACKET SENT [Ionut Server]----->>>>{start_pkt}')
def send_data_packet(packet, addr, seq_no):
pack_type, mess_type, content = packet
packet... | The code implements a packet transmission protocol with retransmission on timeout. It sends a start packet, then data packets up to a retransmission limit, and finally an end packet. Sequence numbers are used for ordering, and ACK responses from a queue determine successful transmission. The function waits for ACKs bef... | def send_packet(packet, addr):
ack = True
# create a random sequence number
start_seq_no = random.randint(1, 20)
while ack:
# time.sleep(0.3)
try:
# wait for a response before retransmiting
if recieving_type_queue.get(timeout=0.3) == 'ACK':
ack = F... |
def send_start_packet(addr, seq_no):
start_pkt = build_packet_formation(
'START', "", seq_no, "")
# encript and send the packet
client.sendto(encrypt_packet(start_pkt), addr)
print(f'PACKET SENT[Ionut Client] ----->>>>{start_pkt}')
def send_data_packet(packet, addr, seq_no):
global send_time... | This code implements a reliable packet transmission mechanism by sending a start packet, followed by data packets, and ending with an end packet. Each packet is retransmitted until an ACK is received, using sequence numbers to manage order and ensure correct delivery. The function waits for ACKs with a timeout, retrans... | def send_packet(packet, addr):
ack = True
# create a random sequence number
start_seq_no = random.randint(1, 20)
while ack:
try:
# wait for a response before retransmiting
r = recieving_type_queue.get(timeout=0.3)
if r == 'ACK':
ack = False
... |
def get_seq_no(packet):
_, seq_no, _, _ = parse_packet(decrypt_packet(packet))
return seq_no
def send_ack_packet(seq_no, addr):
seq_no = int(seq_no)
send_ack_before_data = build_packet_formation('ACK', "", seq_no+1, "")
# encript and send the packet
client.sendto(encrypt_packet(send_ack_before_d... | This function processes incoming packets by acknowledging receipt (SEND ACK) based on packet type (START, DATA, END). For DATA packets, it validates checksums before storing message/data globally. It returns the saved message upon END packet processing, ensuring reliable data transfer with error checking and state rete... | def handle_reciving_data(server_data, packet_type, message):
# save packet's sequence number
seq_no = get_seq_no(server_data)
# we send an ack packet if packet type is START
if packet_type == "START":
send_ack_packet(seq_no, ADDRESS)
elif packet_type == "DATA" and recalculate_checksum(server... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.