dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def mainOption_View(studentSelected=None):
with open("setup.json", "r") as f:
globalVariables = json.loads(f.read())
connection = sqlite3.connect(globalVariables['database_location'], detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
cursor = connection.cursor()
cursor.execute(... | This function updates student attendance records by selecting a student, inputting session details (date, duration, attended time), validating inputs, and inserting the data into a SQLite database. It handles user selection, input validation, error messages, and confirms session creation before committing changes. | def mainOption_Update(studentSelected=None, dateReceived=None, validSessionDuration=None, validSessionDurationAttended=None):
with open("setup.json", "r") as f:
globalVariables = json.loads(f.read())
connection = sqlite3.connect(globalVariables['database_location'], detect_types=sqlite3.PARSE_DECLTYPES ... |
def _apply_covar(self, v):
covar_vec_prod = self.my_zero()
tot_count = 0
for i, data in enumerate(self.loader, 0):
inputs, labels = data[0].to(self.device), data[1].to(self.device)
tot_count += inputs.shape[0]
outputs = self.model(inputs)
loss = se... | The main task of the code is to compute the residual of a Hessian-vector product by subtracting a second-moment term from the Hessian product. It projects the input vector onto the gradient direction, reshapes the projection to match model parameters' dimensions, and combines it with a covariance product. The result is... | def _apply_covar_residual(self, v):
covar_vec_prod = self._apply_covar(v)
Hessian_prod = self._apply_Hessian(v)
v2 = torch.cat([g.contiguous().view(-1) for g in v])
proj = torch.dot(self.grad.detach(), v2) * self.grad.detach()
vec_new = []
curr_index = 0
for param... |
def _apply_Hessian(self, v):
Hg = self.my_zero()
counter = 0
for iter, batch in enumerate(self.loader):
input, target = batch[0], batch[1]
input = input.to(self.device)
target = target.to(self.device)
input = Variable(input)
target ... | The function Hv selects and applies a specific Hessian-related transformation to the input vector v based on the value of self.hessian_type, routing to private methods like _apply_Hessian, _apply_G, or _apply_covar depending on the type. | def Hv(self, v):
if self.hessian_type == 'Hessian':
return self._apply_Hessian(v)
elif self.hessian_type == 'G':
return self._apply_G(v)
elif self.hessian_type == 'H':
return self._apply_H(v)
elif self.hessian_type == 'covar':
return self._... |
def Hv(self, v):
if self.hessian_type == 'Hessian':
return self._apply_Hessian(v)
elif self.hessian_type == 'G':
return self._apply_G(v)
elif self.hessian_type == 'H':
return self._apply_H(v)
elif self.hessian_type == 'covar':
return self._... | This function computes the matrix-vector product by first applying a transformation Hv to the vector v, then iteratively subtracting scaled projections of v onto each eigenvector, weighted by their corresponding eigenvalues, to refine the result. | def mat_vec(self, v):
Av = self.Hv(v)
for eigvec, eigval in zip(self.vecs, self.vals):
coeff = eigval * self.my_inner(eigvec, v)
Av = self.my_sub(Av, self.my_mult_const(eigvec, coeff))
return Av |
def my_randn(self, skip_cuda=False):
v_0_l = []
for param in self.model.parameters():
Z = torch.randn(param.shape)
if self.double:
Z = Z.double()
if not skip_cuda:
Z = Z.to(self.device)
v_0_l.append(Z)
return v_0... | The code implements the Lanczos algorithm to approximate eigenvalues and eigenvectors of a matrix. It iteratively constructs a tridiagonal matrix $ B $ from vectors $ \alpha $ and $ \beta $, then computes its eigenvalues and eigenvectors using `np.linalg.eigh`, returning them alongside $ \alpha $ and $ \beta $. | def Lanczos(self, M):
v = self.my_randn()
v = self.my_div_const(v, self.my_norm(v))
alp = torch.zeros(M)
bet = torch.zeros(M)
if self.double:
alp = alp.double()
bet = bet.double()
alp = alp.to(self.device)
bet = bet.to(self.device)
... |
def get_orders(market_date=None):
orders_list = []
select_st = 'SELECT Ticker1, Ticker2 FROM stockpairs;'
pairs = execute_sql_statement(select_st, engine)
for index, row in pairs.iterrows():
# previous data for ols fit
select_st = "SELECT symbol, date, adjusted_close FROM "+str(row... | The main task of the code is to perform real-time trading analysis by calculating profit/loss metrics, comparing results against the S&P 500 benchmark, generating cumulative PnL and drawdown visualizations, and rendering trade performance summaries in a web template. It processes order data, computes Sharpe ratios, max... | def real_trade():
global bClientThreadStarted, client_thread
print(" >>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<")
print("Real trading ...", bClientThreadStarted)
if bClientThreadStarted == False:
client_thread.start()
bClientThreadStarted = True
print("Client thread ... |
def get_daily_data(symbol='', start=data_start_date, end=data_end_date, requestType=requestURL,
apiKey=myEodKey, completeURL=None):
if not completeURL:
symbolURL = str(symbol) + '?'
startURL = "from=" + str(start)
endURL = "to=" + str(end)
apiKeyURL = "api_token="... | The main task of the code is to prepare market data by checking if existing database tables are empty. If so, it downloads S&P 500 data and processes it to generate stock pairs for analysis. The function then transposes and formats these pairs into a list, which is passed to a HTML template for rendering. The workflow ... | def data_prep():
inspector = inspect(engine)
sp500_info = get_daily_data(completeURL=requestSP500)
sp500_info_df = pd.DataFrame(sp500_info)
if len(inspector.get_table_names()) == 0: # if no market data, download market data
download_market_data(metadata, engine, sp500_info_df)
else:
... |
def _isRightHeavy(self, node) -> bool:
return self._getBalanceFactor(node) < -1
def _getBalanceFactor(self, node) -> int:
return self._getHeight(node.left) - self._getHeight(node.right)
def _rightRotation(self, node):
print(f'RR: {node.val}')
newRoot = node.left
node.left = newRo... | This function balances an AVL tree node by checking if the subtree is right-heavy or left-heavy. If right-heavy, it performs a left rotation after potentially a right rotation on the right child. If left-heavy, it performs a right rotation after potentially a left rotation on the left child. The rotations adjust the tr... | def _balance(self, root) :
if self._isRightHeavy(root):
if self._getBalanceFactor(root.right) > 0:
root.right = self._rightRotation(root.right)
root = self._leftRotation(root)
elif self._isLeftHeavy(root):
if self._getBalanceFactor(root.left) < 0:
... |
def _getHeight(self, node):
if not node:
return -1
return node.height
def _balance(self, root) :
if self._isRightHeavy(root):
if self._getBalanceFactor(root.right) > 0:
root.right = self._rightRotation(root.right)
root = self._leftRotation(root... | This code inserts a value into a balanced binary search tree (BST), recursively placing the value in the appropriate subtree. It updates the node's height based on its children's heights and rebalances the tree using a _balance method to maintain AVL tree properties, ensuring efficient search and insertion operations. | def _insert(self, root, val):
if not root:
return self.Node(val)
if val > root.val:
root.right = self._insert(root.right, val)
else:
root.left = self._insert(root.left, val)
root.height = max(self._getHeight(root.left), self._getHeight(root.r... |
def sim_exchange(num_total_exchanges):
n = len(NODES_POSITIONS)
# we fix the node drifts
node_drifts = np.random.normal(loc=1.0, scale=NODE_DRIFT_STD, size=n)
passive_node_drift = np.random.normal(loc=1.0, scale=NODE_DRIFT_STD, size=1)
tx_delays = np.random.normal(loc=TX_DELAY_MEAN, scale=TX_DEL... | The code simulates and compares three delay calibration methods (TDoA, GN, and a custom approach) across varying numbers of measurements. It runs multiple repetitions, calculates root mean square errors (RMSEs) and execution times for each method, then aggregates results into data rows with mean, standard deviation, an... | def get_sim_data_rows(xs=[16, 64, 256, 1024], num_repetitiosn=1):
max_exchanges = max(xs)
repetitions = []
for i in range(num_repetitiosn):
exchanges = sim_exchange(num_total_exchanges=max_exchanges)
repetitions.append(exchanges)
data_rows = []
for x in xs:
rmses_tdoa = [... |
def isSquare(self) -> bool:
return self._N == self._M
def __inverse(self, mat: List[List[_Number]]) -> List[List[_Number]]:
det = self.__det(mat)
if det == 0:
raise ValueError("Matrix is not invertible")
else:
inverse_matrix = [[0 for _ in range(self._N)] for _ in... | The code computes the inverse of a square matrix. It first checks if the matrix is square; if not, it raises an error. For square matrices, it calculates the inverse using a helper method, transposes the result, and returns a new instance of the class with the transposed inverse matrix. | def Inv(self):
if not self.isSquare():
raise ValueError("Inverse is only defined for square matrices")
else:
return self.__class__(*self.__inverse(self.getArray())).transpose() |
def deploy_to_k8s():
""" Return a success string"""
api = kubernetes_api()
name = "k8s-api-proxy"
dep_api = api.resources.get(api_version="apps/v1", kind="Deployment")
deployment_manifest = {
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"labels":... | The main task of the code is to handle Kubernetes deployment actions based on event triggers. It decodes an action from the event data (defaulting to "create"), then executes corresponding operations: deploying to Kubernetes, deleting resources, or retrieving a service's IP address. The function logs trigger details an... | def main(event, context):
""" Main Entry point for the cloudfunction"""
print(
"""This Function was triggered by messageId {} published at {} to {}""".
format(context.event_id, context.timestamp, context.resource["name"]))
if 'data' in event:
action = base64.b64decode(event['data'])... |
def is_serial_port_created(self):
return True if self._serial_port else False
def _read_tele_info_entry(self):
# Read data out of the buffer until a carriage return / new line is found
return self._serial_port.readline().decode('Ascii').strip()
def _is_start_of_frame(entry):
return entry... | (The code runs a client to read TeleInfo data from a serial port, detecting valid entries and collecting frames by resetting frame storage upon detecting a new frame start. It logs warnings if the serial port isn't created, continuously reads entries, and stops when the port is closed, ensuring proper frame collection ... | def _run_client(self):
if not self.is_serial_port_created():
logger.warning('Could not start serial client thread: serial port not created')
return
logger.info(f'Start TeleInfo reading...')
frame = list()
first_frame_detected = False
while self.is_seria... |
def available(length, orientation, board):
#returns an array of available locations
possible = []
if orientation == 1:
#check left-right
for i in range(0, len(board)):
if i != floor((len(board)+1)/2)-1: #can NOT be in the same row as the target car!
for j in range... | The code generates a specified number of solvable Rush Hour puzzles of a given grid size by randomly placing cars, verifying their validity, and saving them to files if they meet solvability criteria. | def generate(size, quantity):
#generates rush hour puzzles of a particular grid size, difficulty, and quantity
acquired = 0
while acquired != quantity:
successful = False
while not successful:
twocars, threecars = random.randint(9, 12), random.randint(1, 4)
successful... |
def _plan(self,map,reuse=False):
reward_model = self._model_creator(map,reuse)
plan = self._recursive_planning_module(reward_model,reuse)
return plan
def _orientation_lstm_layers(self,fc_input,reuse=False):
with tf.variable_scope("orientation", reuse=reuse) as scope:
self.W_fc_1, self.... | The main task of this code is to construct a neural network that processes map data and planning information to generate policy and value outputs for decision-making. It uses conditional replanning (via `tf.cond`), softmax-normalized plan queries, and attention mechanisms to fuse location probabilities with planning fe... | def _create_map_reading_network(self):
# Map input
self.replan = tf.placeholder("bool", [], name='replan')
self.old_plan = tf.placeholder("float", [1, 63, 63, 4], name='old_plan')
# Lazy planning
self.plan = tf.cond(self.replan,
lambda: self._plan(self.map),... |
def _create_visual_input_network(self):
# State (Base image input)
self.input = tf.placeholder("float", [None, 84, 84, 3],name='view')
self.angle_neurons = tf.placeholder("float", [None, 30], name='angle_neurons')
self.visual_features = self._visual_layers(self.input,self.angle_neurons)
def _cre... | This function constructs a neural network within a TensorFlow variable scope, initializing sub-networks for visual input, vision-language processing, localization, and map-related tasks. It conditionally adds display-specific components if `for_display` is True, resets the network state, and collects trainable variable... | def _create_network(self, for_display):
scope_name = "net_{0}".format(self._thread_index)
with tf.device(self._device), tf.variable_scope(scope_name):
self._create_visual_input_network()
self._create_vlm_network()
self._create_localization_network()
self._create_map_reading_network()
... |
def make_set(vertice):
parent[vertice] = vertice
rank[vertice] = 0
def find(vertice):
if parent[vertice] != vertice:
parent[vertice] = find(parent[vertice])
return parent[vertice]
def union(vertice1, vertice2):
root1 = find(vertice1)
root2 = find(vertice2)
if root1 != root2:
... | This code implements Kruskal's algorithm to compute the minimum spanning tree (MST) of a graph. It initializes disjoint sets for vertices, sorts edges by weight, and iteratively adds edges to the MST if they connect disjoint sets, using union-find operations to detect and prevent cycles. | def kruskal(graph):
for vertice in graph['vertices']:
make_set(vertice)
minimum_spanning_tree = set()
edges = list(graph['edges'])
edges.sort()
for edge in edges:
weight, vertice1, vertice2 = edge
if find(vertice1) != find(vertice2):
union(vertice1, vertice2)
... |
def apply_props_dask(df,
ignore=1):
"""
Same as apply_props() but in parallelized version using DASK by partitioning df.
Local DASK cluster has to be started manually for efficient computation, see cluster_setup_howto().
Args:
df(pandas.DataFrame): Grouped localization... | (The main task of the code is to calculate immobile properties for localization groups in a `_picked.hdf5` file, apply filtering (e.g., threshold or standard deviation), and save results. It processes input data (`locs`, `info`), computes kinetic properties (parallelizable), filters groups, adds metadata, and exports f... | def main(locs,info,path,**params):
'''
Get immobile properties for each group in _picked.hdf5 file (see `picasso.addon`_) and filter.
Args:
locs(pandas.DataFrame): Grouped localization list, i.e. _picked.hdf5 as in `picasso.addon`_
info(list): Info _picked.yaml to... |
def preprocess_image(self, batched_inputs):
"""
Normalize, pad and batch the input images.
"""
images = [self.normalizer(x["image"].to(self.device)) for x in batched_inputs]
images = ImageList.from_tensors(images, self.size_divisibility)
images_whwh = list()
for ... | This code processes input images and instances through feature extraction, generates predictions using a neural network head, and computes losses during training. It handles both training and inference modes, preparing targets, managing frozen class layers, and calculating weighted losses for multi-task optimization. | def forward(self, batched_inputs, k=0, do_postprocess=True):
"""
Args:
batched_inputs: a list, batched outputs of :class:`DatasetMapper` .
Each item in the list contains the inputs for one image.
For now, each item in the list is a dict that contains:
... |
def generateHuffmanCodes(freq):
nodes = []
for i in freq:
nodes.append(node(freq[i], i))
while len(nodes) > 1:
nodes = sorted(nodes, key = lambda x:x.freq)
left = nodes[0]
right = nodes[1]
left.huff = 0
right.huff = 1
newNode = node(left.freq + righ... | The code encodes an input text using Huffman coding. It first calculates character frequencies, generates Huffman codes, encodes the text, pads the encoded binary string, converts it to a byte array, and returns the Huffman code mapping (reverseDict) along with the byte array for compressed storage or transmission. | def encode(originalText):
freq = {}
originalText = originalText.rstrip()
# Grenerating freq map
for i in originalText:
freq[i] = 0
for i in originalText:
freq[i] = freq[i] + 1
generateHuffmanCodes(freq)
encodedText = getEncodedText(originalText)
paddedEncodedText = getP... |
def time_passed():
return int(time.time() * 1000 - EPOCH)
def pol_tick():
global pol_amt
pol_amt += pol_rate
def money_tick():
global money_amt
money_amt += money_rate
def activ_inter():
global activ_int
global activ_count
if time_passed >= activ_int*activ_count:
activ_count+= 1
... | The code runs a Pygame-based game loop handling user input, resource management, and UI interactions. It tracks pollution and money rates, processes upgrades via mouse clicks, switches between tabs, and updates the display. The loop checks for events, updates game state (e.g., ticking resources, applying upgrades), and... | def main():
global tab, ticks, pol_rate, money_rate, pol_amt, money_amt, upgrade_track, alpha_Water, popup
#clock = pyg.time.Clock() #controlls fps and whatnot
pyg.mouse.set_cursor(pyg.cursors.diamond)
run = True
# game loop. this will be active to run the game
pyg.init()
wh... |
def get_shape_list(tensor, expected_rank=None, name=None):
"""Returns a list of the shape of tensor, preferring static dimensions.
Args:
tensor: A tf.Tensor object to find the shape of.
expected_rank: (optional) int. The expected rank of `tensor`. If this is
specified and the `tensor` has a different... | The main task of the code is to process input tokens through a transformer model to generate classification logits. It embeds input tokens, applies positional and token type embeddings, constructs attention masks, and feeds data through multiple transformer layers. The final sequence output is pooled using the first to... | def forward_transformer(self, input_ids, input_mask, token_type_ids, weights, config, is_training): # inp = [batch_size, seq_length, hidden_size]
#print("enter forward_transformer")
config = copy.deepcopy(config)
if not is_training:
config.hidden_dropout_prob = 0.0
config... |
def spect2():
errors3()
global sr1,sr2
# Load the two audio files
filename1 = download_path3.get()
filename2 = download_path4.get()
y1, sr1 = librosa.load(filename1, sr=None)
y2, sr2 = librosa.load(filename2, sr=None)
# Compute the spectrograms
spec1 = librosa.stft(y1)
spec2 ... | The main task of the code is to compare two audio spectrograms using metrics like MSE, SSIM, and cosine similarity, while displaying results in a GUI. It calculates per-band (low/medium/high frequency) similarity scores, converts metrics to percentages, and updates tkinter labels with these values for visual analysis o... | def comp_spect():
spec1, spec2 = spect2()
mse1var = tkinter.DoubleVar()
ssim_scorevar = tkinter.DoubleVar()
ssim_score_percentagevar = tkinter.DoubleVar()
B1var = tkinter.DoubleVar()
B2var = tkinter.DoubleVar()
B3var = tkinter.DoubleVar()
similarityvar... |
def _check_snake_eats_apple(self) -> bool:
s = self.get_snake()
a = self.apple
s_c = s.get_head_col()
s_r = s.get_head_row()
a_c = a.get_col()
a_r = a.get_row()
return s_c == a_c and s_r == a_r
def add_apple(self):
added = False
coords = []
... | The main task of the code is to move the snake in the specified direction, check if it eats an apple (adding a segment and spawning a new apple if true), verify boundary collisions, and return whether the game is over or if the snake is out of bounds. It handles snake movement logic, collision detection, and game state... | def move_snake(self,direction = None):
inside = self.snake.move(direction)
if self._check_snake_eats_apple():
self.snake.add_snake_part()
self.add_apple()
game_over = self._check_snake_bound()
if game_over or inside:
return game_over or inside
... |
def getRandomPlantingDays(self):
np.random.seed()
return np.random.randint(*self.planting_bounds.T)
def getLoss(self, planting_days, daily):
h = self.getHarvest(planting_days, daily)
if self.scenario == 0:
loss = [[ np.max(np.abs(h[h>0]-self.capacity_limit)),
... | This function optimizes planting schedules by iteratively mutating candidate solutions, comparing them against the current best, and updating the best solution if improvements are found. It tracks loss history, adjusts mutation probabilities dynamically, and optionally saves plots of harvest results. The goal is to min... | def optimize(self, n_iter, daily, Pstart=[], iter_offset=0, loss_history=[], plot_path=""):
if len(Pstart) > 0:
self.best_planting_days = Pstart
else:
self.best_planting_days = self.getRandomPlantingDays()
if len(loss_history) > 0:
self.loss_history = loss_his... |
def loadImages(dirName):
from os import listdir
hwLabels = []
trainingFileList = listdir(dirName)
m = len(trainingFileList)
trainingMat = np.zeros((m,1024))
for i in range(m):
fileNameStr = trainingFileList[i]
fileStr = fileNameStr.split('.')[0]
classNumStr = int(fileStr.split('_')[0])
if classNumStr == 9... | The code tests a Support Vector Machine (SVM) model using the Sequential Minimal Optimization (SMO) algorithm on digit recognition data. It loads training and test images, trains the SVM with a specified kernel (e.g., RBF), identifies support vectors, calculates training and test error rates by comparing predicted and ... | def testDigits(kTup=('rbf',10)):
dataArr,labelArr = loadImages('trainingDigits')
b,alphas = smoP(dataArr,labelArr,200,0.0001,10000,kTup)
dataMat = np.mat(dataArr)
labelMat = np.mat(labelArr).transpose()
svInd = np.nonzero(alphas.A>0)[0]
sVs = dataMat[svInd]
labelSV = labelMat[svInd]
print('there are %d Support ... |
def preprocess(self):
"""Converts the image to the input format the model expects"""
input_shape = self.input_dimensions[2:]
# Resize image to match input dimensions
img = cv2.resize(self.img, (input_shape[1], input_shape[0]))
# Convert image to RGB
img = cv2.cvtColor(img... | The code performs object detection by preprocessing input, predicting bounding boxes and class scores, filtering low-confidence detections, applying non-max suppression, rescaling coordinates, and returning a list of BoundingBox objects with class labels, confidence scores, and normalized coordinates. | def detect(self):
self.preprocess()
self.predict()
# return empty list in case of no detected objects
scores = np.max(self.predictions[:, 4:], axis=1)
if scores.size == 0:
return self.detected_objects
# Filter out object confidence scores below threshold
... |
def update_game_grid():
# Take a screenshot of the game and update the grid array
global GAME_GRID
unopened_count = 0
screen = ImageGrab.grab()
# Iterate by column then row
for i in range(0, GAME_GRID.shape[1]):
for j in range(0, GAME_GRID.shape[0]):
square_type = get_squar... | The code's main task is to use constraint satisfaction to solve a Minesweeper-like puzzle by analyzing the game grid's boundaries and open cells. It identifies border cells, partitions them into regions, and applies exact sum constraints based on adjacent opened cells' mine counts. By solving these constraints, it calc... | def logic_solver():
# Attempt to find safe cells using constraint solving
print('Engaging logic solver..')
# Find all border pieces
update_game_grid()
cell_list = []
for i in range(GAME_GRID.shape[1]):
for j in range(GAME_GRID.shape[0]):
if is_boundary(i, j):
... |
def count_flags_around(x_grid, y_grid):
count = 0
sq_type_num = -4
# Count flags in 8 surrounding squares
if inside_grid(x_grid, y_grid - 1) == sq_type_num: count+=1
if inside_grid(x_grid - 1, y_grid) == sq_type_num: count+=1
if inside_grid(x_grid, y_grid + 1) == sq_type_num: count+=1
if in... | The function identifies and opens safe squares with guaranteed no mines by checking if a numbered cell's value matches surrounding flags, ensuring unopened cells exceed flags. If successful, it clicks those squares; otherwise, it resorts to random clicks or a solver logic when no safe moves are found. | def attempt_open_squares():
# Attempt to open safe squares guaranteed no mines
success = False
for i in range(0, GAME_GRID.shape[1]):
for j in range(0, GAME_GRID.shape[0]):
if GAME_GRID[j][i] > 0:
current_square = GAME_GRID[j][i]
flags = count_flags_arou... |
def calibrate():
# Calibrate game grid
global FIRST_SQUARE_X, FIRST_SQUARE_Y, GAME_GRID, SQUARE_SIZE, HIGH_RES
# Check screen resolution
if pyautogui.size()[0] > 1920:
HIGH_RES = True
SQUARE_SIZE = 50 if HIGH_RES else 38
ss = ImageGrab.grab()
ss = np.array(ss)
grey_color = [G... | The code executes a minesweeper-like game, automating mine flagging and square opening. It initializes the grid, performs a random click, and iteratively updates the game state until completion. The loop tracks steps and guesses, outputting the result (win/loss) and total steps. Debugging sections for boundary detectio... | def main():
#Start by game board calibration
calibrate()
print(GAME_GRID.shape)
input('Press enter to continue:')
# Debug // Print grids
# boundary_list = []
# boundary_grid = np.zeros(shape=GAME_GRID.shape)
# for i in range(0, GAME_GRID.shape[1]):
# for j in range(0, GAME_GRID... |
def getLine(sock):
try:
lines=[]
while True:
chr=recv_s(sock,1)
lines.append(chr)
# if lines is "...\r\n"
if (len(lines)>=2 and lines[len(lines)-2]==b'\r' and lines[len(lines)-1]==b'\n'):
break
result=(b"".join(lines)... | This function reads HTTP chunked transfer-encoded data from a socket. It processes each chunk by parsing size lines, extracting data, and assembling all chunks into a complete byte string. It handles chunk extensions, discards trailing CRLF, and removes trailer headers before returning the combined content. | def getContentFromChunks(self,sock):
try:
content=[]
while True:
sizeLine=getLine(sock)
# omit '\r\n'
if (sizeLine.find(';')!=-1): #chunk extension included
sizeLine=sizeLine[0:sizeLine.find(';')].strip()
... |
def player_input(game, controls):
y = helpers.get_input()
if y == controls['up'] and game.player.y > 1:
game.player.y -= 1
if y == controls['left'] and game.player.x > 0:
game.player.x -= 1
if y == controls['down'] and game.player.y < game.grid_size.y - 2:
game.player.y += 1
... | The `game_loop` function manages a game's continuous operation by processing player input, AI logic, and grid updates. It checks for player collisions with guards (ending the round) and interactions with life orbs (activating effects). If the player reaches the door, the score increases, and a new round begins. The loo... | def game_loop(game, controls):
while True:
game.was_paused = False
game = player_input(game, controls)
if not game.was_paused:
game = ai(game)
game = grid(game)
if game.player.y == game.door and game.player.x == game.grid_size.x - 1:
game.s... |
def load_config_file():
try:
with open('resources/data/config.pickle', 'rb') as config_file:
grid_size, color, controls, difficulty = pickle.load(config_file)
config_file.close()
except FileNotFoundError:
setup()
with open('resources/data/config.pickle', 'rb') as conf... | The settings_menu function allows users to adjust grid dimensions, controls, difficulty, and color (on Windows) through a menu, saves changes to a config file, and returns the updated settings. | def settings_menu():
grid_size, color, controls, difficulty = load_config_file()
while True:
helpers.clear()
print('Settings\n\nType the number of an option.\n\n1: Change Grid Length\n2: Change Grid Height'
'\n3: Change Controls\n4: Change Difficulty')
if helpers.get_os() =... |
def new_round(game):
game.door = random.randint(1, game.grid_size.y - 2)
game.player = GameElement(0, random.randint(1, game.grid_size.y - 2))
number_of_guards = round((game.grid_size.x * (game.grid_size.y - 2)) * game.difficulty)
index = 1
while index <= number_of_guards:
new_guard = GameEl... | The code implements a menu-driven game interface, allowing users to start new games, load saved games, view high scores, access instructions, adjust settings, or quit. It loads configuration settings, handles user input for menu navigation, initializes game instances, and triggers game loops or display functions based ... | def main():
grid_size, _, controls, difficulty = config.load_config_file()
# --menu loop--
while True:
helpers.clear()
option = helpers.get_input('Type the number of an option.\n\n1: New Game\n2: Load Game'
'\n3: Highscore\n4: Instructions\n5: Settings\n6: ... |
def adjust_train_test(self):
print(self.label)
print("- Importing train, test and val")
train_df=pd.read_csv(self.config.train_data_path)
test_df=pd.read_csv(self.config.test_data_path)
val_df=pd.read_csv(self.config.val_data_path)
X = pd.concat([train_df, test_df]).res... | This function performs hyperparameter tuning for multiple machine learning models using GridSearchCV or RandomizedSearchCV, trains the best-performing models, and logs results to MLflow. It preprocesses data, evaluates models via cross-validation or specified splits, saves optimized pipelines, calculates metrics, and s... | def grid_search(self, models, params, save_to_mlflow=True, random_grid=False, n_random_hyperparameters=10):
X, y, ps, preprocessor, val_df = self.adjust_train_test()
mlflow.set_experiment(self.label)
print("Hyperparameter-tuning and training best model for each algo: \n")
algo_best_mo... |
def disable(self):
self.fcfs_b.config(state=tk.DISABLED)
self.sjf_b.config(state=tk.DISABLED)
self.npp_b.config(state=tk.DISABLED)
self.pp_b.config(state=tk.DISABLED)
self.srtf_b.config(state=tk.DISABLED)
self.rr_b.config(state=tk.DISABLED)
def algo(self, _algorithm, fram... | This code creates a GUI window for inputting process scheduling parameters (arrival time, burst time, priority, or quantum) based on the selected algorithm. It disables the main window, opens a new Toplevel window with input fields and a submit button that triggers the specified scheduling algorithm with the provided p... | def process_window(self, algo_title, algo = 0):
self.disable()
self.window.iconify()
main_window = tk.Toplevel(self.window)
main_window.geometry("900x700")
main_window.title("Process Scheduling")
main_window.resizable(False, False)
main_frame = tk.Frame(main_windo... |
def _get_pieces_position(self, state: State, enemy: bool) -> List[int]:
if enemy:
out = [pos for pos, piece in enumerate(state.board) if piece * state.turn < 0]
else:
out = [pos for pos, piece in enumerate(state.board) if piece * state.turn > 0]
return out
def _update_pin... | The code initializes a class to track chess board positions, attacked squares, and pinned pieces. It extracts enemy and friendly positions, updates attack and pin maps, and identifies squares attacking the king for strategic evaluation in a game context. | def __init__(self, state: State):
self.enemy_positions: List[int] = self._get_pieces_position(state, True)
self.friendly_positions: List[int] = self._get_pieces_position(state, False)
self.attacked_map_dict: Dict[int, List[int]] = {} # convenient function
self.pin_map_dict: Dict[int, Tu... |
def _get_pieces_position(self, state: State, enemy: bool) -> List[int]:
if enemy:
out = [pos for pos, piece in enumerate(state.board) if piece * state.turn < 0]
else:
out = [pos for pos, piece in enumerate(state.board) if piece * state.turn > 0]
return out
def _update_pin... | The code updates the game state by gathering enemy and friendly piece positions, determining pinned pieces, mapping attacked squares, and identifying positions threatening the king, essential for evaluating board status in a chess AI. | def _update(self, state: State):
self.enemy_positions = self._get_pieces_position(state, True)
self.friendly_positions = self._get_pieces_position(state, False)
self.pin_map = self._update_pin_map(state)
self.attacked_map = self._update_attacked_map(state)
self.positions_atacking... |
def _convert_move_to_ints(self, move: Union[str, List]) -> Tuple[int, int, Optional[str]]:
"""Convert move to ints"""
if len(move) == 5:
# TODO: consistency for types in this var
promoted_piece: Optional[str] = move[4]
move = move[:4]
else:
promot... | This function executes a chess move by updating the board state, handling special rules like en passant and castling, validating the move, tracking game state changes, and updating the optimizer. It also increments move counters, toggles player turns, and logs move history for debugging and repetition checks. | def move(
self,
move: Union[str, List[int]],
check_allowed_moves: bool = False,
update_optimizer: bool = True,
):
if isinstance(move, list):
pos_i, pos_f, promoted_piece = move[0], move[1], move[2]
else:
pos_i, pos_f, promoted_piece = self._co... |
def conform_index(pdf,pages_ten_percent, index):
blank_pages = 0
for page_number, page in enumerate(pdf.pages):
text = page.extract_text(x_tolerance=3, y_tolerance=3)
if text == None:
page_number += 1
blank_pages += 1
if blank_pages > 2:
sys.ex... | The code processes a PDF file to generate an indexed version by: (1) validating input, (2) extracting text from the first 10% of pages, (3) creating an index, (4) locating index entries in the full document, (5) inserting bookmarks/outlines at found positions, and (6) saving the indexed PDF. It handles file errors and ... | def main():
# Verify the two arguments in the command line if not print some error message
if not len(sys.argv) == 2:
print("Usage: python3 indexator.py some_file.pdf")
sys.exit()
pdf_name = sys.argv[1]
try:
with pdfplumber.open(pdf_name) as pdf:
pdf_lenght = len(pdf... |
def set_key(self, key):
"""set the key to major or minor diatonic scale"""
if key == "minor":
self.notes_in_key = MINOR_SCALE
return
elif key == "major":
self.notes_in_key = MAJOR_SCALE
return
assert False, 'ERROR: key must be either "major... | The function `create_score` generates a musical score by iterating through specified fractal dimensions, adjusting tempo multipliers, and appending pitches and durations to the score. It sets the musical key, scales durations using tempo factors, and saves the final composition to a file. The process concatenates measu... | def create_score(
self,
key,
tempo_multiplier_over_time,
fractal_dimensions_to_add,
pitches_at_dimension,
durations_at_dimension,
filename,
):
"""Create a score by concatenating measures with one measure at a given
fractal dimension"""
... |
def reset(self):
self.number_of_run = 0
self.number_of_literal = 0
self.literal_list = []
def __is_run(chunk): # check if the given bit string is a run of 0's
for i in range(0, len(chunk)):
if chunk[i] != "0":
return False
return True
def compress_chu... | The code performs WAH (Wavelet Arithmetic Compression) on input data by processing each of 16 columns. It concatenates column values into strings, splits them into 8-bit chunks, and applies BBC (Bit-Block Compression) by identifying runs (repeated bits) or literals. It tracks run/literal counts, compresses chunks via `... | def compress(self, data): # WAH compression on data's columns
for column in range(16):
string = ""
# combine each column per row into a string
for each_line in data:
string += each_line[column]
# divide the string into list with length of 8 bits... |
def selfies_split(selfies):
return selfies.replace(']', '] ').split()
def token_classify (selfies_token):
### initialization of lists
atoms_idx_list=[]
branch_idx_list=[]
ring_idx_list=[]
skip_list=[]
for i,token in enumerate(selfies_token):
if i in skip_list:
conti... | The code processes a SELFIES string by splitting it into tokens, classifying them into atoms, branches, and rings, then identifying molecular blocks using these classifications. It returns fragmented blocks of the SELFIES structure for further analysis or manipulation. | def process_selfies(selfies):
tokens=selfies_split(selfies)
# print(tokens)
atoms_idx_list,branch_idx_list,ring_idx_list=token_classify(selfies_token=tokens)
# print(f'branch: {branch_idx_list}')
# print(f'ring: {ring_idx_list}')
selfies_frag=find_block(tokens,atoms_idx_list,branch_idx_list,ring... |
def toggle_flagged(self):
if self.is_leaf:
self.flagged = not self.flagged
self.update_w()
else:
for child_key in self.get_node().get_child_keys():
self.get_node().get_child_node(child_key).get_widget().toggle_flagged()
def clear_flagged(self):
... | This method handles keystroke inputs with default behaviors: mapping 'u'/'d' to "up"/"down", toggling flags on space, clearing flags on 'c', toggling expansion on left-arrow (if not a leaf), and updating test details for up/down keys. It allows subclasses to override key handling while providing base functionality for ... | def unhandled_keys(self, size, key):
"""
Override this method to intercept keystrokes in subclasses.
Default behavior: Toggle flagged on space, ignore other keys.
"""
key = "up" if key == 'u' else key
key = "down" if key == 'd' else key
if key == " ":
... |
def feature_extraction(data):
english_common_words, dutch_common_words = get_words()
english_suffix, dutch_suffix, english_prefix, dutch_prefix, dutch_letter_combinations = get_suffix_prefix()
features = []
for line in data:
feature = [False] * 10
words_length = 0
number_of_engli... | The main task of the code is to read input data, extract features, load a pre-trained hypothesis model (either a decision tree or AdaBoost), and apply it to make decisions or predictions on the extracted features. | def main():
data = read_input_file(sys.argv[1])
features = feature_extraction(data)
with open(sys.argv[2], 'rb') as handle:
hypo = pickle.load(handle)
if type(hypo) == TreeNode:
decision(hypo, features)
else:
adaboost(hypo, features) |
def goal_with_higher_number_rows(rows, goal_state):
a_number = 0
b_number = 0
for row in rows:
if row[goal_state] == "en":
a_number += 1
else:
b_number += 1
return LeafNode("en") if a_number > b_number else LeafNode("nl")
def all_belong_to_same_goal(rows, goal_sta... | This function recursively constructs a decision tree by selecting the feature with minimum entropy to split data, creating tree nodes and leaf nodes based on goal state consistency, and partitioning data for left/right child nodes until base cases are met. | def decision_tree_helper(features, cols, goal_state_column, parent_features):
# Base Case
if not features:
return goal_with_higher_number_rows(parent_features, goal_state_column)
value = all_belong_to_same_goal(features, goal_state_column)
if value:
return LeafNode(value)
if len(col... |
def get_min_entropy_col(features, cols, goal_state_column):
entropy_list = [0] * (goal_state_column + 1)
min_entropy = 1
min_entropy_col = -1
for col in cols:
true_rows, false_rows = partition_data(features, col)
entropy_list[col] = entropy(true_rows, false_rows, goal_state_column)
... | The code implements an AdaBoost algorithm by iteratively generating weak hypotheses (decision trees) using entropy-based feature selection. It calculates each hypothesis's significance, adjusts feature weights based on classification accuracy, and normalizes weights. The process repeats K times, removing selected featu... | def adaboost_helper(features, cols, goal_state_column, K):
hypos = []
for i in range(K):
min_entropy_col = get_min_entropy_col(features, cols, goal_state_column)
node = TreeNode(min_entropy_col)
true_rows, false_rows = partition_data(features, min_entropy_col)
true_goal = goal_wi... |
def feature_extraction(data):
number_of_examples = len(data)
english_common_words, dutch_common_words = get_words()
english_suffix, dutch_suffix, english_prefix, dutch_prefix, dutch_letter_combinations = get_suffix_prefix()
features = []
for line in data:
language, words = line.split("|")
... | The main task of the code is to process input data by reading a file, extracting features, and applying either a decision tree or AdaBoost algorithm based on the third command-line argument. It structures features into columns and triggers the corresponding machine learning model for analysis. | def main():
data = read_input_file(sys.argv[1])
features = feature_extraction(data)
cols = [i for i in range(number_of_features)]
if sys.argv[3] == "dt":
decision_tree(features, cols)
elif sys.argv[3] == "ada":
adaboost(features, cols) |
def printMessage(self,message):
print(message)
def isLocalDnsOk(self):
"Just checking timed out is occured for excessive load or network problem"
#make sure that HOST is not censored in this network
dnsOb = SocketFunctions()
HOST = "www.google.com"
isNameResolved = False
for i in range(self.Iterate):
i... | This code checks for DNS censorship by comparing responses from local and remote DNS servers. It queries both DNS types multiple times, analyzes error codes, IP overlaps, and domain existence to determine if a domain is censored. It returns a report with error codes, IP lists, and censorship status based on resolution ... | def dns_censorship_check(self,HOST):
dnsOb = SocketFunctions()
f1 = open("Details.txt","w")
f1.close()
f1 = open("LocalIpList.txt","w")
f1.close()
f1 = open("RemoteIpList.txt","w")
f1.close()
#f = open("domainName.txt","r")
isNameResolved=False
errorCodeLocal = []
errorCodeRemote = []
ipListLoca... |
def get_api_now(self,city_name):
try:
apiKey = "sr4hg8fdmewr6ryuu2g34tthttq7jeq6"
origin_url="http://api.openweathermap.org/data/2.5/weather?"
data= requests.get(origin_url)
url= origin_url + "appid=" + apiKey + "&q=" + city_name
data = request... | The code searches for a city in a PostgreSQL database. If the city exists, it retrieves weather data, prayer times, and displays results; otherwise, it shows an error. | def city_search(self):
self.city_name = self.searchBox.text().title()
conn = psycopg2.connect(database="Weather_App",
user="postgres",
password="1234",
host="localhost",
port="... |
def div_interval(x, y):
"""Return the interval that contains the quotient of any value in x divided by
any value in y. Division is implemented as the multiplication of x by the
reciprocal of y."""
"*** YOUR CODE HERE ***"
assert not (lower_bound(y) <= 0 <= upper_bound(y)), 'Divide by zero'
recip... | The main task of the code is to compute the equivalent resistance of two resistors in parallel using the formula (r1 * r2) / (r1 + r2), where `mul_interval` calculates the product, `add_interval` calculates the sum, and `div_interval` performs the division of the two intervals. | def par1(r1, r2):
return div_interval(mul_interval(r1, r2), add_interval(r1, r2)) |
def interval(a, b):
"""Construct an interval from a to b."""
assert a <= b, 'Lower bound cannot be greater than upper bound'
return [a, b]
def div_interval(x, y):
"""Return the interval that contains the quotient of any value in x divided by
any value in y. Division is implemented as the multiplicat... | The function `par2` calculates the parallel combination of two intervals `r1` and `r2` using interval arithmetic. It computes the reciprocal of the sum of reciprocals of `r1` and `r2`, equivalent to `1/(1/r1 + 1/r2)`, representing parallel resistance in electrical circuits. | def par2(r1, r2):
one = interval(1, 1)
rep_r1 = div_interval(one, r1)
rep_r2 = div_interval(one, r2)
return div_interval(one, add_interval(rep_r1, rep_r2)) |
def take_turn(num_rolls, opponent_score, dice=six_sided):
"""Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free Bacon).
Return the points scored for the turn by the current player. Also
implements the Hogtimus Prime and When Pigs Fly rules.
num_rolls: The number of dice rolls that will ... | The code simulates a turn-based game between two players using provided strategies to determine dice rolls. Players take turns, updating scores based on dice outcomes, with special rules for dice swapping (Pork Chop) and score swapping (Swine Swap) when one score is double the other. The game continues until either pla... | def play(strategy0, strategy1, score0=0, score1=0, goal=GOAL_SCORE):
"""Simulate a game and return the final scores of both players, with
Player 0's score first, and Player 1's score second.
A strategy is a function that takes two total scores as arguments
(the current player's score, and the opponent'... |
def get_pawn_moves_bb(sq, board):
attacks = tables.PAWN_ATTACKS[board.color][sq.index] & board.combined_color[~board.color]
quiets = tables.EMPTY_BB
white_free = Square(sq.index + np.uint8(8)).to_bitboard() & board.combined_all == tables.EMPTY_BB
black_free = Square(sq.index - np.uint8(8)).to_bitboard(... | This function generates all possible moves for a specified chess piece on a board. For pawns, it handles promotion moves (queen, rook, knight, bishop) when reaching the 7th/2nd rank. For other pieces, it calculates valid moves using bitboard operations. It yields Move objects for each valid destination square, with spe... | def gen_piece_moves(src, board, piece):
if piece == Piece.PAWN:
moveset = get_pawn_moves_bb(src, board)
# Handle promotion moves
white_promote = src.to_bitboard() & tables.RANKS[Rank.SEVEN] != tables.EMPTY_BB
black_promote = src.to_bitboard() & tables.RANKS[Rank.TWO] != tables.EMPTY_... |
def detect_and_replace(self, frame, replace_img):
contours, hierarchy = self.find_contours(frame)
try:
# find biggest bounding box
biggest, index = 0, 0
rect = list()
for i in range(len(contours)):
x, y, w, h = cv2.boundingRect(contours[i])... | This function processes a video frame by replacing specific regions with a predefined image, converts the frames to RGB format, and updates both original and modified video displays. It halts processing if a pause button is activated or if the frame is invalid, stopping the video timer accordingly. | def show_result_video(self):
# Video, change the post-it part in video
replace_img = self.replace_img
ret, frame = self.cap.read()
if frame is not None:
replace_result = self.detect_and_replace(frame.copy(), replace_img)
replace_result = self.__convert_bgr_to_rg... |
def detect_and_replace(self, frame, replace_img):
contours, hierarchy = self.find_contours(frame)
try:
# find biggest bounding box
biggest, index = 0, 0
rect = list()
for i in range(len(contours)):
x, y, w, h = cv2.boundingRect(contours[i])... | This function captures a video frame from a webcam, replaces detected regions with a specified image, converts frames to RGB format, and updates two video displays with the original and modified frames in real-time. If no frame is captured, it stops the camera timer and exits. | def show_result_camera_stream(self):
# webcam, change the post-it part in camera stream
replace_img = self.replace_img
ret, frame = self.cap.read()
if frame is not None:
replace_result = self.detect_and_replace(frame.copy(), replace_img)
replace_result = self.__... |
def __convert_rgb_to_bgr(rgb_img_path):
# open image with Image.open to avoid error from opencv
# convert rgb image to bgr for opencv
rgb_img = np.array(Image.open(rgb_img_path).convert("RGB"))
return cv2.cvtColor(rgb_img, cv2.COLOR_RGB2BGR)
def on_picture_button_is_checked(self, replace... | This function processes a replacement image by converting it to BGR format and triggering media-specific handling based on user-selected radio buttons. It disables/enables the pause button depending on the selected mode (picture, video, camera) and calls corresponding methods to manage image/video/camera processing wor... | def show_replace_result(self):
assert self.replace_image_path is not None
replace_img = self.__convert_rgb_to_bgr(self.replace_image_path)
replace_img = Image.fromarray(replace_img)
# check which radiobutton has been selected
if self.ui.radioButton_picture.isChecked():
... |
def inc_group_layers(n_list, d_list, c_list):
if (n_list.ndim != 1) or (d_list.ndim != 1):
raise ValueError("Problem with n_list or d_list!")
if (d_list[0] != inf) or (d_list[-1] != inf):
raise ValueError('d_list must start and end with inf!')
if (c_list[0] != 'i') or (c_list[-1] != 'i'):
... | The function calculates transmission (T) and reflection (R) coefficients of light through a multilayer structure containing coherent stacks and incoherent layers using the transfer matrix method (TMM). It computes angles via Snell's law, processes stacks with coh_tmm, calculates absorption in incoherent layers, constru... | def inc_tmm(pol, n_list, d_list, c_list, th_0, lam_vac):
# Convert lists to numpy arrays if they're not already.
n_list = array(n_list)
d_list = array(d_list, dtype=float)
# Input tests
if (np.real_if_close(n_list[0]*np.sin(th_0))).imag != 0:
raise ValueError('Error in n0 or th0!')
gro... |
def events(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
if event.type == pg.VIDEORESIZE:
self.screen = pg.display.set_mode((event.w, event.h), pg.RESIZABLE)
if event.type == pg.KEYDOWN:
if event.key ... | This code runs a game loop that maintains the game's frame rate, processes events, updates game state, and renders visuals. It sets self.playing to True, then continuously calculates delta time, handles events, updates game logic, draws frames, and updates the display until self.playing is set to False. | def run(self):
self.playing = True
while self.playing:
self.dt = self.clock.tick(FPS) / 1000
self.events()
self.update()
self.draw()
pg.display.update() |
def buildCommitFromRevrecRawCommit(self, rawCommit):
commit = {}
commit["id"] = rawCommit["changeId"]
commit["author"] = rawCommit["owner"]["accountId"]
commit["modifiedFileNames"] = [x["location"] for x in rawCommit["filePaths"]]
commit["reviewers"] = [x["accountId"] for x in ra... | The main task of the code is to process commits from a dataset by handling different dataset types (revrec, seoss, perceval), filtering out invalid commits with no modified files, removing self-reviewers, and testing valid commits for reviewer recommendations. It initializes project start dates, prepares commits for an... | def analyzeCommits(self):
# Traverse every commit
datasetType = self.config["dataset"]["type"]
for i, rawCommit in enumerate(self.commits):
if datasetType == "revrec":
commit = self.buildCommitFromRevrecRawCommit(rawCommit)
elif datasetType == "seoss":
... |
def readCommits(self):
commitsFilePath = self.config["dataset"]["commitsFilePath"]
if self.config["dataset"]["type"] == "revrec":
with open(commitsFilePath, encoding="utf-8") as file:
self.commits = json.load(file)
self.commits.reverse() # Data from rev-rec i... | The code's main task is to process commits by reading them, analyzing their content, saving results, and ensuring cleanup by closing the driver if using the "rstrace+" method, all within a try-finally block for reliability. | def run(self):
try:
self.readCommits()
self.analyzeCommits()
self.saveResults()
finally:
if self.config["method"] == "rstrace+":
self.closeDriver() |
def teslaTop(self):
t.color("#E82127")
self.e(-160, 160)
t.left(18)
self.d(-500, 40)
t.right(89.5)
self.d(500, 39)
t.end_fill()
self.e(-155, 133)
def letterT(self):
self.b(90.5, -500, 38, 70)
t.circle(-30, 80)
t.left(90)
t.... | The code defines a method `teslaLogo` that draws the Tesla logo using Turtle graphics by sequentially calling sub-methods like `teslaTop`, `letterT`, `whiteV`, and others to render each part of the logo. Finally, it hides the turtle cursor and finalizes the drawing with `turtle.done()` to display the completed logo. | def teslaLogo(self):
self.teslaTop()
self.letterT()
self.whiteV()
self.tLetter2()
self.eLetter()
self.sLetter()
self.lLetter()
self.aLetter()
t.hideturtle()
turtle.done() |
def _reduction_a_cell_do(ip, p, filters, net_type, cell_num, total_num_cells, total_training_steps, do_rate=0.3,
block_id=None):
"""Adds a Reduction cell for NASNet-A (Fig. 4 in the paper).
Args:
ip: Input tensor `x`
p: Input tensor `p`
filters: Number of output... | The code defines a function to instantiate a **NASNetLarge** neural network model with configurable parameters, including dropout/droppath mechanisms, input shapes, and pre-trained weights. It constructs the model architecture using convolutional blocks, reduction/normal cells, and applies global pooling/classification... | def NASNet_large_do(net_type, include_top=True, do_rate=0.3, weights='imagenet', input_tensor=None,
input_shape=None, total_training_steps=None, penultimate_filters=4032, num_blocks=6,
stem_block_filters=96, skip_reduction=True, filter_multiplier=2, pooling=None, classes=1000):
... |
def readInputTETrace():
global InputTrace,C, classes, numofclass, basket, ETpaired, paired,FIS, TE, numofbasket
f= open('TEInv.txt', 'w').close()
#f= open('EInv.txt', 'w').close()
lines = open(InputTrace).read().splitlines()
numoflines=len (lines)
#### removing empty members from list#######################... | (The code processes an input trace to identify temporal invariants and event frequencies. It first reads the trace, calculates immediate time invariants, merges them into temporal events (TE) with frequencies, and writes invariants to a file. Then, it determines event frequencies, recalculates invariants from these fre... | def main(InputTrace):
baskets=readInputTETrace()
pairedBasket,pairedTime, numofbasket= calculateImmidiateTimeInv(baskets)
TE, frequency= MergingTime (pairedBasket,pairedTime, numofbasket)
WriteInvariantsToFile (TE)
allFreq= FindEventFrequency(baskets)
pairedBasket2,pairedTime2, numofbasket= calculateI... |
def split_seq(seq, sep):
start = 0
while start < len(seq):
try:
stop = start + seq[start:].index(sep)
yield seq[start:stop]
start = stop + 1
except ValueError:
yield seq[start:]
break
def ChangeFormat(lines):
global var_name
MergedL... | The code processes an input trace file to identify and extract differential invariants (DE invariants) and coincidence invariants between consecutive execution sequences (baskets). It cleans the input data, splits logs into baskets, computes frequent itemsets, and writes detected invariants to 'DEInv.txt'. The main tas... | def readInputTrace():
global InputTrace,C, classes, numofclass, Var_names ,s, Lines, lines, baskets, newbasket,VN
f= open('DEInv.txt', 'w').close()
lines = open(InputTrace).read().splitlines()
#### removing empty members from list############################
lines= [x for x in lines if x]
#print (lines)
... |
def initialize_decision_vars(Rover):
# set minimum obstacel distance to the minimum of the array if the array isn't empty
# otherwise set it to 10
Rover.min_obs_dist = Rover.obs_dists.min()/Rover.dst if len(Rover.obs_dists) >0 else 10
# set rover stop distacne to Rover.min_stop_dist + d(t) at t = Rove... | The code implements a decision-making algorithm for a rover's autonomous navigation, adjusting movement (throttle/brake/steer) based on perception data like navigable terrain ratios, obstacle distances, and sample detection. It handles three modes: 'forward' (path-following with obstacle avoidance), 'stop' (pausing and... | def decision_step(Rover):
# Implement conditionals to decide what to do given perception data
# Here you're all set up with some basic functionality but you'll need to
# improve on this decision tree to do a good job of navigating autonomously!
# Example:
# Check if we have vision data to make deci... |
def load_training_data():
document_url = "http://frontend/jsonbox/documents/?limit=0"
annotation_url = "http://frontend/jsonbox/annotations/?sort=_createdOn&limit=0"
documents_data = requests.get(document_url).json()
annotations_data = requests.get(annotation_url).json()
annotation_map = defaultdi... | The code trains a spaCy model and a random forest classifier using provided training data. It saves the spaCy model to disk and serializes the random forest classifier as a pickle file. The function takes a model name and iteration count, processes data, trains both models, and stores them in a specified directory with... | def train_model(model_name, iterations):
model_path = f'{MODEL_DIR}/{model_name}'
print(f'Training {model_name}...')
training_data = load_training_data()
model = train_spacy(training_data, iterations=iterations)
classifier = train_forest(training_data, model)
model.meta["name"] = model_name
... |
def initialize(self, data):
# Siyi's Part: Initialize the mean, the variance and the weight for each cluster
# Comment the following code and implement a better initialization algorithm
k = self.n_components
n_samples = data.shape[0]
if self.init_params == 'kmeans':
r... | This code implements the Expectation-Maximization (EM) algorithm for a Gaussian Mixture Model (GMM). It iteratively computes likelihoods, updates posterior probabilities, and re-estimates parameters (means, covariances, weights) until convergence. The algorithm stops when the change in log-likelihood falls below a thre... | def fit(self, data):
self.start_time = time()
k = self.n_components
n_samples = data.shape[0]
if len(data) < k:
print('Number of cluster exceeds size of data')
return
self.initialize(data)
# posterior: P(theta | X) likelihood: P(X | theta)
... |
def _read(self, register, n_bytes):
return self._read_reg(register, n_bytes)
def _write(self, register, data):
self._write_reg(register, data)
def _io_update(self):
"""
Toggle IO update pin, thereby latching register values to dds core.
:return:
"""
logger.info("I... | This function configures a PLL (Phase-Locked Loop) by updating the CFR3 register with parameters like enable status, multiplier, VCO selection, charge pump current, and input divider bypass. It reads the register, modifies specific bytes based on inputs, writes the updated data back, and triggers I/O updates to apply c... | def set_pll(self, pll_enable, pll_multiplier, vco_sel=7, ch_pump_current=7, input_div_bypass=True):
logger.info("Set_pll: PLL enable {0}, mult {1}, vco_sel {2}, "
"ch_pump_current {3}, input_dev_bypass {4}".format(pll_enable, pll_multiplier, vco_sel,
... |
def setup_gpio(self):
"""
Setup gpio pins input/output
:return:
"""
logger.info("Setting up GPIO pins")
gpio.setmode(gpio.BOARD)
gpio.setup(self.pins["SCLK"], gpio.OUT)
gpio.setup(self.pins["SDO"], gpio.OUT)
gpio.setup(self.pins["SDI"], gpio.IN)
... | This code initializes a Direct Digital Synthesizer (DDS) module by configuring GPIO pins, setting system clock and output frequency parameters, initializing SPI communication, and performing hardware reset and configuration steps to generate a specified output frequency (150 MHz by default). | def __init__(self, sys_clk=1e9, f_out=150e6):
self.pins = {"SCLK": 40,
"SDO": 38,
"SDI": 36,
"IO_UPDATE": 7,
"IO_RESET": 11,
"RAM_SWP_OVR": 13,
"EXT_PWR_DOWN": 15,
"... |
def read_txt(path: str) -> list:
rules = re.split('\n+', open(path, 'r')\
.read()\
.replace(' ', '')\
.replace('\t', ''))
rules = [r for r in rules if r]
return rules
def parse_first_line(line: Queue):
vars = set()
assert line.pop() == '... | The code reads a file, parses its lines into structured data, and returns parsed results alongside construct keys. It reads the file content, validates line count, extracts global variables from the first line, processes subsequent lines to build a list of parsed entries, and returns this list with the keys from the `C... | def parse_file(file_name: str) -> (list, list):
global VARS, CONSTRUCTS, TERMS
rules = read_txt(file_name)
res = []
assert len(rules) > 1, INCORRECT_SYNTAX_ERROR
VARS = parse_first_line(Queue(rules[0]))
for rule in rules[1:]:
p_l = parse_line(Queue(rule))
if p_l:
res.... |
def read_and_normalize_train_data(path):
train_data, train_target= load_train(path)
print('Convert to numpy...')
train_data = np.array(train_data, dtype=np.uint8)
train_target = np.array(train_target, dtype=np.uint8)
print('Reshape...')
train_data = train_data.transpose((0, 1, 2, 3))
... | The code trains a hybrid VGG-MoblieNet model on a dataset, applying data augmentation (shifts, zoom) to enhance generalization. It compiles the model with Adam optimizer, trains for 256 epochs using augmented batches, saves best weights via checkpointing, logs training metrics to CSV, and evaluates validation performan... | def train_model(path_to_train_dataset):
batch_size = 64
nb_epoch =256
X_train, Y_train = read_and_normalize_train_data(path_to_train_dataset)
X_valid, Y_valid = read_and_normalize_valid_data(path_to_train_dataset)
#Data augmentation
datagen = ImageDataGenerator(
wid... |
def update_height(node):
node.height = max(height(node.left), height(node.right)) + 1
def height(node):
if node is None:
return -1 # define as -1 so you don't have to do cas anaysis on whether your children exist or not
else:
return node.height
def left_rotate(self, x):
"""
o... | The code rebalances an AVL tree by checking height differences between subtrees. It performs left or right rotations on nodes to maintain balance, handling both right-heavy and left-heavy cases. If a node's right subtree is taller by ≥2, it rotates left (or right then left) to fix. Similarly, for left-heavy cases, it r... | def rebalance(self, x):
"""
1. it's all about case analysis, take advantage of symmetric nature of tree operation.
2. We need to rebalance all the way up to the root.
"""
while x is not None:
update_height(x)
if height(x.right) >= height(x.left) + 2: # f... |
def predict_output_neural(features, weights_11, weights_12, weights_13, weight_ouput, bias_11, bias_12, bias_13, bias_output):
"""
Determine the prediction of the output
"""
layer1_result = predict_hidden_layer(features, weights_11, weights_12, weights_13, bias_11, bias_12, bias_13)
#print (laye... | This function trains a multi-layer neural network using gradient descent to minimize prediction errors between input features and target outputs. It iteratively adjusts weights and biases over 1000 epochs, calculates gradients via backpropagation, and updates parameters to improve accuracy. Initial and final accuracy a... | def train_multiple_neurals(features, targets, weights_11, weights_12, weights_13, weight_ouput, bias_11, bias_12, bias_13, bias_output):
"""
function of training multiple neural (ajust weights and bias in function of features and targets)
This function is not generic or optimized and aims to underst... |
def choose_batch(self, input, output, index):
x = index*self.batchsize
input_batch = input[x:x+self.batchsize]
output_batch = output[x:x+self.batchsize]
return input_batch, output_batch
def feed_forward(self, input, weights, biases):
z = []
activations = []
activa... | The main task of the code is to optimize a neural network's weights and biases through iterative training using batch processing and back-propagation. It performs multiple epochs of training, where each epoch processes data in batches, computes forward passes, evaluates cost, calculates gradients via back-propagation, ... | def optimize(self):
print("Optimizing...")
weights = self.weights
biases = self.biases
trials = int(len(self.input) / self.batchsize)
for i in range(self.epochs):
index = 0
for j in range(trials):
input, output = self.choose_batch(self.inp... |
def preprocessing(dendogram, distanceMetrics, data):
jumlah_data = len(data)
# make empty data
for i in range(0,jumlah_data):
dendogram.append(dict())
distanceMetrics.append([])
for j in range(0, jumlah_data):
distanceMetrics[i].append(0)
# initiate distance... | This function performs agglomerative hierarchical clustering on input data using specified linkage (mode) to iteratively merge closest clusters, updating a dendrogram and distance matrix until n_cluster clusters remain. It returns the final cluster assignments derived from the dendrogram structure. | def agglomerative(data, mode, n_cluster):
dendogram = []
distanceMetrics = []
preprocessing(dendogram, distanceMetrics, data)
# Main Agglomerative iteration n-1
for iteration in range(1,len(data)):
# print(distanceMetrics)
# print("=======================")
i, j = search... |
def kMeans(data):
# Initialize centroid
c1, c2, c3 = random.sample(range(0, len(data) - 1), 3)
centroid = data[c1], data[c2], data[c3]
cluster = [-1] * len(data)
error = (99999, 99999, 99999)
epoch = 0
while not stopIter(error, epoch):
for i in range(len(data)):
cluste... | The code performs k-means clustering on the Iris dataset, evaluates clustering quality using Fowlkes-Mallows score and Silhouette coefficient, and visualizes cluster distributions via a pairplot with seaborn. | def main():
# Read iris dataset
iris = load_iris()
data = iris.data
pred = kMeans(data)
fm = fowlkesMallows(iris.target, pred)
sc = silhuoette(data, pred)
print("Prediction:", pred)
print("Folkes-Mallows Score:", fm)
print("Silhouette Coefficient:", sc)
sns.set(style="white", co... |
def agglomerative(data, mode, n_cluster):
dendogram = []
distanceMetrics = []
preprocessing(dendogram, distanceMetrics, data)
# Main Agglomerative iteration n-1
for iteration in range(1,len(data)):
# print(distanceMetrics)
# print("=======================")
i, j = search... | The main task of the code is to perform agglomerative clustering on the Iris dataset using average linkage, evaluate the clustering with the Fowlkes-Mallows score and Silhouette coefficient, and visualize the results in a 3D scatter plot colored by cluster assignments. | def main():
iris = load_iris()
data = iris.data
print(data)
prediction = agglomerative(data, AVERAGE_GROUP_LINKAGE, 3)
fm = fowlkesMallows(iris.target, prediction)
sc = silhuoette(data, prediction)
print("Prediction:", prediction)
print("Folkes-Mallows Score:", fm)
print("Silhouette ... |
def go_up(self):
if self.snake.direction != "down":
self.snake.direction = "up"
def go_right(self):
if self.snake.direction != "left":
self.snake.direction = "right"
def go_down(self):
if self.snake.direction != "up":
self.snake.direction = "down"
def go_left(... | The code defines a `step` method that processes an action by moving an agent in a specified direction (up, right, down, left), executes the game logic, retrieves the current state, and returns the state, reward, termination status, and additional info. Its main task is to handle environment interaction in a reinforceme... | def step(self, action):
if action == 0:
self.go_up()
if action == 1:
self.go_right()
if action == 2:
self.go_down()
if action == 3:
self.go_left()
self.run_game()
state = self.get_state()
return state, self.reward, s... |
def item_summary():
item_list = []
with open(item_file_name, 'r+') as my_file:
reader = csv.DictReader(my_file)
for row in reader:
item_list.append([row['Item_Number'], row['Item_Name'], row['Item_Cost']])
print(tabulate(item_list, headers=["Number", "Name", "Cost"], tablefmt='fa... | The main task of the code is to handle a purchase process by validating user inputs for employee discount numbers and item numbers, checking their existence in the system, applying discounts, and allowing multiple purchases until the user quits. It ensures numeric inputs, verifies data existence, and manages purchase c... | def purchase_page():
# Variables
# Logic Starts:
print("Type QUIT to return to the menu...\n")
valid_item_number = False
valid_employee_number = False
continue_purchase = False
item_summary()
while not continue_purchase:
# Check if user wants to quit purchase
print(" ... |
def process_events(self, events):
for event in events:
self.manager.process_events(event)
if event.type == pygame.USEREVENT:
if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
new_event = pygame.event.Event(pygame.USEREVENT,
... | The code processes a single frame by handling input events, updating the simulation and manager state with the given time delta, rendering the simulation, and drawing the user interface. It orchestrates game loop tasks including event processing, state updates, and visual rendering. | def process_frame(self, time_delta, events):
self.process_events(events)
self.manager.update(time_delta)
self.update_simulation(time_delta)
self.draw_simulation()
self.manager.draw_ui(pygame.display.get_surface()) |
def __reset(self):
self.field = [[" "," "," "],[" "," "," "],[" "," "," "]]
self.move_list = []
self.player1 = ""
self.player2 = ""
self.move_counter = 0
self.bot = 0
self.bot_first_or_second = 0
def __who_starts_first_pve(self):
while True:
ws... | This function initializes and manages a Player vs. AI (PVE) Tic-Tac-Toe game. It resets the game state, sets up the AI bot, determines starting player, and enters a loop to handle turns, update the board, check for wins, and declare results (win/loss/tie) until the game concludes. | def start_game_pve(self):
self.__reset()
self.bot = TTTBot.TTTBot()
self.__who_starts_first_pve()
self.bot.first_or_second = self.bot_first_or_second
self.bot.field = self.field
self.bot.move_list = self.move_list
if self.bot_first_or_second == 2:
self... |
def __reset(self):
self.field = [[" "," "," "," "," "],[" "," "," "," "," "],[" "," "," "," "," "],[" "," "," "," "," "],[" "," "," "," "," "]]
self.move_list = []
self.player1 = ""
self.player2 = ""
self.move_counter = 0
self.bot = 0
self.bot_first_or_second = 0
... | This function initializes a Player vs. Bot Tic-Tac-Toe game, sets up the bot's parameters, and manages the game loop. It alternates turns, updates the game state, checks for wins/ties, and displays results. The bot's role (first or second) is determined, and the loop continues until a win or tie occurs, with appropriat... | def start_game_pve(self):
self.__reset()
self.bot = TTTBot.TTTBot()
self.__who_starts_first_pve()
self.bot.first_or_second = self.bot_first_or_second
self.bot.field = self.field
self.bot.move_list = self.move_list
if self.bot_first_or_second == 2:
self... |
def squareUnderAttack(self, x, y):
self.whiteMoves = not self.whiteMoves
opponentMoves = self.getPossibleMoves()
self.whiteMoves = not self.whiteMoves
for move in opponentMoves:
if move.endR == x and move.endC == y:
return True
return False
def getKing... | The function `getCastleMoves` checks if a square is under attack and, if not, generates valid castling moves for the king on the king's side or queen's side based on current castling rights and player turn, appending these moves to the `moves` list for the ally color. | def getCastleMoves(self, x, y, moves, allyColor):
if self.squareUnderAttack(x, y):
return
if (self.whiteMoves and self.currentCastling.wks) or (not self.whiteMoves and self.currentCastling.bks):
self.getKingSideCastle(x, y, moves, allyColor)
if (self.whiteMoves and self.c... |
def pinsAndChecks(self):
pins = []
checks = []
inCheck = False
if self.whiteMoves:
allyColor = 'w'
enemyColor = 'b'
kingRow = self.wKing[0]
kingCol = self.wKing[1]
else:
allyColor = 'b'
enemyColor = 'w'
... | This function generates valid moves for the current player, considering check, pins, and castling. It determines the king's position, checks if the king is in check, and filters moves to ensure the king is not left in check. If in check, it handles blocking or capturing the checking piece, or moves the king. If not in ... | def getValidMoves(self):
moves = []
self.inCheck, self.pins, self.checks = self.pinsAndChecks()
if self.whiteMoves:
kingRow = self.wKing[0]
kingCol = self.wKing[1]
else:
kingRow = self.bKing[0]
kingCol = self.bKing[1]
if self.inChec... |
def get_relevance(terms, metric):
tf = get_tf(terms)
idf = get_idf(terms)
tdf = get_tdf(terms)
tf_tdf = {}
tf_idf = {}
if metric == "tf":
return tf
elif metric == "idf":
return idf
elif metric == "tdf":
return tdf
elif metric == "tf_tdf":
for term in ... | The code computes and returns four metrics related to domain analysis: target domain relevance, divergence weight (dw), likelihood ratio (llr), and background likelihood ratio (lor_bg). It uses input domains and a metric parameter to calculate these values, leveraging helper functions for relevance, divergence, and lik... | def get_metrics(target_domain, contrastive_domain, metric):
target_relevance = get_relevance(target_domain, metric)
alpha = 0.5
candidates = set([item for sublist in target_domain for item in sublist])
dw = get_dw(target_domain, contrastive_domain, candidates, alpha)
llr = get_llr(target_domain, c... |
def get_tf(terms, norm=0):
flat_terms = [item for sublist in terms for item in sublist]
tf = Counter(flat_terms)
max_freq = Counter(flat_terms).most_common(1)[0][1]
for t in tf:
if norm:
tf[t] = (tf[t] / max_freq)
else:
pass
return tf
def get_relevance(terms,... | The function `label_concepts` assigns labels to terms in the `target_domain` by comparing their relevance in `background_domain` and `contrastive_domain`, using metrics like term frequency (TF) and shared concepts. It prioritizes terms based on: 1) higher background relevance, 2) presence in shared concepts, or 3) TF >... | def label_concepts(target_domain, background_domain, contrastive_domain, method=0, metric="tf"):
label = {}
# get term frequency for last stage decision making
target_tf = get_tf(target_domain)
candidates = set([item for sublist in target_domain for item in sublist])
# get all relevant metrics
... |
def ask_question():
if len(Q_and_A) != 0:
question_and_answer = Q_and_A[0]
question = question_and_answer[0]
options = question_and_answer[1]
answer = question_and_answer[2]
random.shuffle(options)
option_number = 1
send_to_all(server_socket, "\nQ. " + str(q... | The code manages a multiplayer quiz game where players buzz in to answer shuffled questions. It waits for a buzzer press, notifies the player, and allows 10 seconds to answer. If unanswered, the player loses points; otherwise, the quiz proceeds. The process repeats until all questions are answered, with real-time updat... | def quiz():
current_player[0] = server_socket
random.shuffle(Q_and_A)
ask_question()
key_press = select.select(clients_list, [], [], 10)
if len(key_press[0]) > 0:
buzzer_pressed_by = key_press[0][0]
send_to_one(buzzer_pressed_by, "YOU PRESSED THE BUZZER")
... |
def loadLastTenTable(self):
#Loads table with last ten movies watched
sql = "SELECT * FROM log ORDER BY LOG_MOVIE_DATE desc LIMIT 0, 10" #Selects top 10 results from the table
cursor = self.dbConnection.cursor()
cursor.execute(sql)
myresult = cursor.fetchall()
cursor.clos... | The main task of the code is to initialize UI components when the application starts by loading recent entries into a table, displaying main log data, and updating statistics if there are historical entries. It retrieves entry counts and triggers a stats update only if entries exist, ensuring UI elements reflect curren... | def startup(self):
#Methods that need to run right when the UI opens
self.loadLastTenTable()
self.loadMainLogTable()
entriesCount = self.getAllTimeCount() #Probably could make this a one liner, but not sure how yet
if(entriesCount[0][0] != 0):
self.updateStats() |
def refreshLastTen(self):
#Refreshes the table of recently watched movies after a new entry is added or a change
self.LastTenTable.clearContents()
sql = "SELECT * FROM log ORDER BY LOG_MOVIE_DATE desc LIMIT 0, 10" #Selects top 10 results from the table
cursor = self.dbConnection.cursor(... | This function displays an add movie form when the AddMediaButton is pressed. If the form is successfully submitted, it updates the UI by refreshing the last ten entries, main log, and statistics. If canceled, it only closes the form without changes unless a new entry was added, triggering UI updates. | def displayAddMovieForm(self):
# Displays the Add Movie Form when the AddMediaButton is pressed
addForm = AddForm_Win(self)
if addForm.exec_():
print("Success!")
else:
print("Closing Add Form")
if(self.changed == True): #Only updates if an entry has ... |
def refreshLastTen(self):
#Refreshes the table of recently watched movies after a new entry is added or a change
self.LastTenTable.clearContents()
sql = "SELECT * FROM log ORDER BY LOG_MOVIE_DATE desc LIMIT 0, 10" #Selects top 10 results from the table
cursor = self.dbConnection.cursor(... | This method displays an edit window for the selected entry in a table, retrieves its data, and updates the UI if changes are saved. It checks for a selected row, extracts relevant fields, opens an edit form, and refreshes logs/stats upon successful edits. If no row is selected, it shows a warning message. | def displayEditWindow(self):
#Displays the Edit Window when the EditButton is pressed
if(len(self.MainLogTable.selectedItems()) > 0):
entryID = self.MainLogTable.item(self.MainLogTable.currentRow(), 0).text()
title = self.MainLogTable.item(self.MainLogTable.currentRow(), 1).text(... |
def getAllTimeCount(self):
#Gets the Count of all movies logged
sql = "SELECT COUNT(LOG_ID) FROM log"
cursor = self.dbConnection.cursor()
cursor.execute(sql)
myresult = cursor.fetchall()
cursor.close()
return myresult
def updateStats(self):
#Gets the main ... | This code deletes a selected entry from a table by executing an SQL DELETE query using the entry's ID, then removes the corresponding row from the UI table. It notifies the user of the deletion and updates statistics, last ten entries, and the main log if entries remain. If no row is selected, it prompts the user to ch... | def deleteEntry(self):
#Deletes a selected entry from the table
if(len(self.MainLogTable.selectedItems()) > 0):
entryID = self.MainLogTable.item(self.MainLogTable.currentRow(), 0).text()
sql = "DELETE FROM log WHERE LOG_ID = %s"
vals = [entryID]
cursor = s... |
def solve_custom_vigenere(ciphertext, min_key_size=1, max_key_size=12, a_is_zero=True):
best_keys = []
text_letters = [c for c in ciphertext.lower() if c in string.ascii_lowercase]
for key_length in range(min_key_size, max_key_size + 1):
# Try all possible key lengths
secret_key = [None] *... | The code decrypts a given ciphertext using a custom Vigenère cipher by iterating through possible secret keys in reverse order. It verifies each decryption by re-encrypting the result and checking if it matches the original ciphertext and contains meaningful English words. If valid, it prints the key and decrypted text... | def custom_main():
ciphertext = input("Enter the ciphertext to decrypt: ").strip()
for secret_key in reversed(solve_custom_vigenere(ciphertext)):
decrypted_text = custom_vigenere_decrypt(ciphertext, secret_key)
if ciphertext == custom_vigenere(decrypted_text, secret_key) and contains_custom_mea... |
def carve_files_tsk(self, out_folder, partition):
self.generate_dfxml_fiwalk()
print("Carving files using tsk_recover")
tsk_version_cmd = ["tsk_recover", "-V"]
tsk_version = subprocess.run(tsk_version_cmd, capture_output=True).stdout.decode("utf-8").strip()
if partition:
... | The main task of the code is to identify the appropriate filesystem from given partitions or stored data, then extract files using corresponding methods (TSK, UNHFS, or mounting) based on the detected filesystem type. It handles hybrid disk cases, skips unsupported formats, and returns success or error statuses. | def handle_file_extraction(self, out_folder, partition):
if partition:
filesystems = partition["filesystems"]
else:
filesystems = self.filesystems
if len(filesystems) == 1:
filesystem = filesystems[0]
elif len(filesystems) == 3 and sorted(filesystems)... |
def run_preliminary_tools(self):
self.disktype_txt = os.path.join(self.subdoc_dir, "disktype.txt")
disktype_cmd = ["disktype", self.image_path]
timestamp = str(datetime.datetime.now())
with open(self.disktype_txt, "w") as f:
disktype_result = subprocess.run(disktype_cmd, stdo... | The main task of the code is to process disk content by running preliminary tools, checking for video directories (VIDEO_TS/AUDIO_TS), executing Brunnhilde if no video is detected, and updating records via CSV and bagging. It returns status ("success", "flagged", or "skipped") and messages based on file analysis and pr... | def process_disk(self):
status = ""
message = ""
self.run_preliminary_tools()
status, message = self.characterize_and_extract_files()
if status == "skipped":
self.write_premis_csv()
return status, message
else:
potential_video = self.ch... |
def add_ability_with_id(name):
query = """
SELECT id from heroes
WHERE name = %s
"""
results = execute_query(query, (name,)).fetchone()[0]
print(results)
type_id = input('What is your super power? 1: Super Strength 2: Flying 3: Telekinesis 4: Telepathy: 5: Frost Brea... | The code creates a new villain character by collecting user input for the villain's name, backstory, and power origin. It inserts this data into a database as a villain (with is_villain=True), adds abilities, checks them, and deletes the original hero character. The main task is to generate and register a villain in th... | def create_main_villain(hero_name):
name = input('* Now at the lair of the "Order of the Villains" * Ah welcome to the order of the villains! What is your villain name?: ')
about = input('Welcome ' + name + '. Now tell me how you became a villain: ')
bio = input("One last question. How did you get your powe... |
def _process_event(self, event):
if event == 'FIX_WAIT':
if self._output == 'raw':
print('waiting for a fix')
elif self._output == 'parsed':
print('waiting for a fix (parsed)')
elif self._output == 'database':
self._logger.deb... | The main task of the code is to continuously monitor GPS data, detect fix status changes (lost/found), trigger corresponding events (FIX_LOST, FIX_FOUND, FIX_WAIT), and process GPS data when a valid fix is available. It maintains a loop to update GPS information, checks for fix stability, and ensures processing complet... | def _mainloop(self):
self._logger.debug('process: message="entering main processing loop"')
gps = adafruit_gps.GPS(self._uart)
gps.send_command(b'PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0')
gps.send_command(b'PMTK220,1000')
gps.send_command(b'PMTK605')
fix_lost = Fa... |
def _initialize_logger(self, args):
level = logging.DEBUG
if args.verbose:
level = logging.DEBUG
if args.quiet:
level = logging.ERROR
self._logger.setLevel(level)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(level)
format... | The main task of the code is to initialize a system's components by setting up logging, configurations, database, UART communication, and processing a SESSION_INITIALIZE event. It also optionally starts a background thread to track elapsed runtime if a maximum runtime is specified, ensuring the system is fully prepared... | def _initialize(self, args):
self._initialize_logger(args)
self._logger.debug('process: message="initializing"')
self._initialize_settings(args)
self._initialize_database(args)
self._process_event('SESSION_INITIALIZE')
self._initialize_uart(args)
if self._max_run... |
def _initialize(self, args):
self._initialize_logger(args)
self._logger.debug('process: message="initializing"')
self._initialize_settings(args)
self._initialize_database(args)
self._process_event('SESSION_INITIALIZE')
self._initialize_uart(args)
if self._max_run... | The code's main task is to start an application by initializing it with provided arguments and entering a main loop. It handles keyboard interrupts to exit gracefully with a status code of -1. | def start(self, args):
try:
self._initialize(args)
self._mainloop()
except KeyboardInterrupt:
self._exit(-1) |
def get_siamese_data(train_dir):
image_paths_dict = util.get_data_arrays(train_dir)
siamese_data = get_siamese_data_format(image_paths_dict)
return siamese_data
def parse_siamese_data(siamese_data):
train_data_left = list()
train_data_right = list()
target_list = list()
print("Siamese Test d... | The main task of the code is to train a Siamese neural network model on a dataset of paired images, evaluate its binary classification performance, save the trained model, and visualize training accuracy/loss curves. The model uses ResNet architecture, is compiled with Adam optimizer, and trains for 50 epochs with vali... | def main():
train_dir = util.train_dir
siamese_data = get_siamese_data(train_dir)
train_data_left, train_data_right, target_list = parse_siamese_data(siamese_data)
siamese_model = get_siamese_model()
siamese_model.compile(optimizer=Adam(lr=0.0006), loss="binary_crossentropy", metrics=['accuracy'])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.