dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def BTCETHpercent():
btc = krakenBTCPrice()
eth = krakenEthPrice()
btceth = eth/btc
kbtceth = krakenBTCETHPrice()
return (btceth - kbtceth)/kbtceth*100
def ordersClosed():
global inPosition
if not mainTXID: #if mainTXID is empty
return True
else:
while True:
t... | The code executes a trade (buy or sell) based on the calculated percentage (BTCETHpercent) relative to predefined thresholds (negPercent, posPercent) and checks if orders are closed before proceeding. | def makeTrade(volume,price,calcprice):
percent = BTCETHpercent()
if percent <= negPercent and ordersClosed():
print('Making trade...')
make_trade(_SELL_,volume,price,calcprice)
elif percent >= posPercent and ordersClosed():
print('Making trade...')
make_trade(_BUY_,volume,pri... |
def printTXIDs():
if mainTXID:
print("Main: " + str(mainTXID))
if closeTXID:
print("Close: " + str(closeTXID))
def makeTrade(volume,price,calcprice):
percent = BTCETHpercent()
if percent <= negPercent and ordersClosed():
print('Making trade...')
make_trade(_SELL_,volume,p... | The main task of the code is to continuously monitor and execute trades on Kraken, adjusting trade volume and direction based on BTC/ETH price differences. It maintains a loop to check order status, triggers stoploss mechanisms if trades remain open beyond a set time, and resets counters upon successful closures, ensur... | def main():
global _TRADE_VOLUME_
_TRADE_VOLUME_ = .25 #(availablecapital/krakenEthPrice())
while True:
printTXIDs()
#balanceCheck("XETH")
makeTrade(_TRADE_VOLUME_,round(krakenBTCETHPrice(),5),round(krakencalcprice(),5))
print("BTC/ETH diff: " + str(BTCETHpercent()))
... |
def _get_current_nucleation_rate(self) -> float:
self._verify_string_variable_setting('nucleation_rate_mode',self.nucleation_rate_mode,nucleation_rate_modes)
if self.nucleation_rate_mode == 'constant': return self.nucleation_rate
else: return self.nucleation_rate
def _get_area_coverage(self) -> float:
return... | The function generates new crystals using a Poisson distribution based on the current nucleation rate. It checks constraints: maximum crystal count and full area coverage. If valid, it assigns random positions and orientations, then creates new crystals. Early exits occur if a snapshot was taken and nucleation should s... | def _nucleate_crystals(self):
if self._snapshot_taken and self.stop_nucleation_after_snapshot: return
new_crystals = self._RNG.poisson(self._get_current_nucleation_rate())
for new_crystal in range(new_crystals):
if self._current_crystals >= self.maximum_crystals: return
if self._get_area_coverage() == 1.0... |
def _get_area_coverage(self) -> float:
return (self._total_crystal_area/(self.height*self.width))
def _get_growth_rate(self, crystal: int) -> float:
self._verify_string_variable_setting('growth_rate_mode',self.growth_rate_mode,growth_rate_modes)
if len(self._crystals[crystal].candidate_points) == 0: return 0
... | The main task of the code is to grow existing crystals by incrementing their radii based on growth rates and iteratively updating candidate points until no further changes occur. It checks if crystals can expand by evaluating candidate points, marking them as finished when their points stabilize, ensuring all crystals ... | def _grow_crystals(self):
if self._get_area_coverage() == 1.0: return
if self._current_crystals == 0: return
finished_updating_points = np.zeros((self._current_crystals+1))
finished_updating_points[0] = 1
for i in range(1,self._current_crystals+1):
self._crystals[i].radii.append(self._crystals[i].radii... |
def _reset_simulation_parameters(self):
self._current_time = 0
self._image = np.zeros((self.height,self.width),dtype=int)
self._crystals = list([None]) # this allows the list index to match the image label
self._current_crystals = 0
self._primary_orientation = round(self._RNG.random(),self.orientation_preci... | This function performs a single crystal growth simulation using the simulator's current configuration. It either uses pre-imported nucleation data or generates it dynamically, advancing through nucleation, growth, and snapshot steps until termination criteria (e.g., full coverage, snapshot conditions) are met. It handl... | def run_simulation(self, use_imported_data: bool = False):
"""
Using the existing configuration of the simulator, perform a single crystal growth simulation.
Parameters
----------
use_imported_data : bool , default False
whether to use nucleation data that has been imported with import_nucleation_data(.... |
def create_folder(client_id, folder_name, event_time):
path = os.path.join(client_id, folder_name)
os.makedirs(path, exist_ok=True)
create_event = Event(folder_name, event_time, "createFolder")
clients_events[client_id].append(create_event)
def create_file(client_source, client_id, file_name, length, ev... | This function processes incoming client events by reading commands from a socket, handling "createFolder", "create", and "delete" operations. It decodes data, extracts parameters like filenames, lengths, and timestamps, then triggers corresponding actions (e.g., creating folders/files or deleting files) using the clien... | def check_for_new_events(client_socket, client_id):
with client_socket.makefile('rb') as client_file:
data = client_file.readline().strip().decode()
# get operation.
while data != '':
if data == "createFolder":
folder_name = client_file.readline().strip().decode()... |
def create_folder(folder_name):
path = os.path.join(folder_path, folder_name)
os.makedirs(path, exist_ok=True)
def create_file(server_source, file_name, length):
# new file path
path = os.path.join(folder_path, file_name)
# in case file's folder doesn't exist, create it
os.makedirs(os.path.dir... | This function reads event data from a server socket, processes each event (create, delete, or folder creation) by applying corresponding actions to the client's file system, and updates the last update timestamp. It decodes event actions and paths, creates Event objects, and handles file/folder operations based on the ... | def get_events_from_server(server_socket):
with server_socket.makefile('rb') as server_file:
# current event action
action = server_file.readline().strip().decode()
# get all new events and implement them in the client folder
while action != '':
# file path
... |
def display_menu():
# Function to display menu
print("-----MENU-----")
print(f"1. Midpoint Ellipse Algorithm")
print(f"2. Polar Ellipse")
print(f"3. Non-Polar Ellipse")
print(f"0. Exit")
return int(input("Enter Choice: "))
def get_input():
# Function to get input from user
xc, yc =... | The main task of the code is to implement a menu-driven program that allows users to select an ellipse drawing algorithm (Mid-point, Polar, or Non-Polar), input ellipse parameters (xc, yc, rx, ry), and display the corresponding ellipse. It handles input validation, loops until exit (choice 0), and uses a dictionary to ... | def main():
choice = 1
titleList = {
1: "Mid point ellipse drawing algorithm",
2: "Polar ellipse drawing algorithm",
3: "Non-Polar ellipse drawing algorithm",
}
while choice != 0:
choice = display_menu()
if choice == 1 or choice == 2 or choice == 3:
... |
def get_translate_points(vertices: list) -> list:
tx = int(input("Enter X translation: "))
ty = int(input("Enter Y translation: "))
points = []
for x, y in vertices:
points.append((x + tx, y + ty))
return points
def get_rotated_points(vertices: list) -> list:
theta = (pi / 180) *... | The function `display_window` applies geometric transformations (translation, rotation, scaling, reflection) to a set of vertices based on user input. It uses OpenGL via GLUT to create a window, render the transformed vertices, and display the result. The choice parameter determines the transformation type, with sub-op... | def display_window(vertices: list, choice: int, title: str) -> None:
# Get the vertices of transformed object
if choice == 1:
points = get_translate_points(vertices)
elif choice == 2:
while True:
print("1. Rotated about origin")
print("2. Rotated about an arbitary po... |
def display_menu():
# Function to display menu
print("-----MENU-----")
print(f"1. Bresenham's Algorithm")
print(f"0. Exit")
return int(input("Enter Choice: "))
def get_input():
# Function to get input from user
x1, y1 = map(int, input("Enter initial coordinate seperated by space: (Eg. '20 ... | The main task of the code is to create a loop that repeatedly displays a menu, allowing the user to input coordinates for a window display (option 1) or exit the program (option 0). It validates user choices, handles invalid inputs, and terminates when the user selects "0". | def main():
choice = 1
while choice != 0:
choice = display_menu()
if choice == 1:
# Checks if it's a valid input (i.e. present in dictionary)
x1, y1, x2, y2 = get_input()
display_window(x1, y1, x2, y2)
elif choice == 0:
# To handle exit fro... |
def display_menu() -> int:
print("-----MENU-----")
print(f"1. Translation")
print(f"2. Rotation")
print(f"3. Scale")
print(f"4. Reflection")
print(f"0. Exit")
return int(input("Enter Choice: "))
def get_input() -> list:
while True:
try:
x1, y1 = map(int, input("Enter... | The code defines a menu-driven program to perform geometric transformations (Translation, Rotation, Scale, Reflection) on input vertices. It repeatedly displays a menu, accepts user choices, validates inputs, and visualizes the selected transformation. The loop exits when the user selects "0", with error handling for i... | def main():
choice = 1
titleList = {
1: "Translation",
2: "Rotation",
3: "Scale",
4: "Reflection"
}
while choice != 0:
choice = display_menu()
if choice in titleList.keys():
# Checks if it's a valid input
vertices = get_input()
... |
def init(prs):
prs['dataset_type'] = prs.get('dataset_type', CONFIG['dataset_type'])
# Params
prs['nb_inputs'] = prs.get('nb_inputs', CONFIG['nb_inputs'])
prs['nb_hidden'] = prs.get('nb_hidden', CONFIG['nb_hidden'])
prs['nb_hidden2'] = prs.get('nb_hidden2', CONFIG['nb_hidden2'])
prs['nb_outputs'... | The function `run_and_time` executes and benchmarks different sparse neural network training methods (e.g., S3GD, LocalZO) on GPU, initializing parameters, training models, recording loss, forward/backward timing/memory, and classification accuracy, while handling surrogate gradient functions and data setup. | def run_and_time(prs=None, method='s3gd'):
prs = {} if prs is None else prs
prs['set_random_state'] = True
if torch.cuda.is_available():
prs['device'] = 'cuda'
assert prs['device'] == 'cuda'
if method == 's3gd': # Sparse Gradient
prs['SNN_function'] = SparseSNNLayer.apply
elif ... |
def make_tempfile(self, code):
self._tempdir = tempfile.TemporaryDirectory()
self._tempfile = self._tempdir.name + '/tempfile'
file = open(self._tempfile, 'w+b')
file.write(code.encode('utf-8'))
file.close()
def executable(self):
if not self.executables:
retu... | The main task of the code is to execute a command for formatting code, using a temporary file if enabled, and return the formatted result or the temporary file. It constructs a command from an executable path, substitutes variables, runs the process, captures output, and handles errors by raising exceptions or returnin... | def format(self, code):
temporary_file = None
if (self.use_tempfile == True):
self.make_tempfile(code)
executable = self.executable()
if executable is None:
sublime.error_message('Could not find executable.')
raise Exception('Could not find executab... |
def get_syntax(self):
pattern = re.compile(r'Packages/.*/(.+?).(?=tmLanguage|sublime-syntax)')
matches = pattern.search(self.view.settings().get('syntax'))
found = ''
if matches and len(matches.groups()) > 0:
found = matches.groups()[0]
return found.lower()
def get_... | The main task of the code is to format code based on its syntax. It retrieves the current syntax, obtains the corresponding formatter, checks if it's supported, and applies formatting if valid. If unsupported, it displays an error message. | def run(self, edit):
syntax = self.get_syntax()
formatter = self.get_formatter(syntax)
if (formatter is None):
return sublime.error_message('Syntax "%s" is not supported in Code Formatter.' % syntax)
self.format(edit, formatter, syntax) |
def intro():
# This function introduces the rules of the game Tic Tac Toe
print("Hello! Welcome to Mridul's Tic Tac Toe game!")
print("\n")
print("Rules: Player 1 and player 2, represented by X and O, take turns "
"marking the spaces in a 3*3 grid. The player who succeeds in placing "
"t... | The main task of the code is to initialize a game by setting up a board, retrieving player symbols, and checking if the board is full, likely part of a turn-based game like Tic-Tac-Toe. It calls functions to create the game grid, display it, assign symbols to players, and verify board completion. | def main():
# The main function
introduction = intro()
board = create_grid()
pretty = printPretty(board)
symbol_1, symbol_2 = sym()
full = isFull(board, symbol_1, symbol_2) |
def parse_int(value, default):
try:
return int(value)
except (TypeError, ValueError):
return default
def parse_float(value, default):
try:
return float(value)
except (TypeError, ValueError):
return default
def json_response(data):
return Response(json.dumps(data),... | This code handles a package submission by extracting uploaded files, updating metadata, and managing storage. It processes request parameters, validates file uploads, extracts ZIP content, updates package fields, and returns a JSON response indicating success or errors. | def studio_submit(self, request, _suffix):
self.display_name = request.params["display_name"]
self.width = parse_int(request.params["width"], None)
self.height = parse_int(request.params["height"], None)
self.has_score = request.params["has_score"] == "1"
self.weight = parse_floa... |
def bch_encode(data, g):
return gf_mul(data, g)
def bch_decode(c, g):
syndrome = gf_div(c, g)
if not weight(syndrome):
return c
cnt_rot = 0
recd = c
stp = 0
while weight(syndrome) > t:
## print('ada sindrom %d , loop ke %d'%(weight(syndrome),(stp+1)))
recd = l_... | The code encodes two data sets using a BCH error-correcting code, compares their parity bits to detect discrepancies, corrects errors in one codeword if within the code's correction limit (t), decodes both corrected and original codewords, and stores results. If errors exceed t, it increments a global counter. The task... | def main(data, data2, z):
global deleteblok
seed()
# g = "1101111100110100001110101101100111" # g(x) BCH(63,30) t=6 m=6 k=30
g = "11001011011110101000100111" # BCH (31,6) m=5 k=6 t=7
#g = "10010110111" # generating polynomial g(x), of the (31,21) BCH code x^10 + x^9 + x^8 + x^6 + x^5 + x^3 + 1 t=... |
def update_variables(url_name, current_cycle, analysis, phrases):
global article_content_list
global cycle
global analysis_type
global get_phrases
analysis_type = analysis
cycle = current_cycle
article_content_list = webScrape.get_article_content_list(url_name)
get_phrases = int(phrase... | The main task of the code is to process an HTTP request by extracting parameters (name, cycle, analysis, phrases), validate their presence, update variables, generate an analysis object, scrape web content, and return analytics results. If parameters are missing, it returns a 400 error. | def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
name = req.params.get('name')
cycle = req.params.get('cycle')
analysis = req.params.get("analysis")
phrases = req.params.get("phrases")
if not name:
try:
... |
def runIF(filename, X, gt, param_r, param_mat, param_sk):
global withGT
labelFile_r = filename + "_" + str(param_r[0][1]) + "_" + str(param_r[1][1]) + "_" + str(param_r[2][1]) + "_" + str(param_r[3][1])
labelFile_mat = filename + "_" + str(param_mat[0][1]) + "_" + str(param_mat[1][1]) + "_" + str(param... | The function `get_guided_route` optimizes clustering parameters by iteratively testing different configurations for tools (Sklearn, Matlab, etc.) to maximize ARI and F1 scores. It evaluates parameter variations, compares results with a baseline, and selects the best-performing settings. If no tools are provided, it run... | def get_guided_route(X, gt, filename, parameters_r_copy,parameters_mat_copy, parameters_sk_copy, tools):
if tools == []:
ari_score, f1_score_r, f1_score_mat, f1_score_sk = runIF(filename, X, gt, parameters_r_copy, parameters_mat_copy, parameters_sk_copy)
return ari_score, f1_score_r, f1_score_mat, f... |
def IF_LOF_ContFactor(X):
labels = []
num_label = 0
for i in range(5):
clustering = IsolationForest().fit(X)
l = clustering.predict(X)
num_label = len(l)
l = [0 if x == 1 else 1 for x in l]
labels.append(l)
_, counts_if = np.unique(labels, return_counts=True)... | The function processes datasets (from .mat or .csv) to evaluate and optimize Isolation Forest and LOF anomaly detection parameters in R, Matlab, and Scikit-Learn. It loads data, checks for NaN values, adjusts parameters based on contamination factors, runs default and optimized configurations, and outputs ARI scores, F... | def isolationforest(filename, parameters_r, parameters_mat, parameters_sk):
folderpath = datasetFolderDir
global withGT
if os.path.exists(folderpath+filename+".mat") == 1:
try:
df = loadmat(folderpath+filename+".mat")
except NotImplementedError:
df = mat73.loadma... |
def IF_LOF_ContFactor(X):
labels = []
num_label = 0
for i in range(5):
clustering = IsolationForest().fit(X)
l = clustering.predict(X)
num_label = len(l)
l = [0 if x == 1 else 1 for x in l]
labels.append(l)
_, counts_if = np.unique(labels, return_counts=True)... | The main task of the code is to evaluate and compare clustering algorithms (Matlab and Scikit-Learn) on a dataset, using default settings, an uninformed parameter search, and an informed parameter search (guided by ground truth labels). It loads data from .mat or .csv files, adjusts parameters based on contamination fa... | def ee(filename, parameters_mat, parameters_sk):
folderpath = datasetFolderDir
global withGT
if os.path.exists(folderpath+filename+".mat") == 1:
try:
df = loadmat(folderpath+filename+".mat")
except NotImplementedError:
df = mat73.loadmat(folderpath+filename+".mat... |
def cleaned_categories(categories):
"""
Returns a string of categories, either from the provided list or by generating random categories.
"""
if categories is None:
categories = random_categories()
else:
categories = ", ".join(categories)
return categories
def generate_story(cate... | The main task of the code is to generate a story based on input categories, parse it into sections, create images for each section, and compile the story with images into HTML. It optionally uploads generated images to a Google Cloud bucket using provided credentials. | def story(openai_api_key, categories=None, google_id=None, google_bucket=None):
"""
Generates a story based on categories, parses it into sections, generates images for each section, and converts the story and images into HTML.
"""
openai.api_key = openai_api_key
categories = cleaned_categories(cate... |
def player_turn(self):
if Who_Starts.computer:
self.role_label['text']="Your turn!"
else:
if self.turn:
self.role_label['text']="Player turn:\n'X'"
else:
self.role_label['text']="Player turn:\n'0'"
def win(self):
if self.way... | This function handles a player's move in a Tic-Tac-Toe game by updating the board with 'X' or 'O', disabling the button, toggling turns, checking for a win, removing the move from available options, and initiating the computer's turn if configured. It tracks move count and ensures proper UI state transitions. | def your_move(self,row,column):
self.moves+=1
if self.turn:
self.role='X'
self.buttons[row][column].config(text=self.role,bg='blue',state='disabled')
else:
self.role='O'
self.buttons[row][column].config(text=self.role,bg='red',state='disabl... |
def your_move(self,row,column):
self.moves+=1
if self.turn:
self.role='X'
self.buttons[row][column].config(text=self.role,bg='blue',state='disabled')
else:
self.role='O'
self.buttons[row][column].config(text=self.role,bg='red',state='disabl... | The code creates a 3x3 grid of buttons for a Tic-Tac-Toe game, initializes available moves, best moves for the computer, adds a reset button, and labels for player turns. It sets up the GUI interface, binds button clicks to handle player moves, and prepares the game state for player vs. computer interaction. | def create_widgets(self):
for row in range(3):
self.rows=[]
for column in range(3):
self.rows.append(Button(self,width=10,height=3,font=('Calibri 18 bold',35),command=lambda x=row,y=column:self.your_move(x,y)))
self.rows[column].grid(row=row,column=column)... |
def build_forward_graph(self):
with self.forward_graph.as_default():
self.build_content_op()
self.build_style_ops()
def build_train_graph(self):
# in order to build this graph we need to evaluate the forward_graph
with self.forward_graph.as_default():
content_... | The code's main task is to train a model over a specified number of steps. It first constructs the forward and training graphs, then iterates through each training step, executes the training process, and collects non-empty results. Finally, it returns the list of collected results. | def fit(self):
self.build_forward_graph()
self.build_train_graph()
results = []
for step in range(1, self.steps):
result = self.train(step)
if result:
results.append(result)
return results |
def load_text_to_translate(self):
with open(self.text_to_translate_path, 'r', encoding="utf-8") as f:
self.text_to_translate = f.read()
def load_translation_model(self):
self.model = OpenaiTranslationModel(self.text_to_translate, self.supported_languages_instance)
def batch_translate_the_tex... | This method translates all text files in a specified folder by iterating through each file, loading the text content, initializing a translation model, and performing batch translations. It constructs file paths dynamically, processes each text file individually, and applies translation in batches to efficiently handle... | def translate_the_folder(self):
for text_to_translate_name in self.text_to_translate_names:
self.text_to_translate_path = os.path.join(self.folder_to_translate_path, text_to_translate_name)
self.load_text_to_translate()
self.load_translation_model()
self.batch_tr... |
def is_empty(self):
return len(self._data) == 0
def _swap(self, i, j):
self._data[i], self._data[j] = self._data[j], self._data[i]
def _downheap(self, j):
small_child = 0
if self._has_left(j):
left = self._left(j)
small_child = left
if self._has_right... | This function removes the minimum element from a priority queue by swapping the root with the last element, popping it, and then adjusting the heap. It also checks adjacent elements for equal keys, swapping them if found, before restoring the heap property via _downheap. Finally, it returns the removed element's value. | def remove_min(self):
if self.is_empty():
raise Exception("Priority queue is empty.")
self._swap(0, len(self._data) - 1)
item = self._data.pop()
for i in range(0, len(self._data)):
if (i + 1) < (len(self._data)) and self._data[i]._key == self._data[i + 1]._key:
... |
def _swap(self, i, j):
self._data[i], self._data[j] = self._data[j], self._data[i]
def _upheap(self, j):
parent = self._parent(j)
if j > 0 and self._data[j] < self._data[parent]:
self._swap(j, parent)
self._upheap(parent)
def _downheap(self, j):
small_child = 0
... | The main task of the code is to remove the element at index `k` from a heap structure. It swaps the element at index `k` with the last element, then removes the last element. If the removed element's key is greater than the swapped element's key, it restores the heap property by calling `_upheap` or `_downheap` based o... | def remove_index(self, k):
d = self._data[len(self._data) - 1]
# w = self._data[k]
self._swap(k, len(self._data) - 1)
if k == len(self._data) - 1:
self._data.pop()
return
else:
item = self._data.pop()
if d._key <= item._key:
... |
def _swap(self, i, j):
self._data[i], self._data[j] = self._data[j], self._data[i]
def _upheap(self, j):
parent = self._parent(j)
if j > 0 and self._data[j] < self._data[parent]:
self._swap(j, parent)
self._upheap(parent)
def _downheap(self, j):
small_child = 0
... | This function removes the element at index k from a heap-like structure, maintaining the heap property. It swaps the element with the last one, pops it, and adjusts the heap by either upheaping or downheaping based on the comparison between the swapped element and the popped item. The returned value is the value of the... | def remove_g_index(self, k):
d = self._data[len(self._data) - 1]
# w = self._data[k]
self._swap(k, len(self._data) - 1)
if k == len(self._data) - 1:
item = self._data.pop()
else:
item = self._data.pop()
if d._key <= item._key:
s... |
def forward(self, X):
"""Perform one forward step.
Return a pair consisting of the outputs of the hidden_layer
and the outputs on the final layer"""
hidden_activations = self.activ(X @ self.weights1)
hidden_outs = add_bias(hidden_activations, self.bias)
outputs = self.act... | This code trains a neural network with one hidden layer for binary classification using stochastic gradient descent. It initializes weights with Xavier initialization, performs forward and backward passes over epochs, computes binary cross-entropy loss, tracks training/validation metrics, and implements early stopping ... | def fit(self, X_train, y_train, X_val=None, y_val=None, eta=0.001, epochs=100, tol=1e-4, n_epochs_no_update=5,
seed=None):
"""Initialize the weights. Train *epochs* many epochs.
X_train is a Nxm matrix, N data points, m features
y_train is a vector of length N of targets values for t... |
def generatePossibleMoves(self, box):
piece_row = box.row
piece_col = box.col
surrounding_pieces = []
piece = self.get_piece(piece_col, piece_row)
for col in range(-1, 2, 2):
for row in range(-1, 2, 2):
if self.withinBounds(piece_col + col, piece_row ... | The code defines a method to move a game piece on a grid, checking if the target position is a valid move. It prints the move coordinates, retrieves the selected piece, and checks possible moves. If the target is empty, it swaps pieces and promotes the moved piece to a king if applicable. If the target has an opponent'... | def move_piece(self, from_col, from_row, to_col, to_row):
print("From: (" + str(from_col) + ", " + str(from_row) + ")")
print("To: (" + str(to_col) + ", " + str(to_row) + ")")
selected_piece = self.grid[from_col][from_row].piece
moves = self.generatePossibleMoves(self.grid[from_col][from... |
def check_longech_online_status():
sites = ['LON']
for items in sites:
return run_sites(items)
def check_lolupe_online_status():
sites = ['LOL']
for items in sites:
return run_sites(items)
def check_illeret_online_status():
sites = ['ILL']
for items in sites:
return run_s... | The function checks if multiple services (longech, lolupe, illeret, dukana, nadwat, kataboi) are online using regex. If all are online, it sends an SMS via Africas Talking API to specified recipients with a timestamp and success message. If any service is offline, it triggers an alternative method to handle partial onl... | def sending_all_online(self):
lon = check_longech_online_status()
lol = check_lolupe_online_status()
ill = check_illeret_online_status()
duk = check_dukana_online_status()
nad = nadwat_online()
kat = kataboi_online()
longech = re.search("Online$", lon)
if ... |
def get_ordered_idxs(parse_s: dict) -> list[int]:
"""Return a list of parse_s idxs in order of top to bottom of the tree.
Note: ignores idx 0 (i.e., fakeroot)
Args:
parse_s (dict) : a tree of head::int->deps::list[int]
has a fakeroot idx=0, whose dependent is the real ... | The function `get_tuples` generates a list of tuples by matching patterns in `pattern_tiers` against parse structures (`parse_s`, `parse_p`). It prioritizes the highest-ranked tier, processes all patterns within that tier, and considers every token in the parse as a potential root. It returns tuples derived from the fi... | def get_tuples(parse_s: dict, parse_p: dict, pattern_tiers) -> list[tuple]:
"""Return a list of tuples.
Notes:
* we return for the highest ranked matching tier only
* we return for every pattern in that tier
* we return considering every token in the parse as a potential root wrt., each... |
def subgraphs_to_domon_costello(nx_mono, subgs):
"""Converts the subgraphs of a given graph object into their canonical Domon & Costello fragment names\n
| Arguments:
| :-
| nx_mono (networkx_object): the original monosaccharide only graph
| subg (list): a list of modified networkx subgraphs\n
| Returns:
... | The function processes molecular graphs to generate ion names by converting subgraphs into Domon-Costello names, optionally adjusting for mass differences. It sorts and selects top 5 candidates by length, appending IUPAC names if specified. The output is a list of ion names, prioritizing shorter fragments, with optiona... | def finalise_output_fragments(nx_mono, graphs, diffs, reverse_anneal = False, iupac=False):
ion_names = []
dc_names = subgraphs_to_domon_costello(nx_mono, graphs)
if reverse_anneal:
dc_names = mass_match(dc_names, diffs)
idx = np.argsort([len(x) for x in dc_names])
dc_names = [dc_names[x] for x in idx][:5... |
def assign_dict_labels(dicty):
"""bin dictionary items according to key values\n
| Arguments:
| :-
| dicty (dict): dictionary of form m/z : spectrum\n
| Returns:
| :-
| Returns a list of labels used for binning/grouping the dict items
"""
k = 0
labels = [0]
keys = list(dicty.keys())
for d in ran... | The main task of the code is to organize a cluster of mass spectra into averaged spectra by grouping m/z values with discontinuities >0.5, then averaging intensities and retention times within each cluster. It returns lists of averaged m/z values, representative spectra, retention times, cluster sizes, and optionally a... | def build_mean_dic(dicty, rt, intensity):
"""organizes a spectra cluster into an averaged spectrum\n
| Arguments:
| :-
| dicty (dict): dictionary of form m/z : spectrum
| rt (list): list of retention times
| intensity (list): list of intensities\n
| Returns:
| :-
| (1) list of peak m/z
| (2) list of... |
def glycan_to_graph_monos(glycan):
"""Modified version of glycan_to_graph taking every other node, i.e., the monosaccharides\n
| Arguments:
| :-
| glycan (string): IUPAC-condensed glycan sequence\n
| Returns:
| :-
| (1) a dictionary of node : monosaccharide
| (2) an adjacency matrix of size monosacchari... | (CandyCrumbs annotates observed fragment masses with possible glycan fragment names derived from a given glycan structure. It processes the input glycan into a graph, generates atomic fragments, matches them to observed masses within a mass threshold, and returns annotated tuples of mass and fragment names. Parameters ... | def CandyCrumbs(glycan_string, fragment_masses, mass_threshold, libr = None,
max_frags = 3, simplify = True, reverse_anneal = True,
charge = 1, iupac = False, intensities = None, mode = 'negative'):
"""Basic wrapper for the annotation of observed masses with correct nomenclature given ... |
def FromTxtTransactionsDF(
folder: Folder,
filename: Optional[str] = None,
prefix: Optional[str] = None,
) -> TransactionsDF:
"""Imports a relay txt file as a TransactionsDF.
If filename is None, the max filename with the prefix 'relay' and the suffix '.txt'
from the directory 'path_to_transac... | This function imports unannotated transaction data from all folders (excluding 'merged') by reading files (txt/xlsx/csv), creating TransactionsDF objects, and optionally pruning duplicates using prune_tdf. It concatenates all non-empty DataFrames into a single TransactionsDF, collects unique filenames, and returns the ... | def concat_all_unannotated(
prune_tdf: Optional[TransactionsDF] = None,
) -> Tuple[TransactionsDF, List[str]]:
"""Imports all unannotated transactions from all folders in folders.keys() (except 'merged') and
concatenates them into a single TransactionsDF.
If prune_tdf is not None, prune_tdf is passed ... |
def FromCsvTransactionsDF(**kwargs) -> TransactionsDF:
"""Imports a csv file as a TransactionsDF by calling FromSpreadsheetTransactionsDF."""
return FromSpreadsheetTransactionsDF(filetype='csv', **kwargs)
def FromExcelTransactionsDF(**kwargs) -> TransactionsDF:
"""Imports an excel file as a TransactionsDF b... | The function merges unannotated transactions from multiple sources with existing annotated data by pruning duplicates and deleted entries, annotates new transactions, and consolidates them into a unified merged TransactionsDF, which is saved as a CSV file if specified. | def merge_all(write: bool = True) -> TransactionsDF:
"""Imports all unannotated transactions from all non-'merged' folders in folders.keys(), prunes them
against the latest merged transactions file, and concatenates them into a single unannotated TransactionsDF.
Prunes internal duplicates from the unannota... |
def BatchRun(textList, outputFolder):
dreamList = []
for text in textList:
print('Converting text:', text)
sha_key = sha(text)
outputPath = os.path.join(outputFolder, '{}.mp3'.format(sha_key))
for retry in range(3):
content = Synthesize(text)
if content:
... | The main task of the code is to process input text from a file by reading, stripping, and storing lines in a list. It then executes batch operations, searches for images using generated JSON paths, and translates processed content into Chinese, though the translation function appears to have a redundant parameter call. | def MakeDreamSpeech(inPath, outFolder):
textList = []
with codecs.open(inPath, 'r', 'utf8') as fin:
for line in fin:
line = line.strip()
textList.append(line)
jsonPath = BatchRun(textList, outFolder)
SearchImage(jsonPath)
# Translate to Chinese
TranslateDreamList(... |
def get_doc_table(self):
try:
wait = WebDriverWait(self.get_dsc_table(), LONG_WAIT)
return wait.until(EC.presence_of_element_located((By.XPATH, "./doc-table//table/tbody")))
except:
return None
def load_all_elements(self, timeout=SHORT_WAIT):
"""Triggers infin... | The code processes a table by iterating through rows to extract user data, check for duplicates in a cache, and store new records. It skips processing if "fast_scan" mode is enabled. For each row, it retrieves user IDs, parses documents, and stores records only if they are not already cached, logging progress and skipp... | def process_table(self, target):
table = self.get_doc_table()
logger.info("Waiting for data to be loaded on the page")
self.load_all_elements()
if config["DEFAULT"].getboolean("fast_scan", False):
logger.info("fast_scan mode")
return
... |
def count_rows(self):
return len(self.get_doc_table().find_elements_by_xpath("./tr"))
def get_row_at_index(self, index):
try:
wait = WebDriverWait(self.get_doc_table(), SHORT_WAIT)
return wait.until(EC.presence_of_element_located((By.XPATH, f'./tr[{index}]')))
except:
... | The function retrieves the timestamp of the last row in a dataset by first counting the total rows, identifying the index of the last row, fetching that row, and then extracting its timestamp. It returns this timestamp as the result. | def get_last_displayed_elements_timestamp(self):
row_count = self.count_rows()
last_summary_row_index = row_count-1
last_summary_row = self.get_row_at_index(last_summary_row_index)
timestamp = self.get_timestamp(last_summary_row)
return timestamp |
def get_last_displayed_elements_timestamp(self):
row_count = self.count_rows()
last_summary_row_index = row_count-1
last_summary_row = self.get_row_at_index(last_summary_row_index)
timestamp = self.get_timestamp(last_summary_row)
return timestamp
def navigate(se... | The code's main task is to load the next page of search results by constructing a URL with a timestamp from the last displayed elements, then navigating to this URL to fetch subsequent data. It logs the action, retrieves the timestamp, and uses it to build a new search URL for pagination or continuous data retrieval. | def update_search(self, url):
logger.info("Loading next page")
timestamp = self.get_last_displayed_elements_timestamp()
self.navigate(self.build_search_url(url, timestamp)) |
def sample_hidden(self,v):
"""Returns samples of binary hidden variables"""
return sample_bernoulli(self.prob_hidden(v))
def prob_visible(self,h):
"""Returns probabilities of visible variables being equal to 1"""
return tf.nn.sigmoid(self.hiddenTimesW(h)+self.visible_bias)
def prob_hidde... | The code performs Gibbs sampling for a Restricted Boltzmann Machine, starting with an initial visible state `v_init`. It alternates between sampling hidden units from visible states and reconstructing visible units from hidden states for `kGibbs-1` iterations. Finally, it computes the last hidden state probabilisticall... | def gibbs_sampling(self,v_init):
"""Performs Gibbs sampling and returns first visible+hidden state as well as the last visible+hidden sample"""
h = self.sample_hidden(v_init)
h_k = tf.identity(h)
v_k = self.prob_visible(h_k)
for _ in range(self.kGibbs-1):
h_k = self.sam... |
def recon_mse(self,data,corrupted_data):
"""Returns reconstructions error"""
return tf.reduce_mean(tf.math.squared_difference(data,self.reconstruct(corrupted_data)),axis = 1)
def free_energy(self,v):
"""Returns free energy"""
return - tf.einsum("ni,i->n",v,self.visible_bias) - tf.reduce_... | This function computes evaluation metrics for training and validation datasets based on specified metrics. It calculates ROC, accuracy (with class weighting), log loss (with sample weights), reconstruction MSE, free energy difference, and approximate log-likelihood (LL) for each epoch. Metrics like accuracy and LL are ... | def compute_metrics(self,metrics,train_data,val_data,train_data_y,val_data_y,train_corrupted,val_corrupted):
"""Computes metrics for train and val set, and adds them to the history of the model"""
for metric in metrics:
if metric["name"] == "roc":
self.history["train_roc"].ap... |
def epochIterable(self):
"""Returns iterable depending on being executed in notebook or shell"""
if not isnotebook():
return range(self.epochs)
else:
return tqdm(range(self.epochs),desc="Epoch",leave = self.leave_bar)
def step(self,batch,batch_class):
"""Implement... | The main task of the code is to train a Restricted Boltzmann Machine (RBM) using contrastive divergence. It initializes model parameters, computes class weights, processes training/validation data, and iteratively updates weights via stochastic gradient descent. The function tracks metrics, implements early stopping, a... | def fit(self,**kwargs):
"""Main RBM model training function"""
train_data = kwargs.get("train_data")
visible_mean = np.mean(train_data,axis = 0)
visible_mean[visible_mean==0]=0.001
self.baserate_bias = (np.log(visible_mean) - np.log(1-visible_mean)).astype(kwargs.get("dtype","flo... |
def get_bias_matrix(bias_vec, meters_a):
m_a = len(meters_a)
n = len(bias_vec) / hist_samples
# Check if we use a unique bias
if n < m_a:
bias = np.zeros((hist_samples, m_a))
bias_base = bias_vec.reshape((hist_samples, 1))
for i in range(m_a):
bias[:, i] = bias_base[:, 0]
else:
bias = bias_vec.reshap... | The function `grad_Gamma` computes a gradient vector for a set of meters using input parameters. It generates a bias matrix from `bias_vec` and `meters_a`, updates data using time points `t_0` and `t_f`, calculates gradients via `get_grad`, and converts the result into a vector format aligned with `bias_vec`'s length. ... | def grad_Gamma(bias_vec, models, grad_f, list_meters, t_0, t_f, meters_a):
m_a = len(meters_a)
bias = get_bias_matrix(bias_vec, meters_a)
x_a = update_data(list_meters, t_0, t_f, bias, meters_a)
grad = get_grad(x_a, list_meters, grad_f)
grad_a = get_grad_vector(grad, meters_a, len(bias_vec))
'''
if np.any(gr... |
def get_bias_matrix(bias_vec, meters_a):
m_a = len(meters_a)
n = len(bias_vec) / hist_samples
# Check if we use a unique bias
if n < m_a:
bias = np.zeros((hist_samples, m_a))
bias_base = bias_vec.reshape((hist_samples, 1))
for i in range(m_a):
bias[:, i] = bias_base[:, 0]
else:
bias = bias_vec.reshap... | The function `Gamma` computes the average error between predicted values (`hat_y_a`) and actual samples (`y_sample`) over a specified time range `[t_0, t_f]`. It uses a bias correction matrix derived from `bias_vec` and meters in `meters_a` to adjust input data (`x_a`), generates predictions via provided `models`, and ... | def Gamma(bias_vec, models, grad_f, list_meters, t_0, t_f, meters_a):
m_a = len(meters_a)
bias = get_bias_matrix(bias_vec, meters_a)
x_a = update_data(list_meters, t_0, t_f, bias, meters_a)
y_sample = y[t_0+hist_samples:t_f]
try:
hat_y_a = get_prediction(x_a, models)
except:
pdb.set_trace()
error = hat_y_... |
def get_bias_matrix(bias_vec, meters_a):
m_a = len(meters_a)
n = len(bias_vec) / hist_samples
# Check if we use a unique bias
if n < m_a:
bias = np.zeros((hist_samples, m_a))
bias_base = bias_vec.reshape((hist_samples, 1))
for i in range(m_a):
bias[:, i] = bias_base[:, 0]
else:
bias = bias_vec.reshap... | The function `find_attack` aims to identify an optimal adversarial attack vector that minimizes a defined objective function (`Gamma`), using gradient-based optimization. It loads multiple machine learning models, constructs initial bias conditions, and computes the impact of the attack on model predictions. The attack... | def find_attack(directory, total_models, number_models, meters_a, unique_bias=False):
#t_0 = time.perf_counter()
# create a new session
sess = tf.Session()
sess.run(tf.global_variables_initializer())
K.set_session(sess)
models = []
grad_f = []
m_a = len(meters_a)
# select randomly the models
id_models = s... |
def publickeylisttoarray(input):
width = 6
output = np.array([input[i:i+width] for i in range(0, len(input), width)])
return output
def encryptstring(input, inputpublickey):
input = str(input)
encryptedarray = np.empty(shape=[0, 5])
for chars in input:
encryptedchar = encryptcharacter(ch... | The main task of the code is to encrypt a given password using a provided public key. It converts the public key input into an array, encrypts the password with the public key, and returns the encrypted result as a list of integers. The process involves converting the encrypted data to a NumPy array, casting it to inte... | def encryptPasswordApi(password, publickeyinput):
publickey = publickeylisttoarray(publickeyinput)
encryptedpassword = encryptstring(password, publickey)
return (np.array(encryptedarraytolist(encryptedpassword)).astype(int)).tolist() |
def publickeylisttoarray(input):
width = 6
output = np.array([input[i:i+width] for i in range(0, len(input), width)])
return output
def hash_words(selected_words):
encrypted_words = [hash_function(word) for word in selected_words]
return encrypted_words
def decryptstring(input, inputsecretkey, publi... | The function verifies a secret key by checking if it can correctly decrypt a randomly generated test message. It hashes the secret key, converts the public key to an array, encrypts the test message with the public key, and decrypts it using the secret key. If the decrypted message matches the original, the secret key ... | def verifySecretKey(secretkey, publickey):
if (len(secretkey) == 4):
publickeyarr = publickeylisttoarray(publickey)
secretkeyarr = hash_words(secretkey)
testmessage = str(random.randint(256, 512))
if (testmessage == decryptstring((encryptstring(testmessage, publickeyarr)), secretkeya... |
def hash_words(selected_words):
encrypted_words = [hash_function(word) for word in selected_words]
return encrypted_words
def generate_public_key(secretkey, publickeycount, modulus):
vectorsize = len(secretkey)
publickey = np.random.randint(100, 400, (publickeycount, vectorsize))
publickeysecretkeym... | The main task of the code is to generate a public key from a given secret key. It hashes the secret key, uses a randomly selected large prime number, and constructs a public key array. The result is converted to a list of integers for output. | def publicKeyApiGenerator(secretkey):
secretkeyarr = hash_words(secretkey)
publickey = generate_public_key(
secretkeyarr, 20, random.choice(prime_list_larger_100))
return np.array(publickeyarraytolist(publickey)).astype(int).tolist() |
def publickeylisttoarray(input):
width = 6
output = np.array([input[i:i+width] for i in range(0, len(input), width)])
return output
def hash_words(selected_words):
encrypted_words = [hash_function(word) for word in selected_words]
return encrypted_words
def encryptedlisttoarray(input, publickey):
... | The main task of the code is to decrypt an encrypted password using a secret key and public key. It converts input parameters into required formats, hashes the secret key, processes the encrypted password, and decrypts it to return the original password. | def decryptPasswordApi(encryptedpassword, secretkeyinput, publickeyinput):
publickey = publickeylisttoarray(publickeyinput)
secretkey = hash_words(secretkeyinput)
passwordarray = encryptedlisttoarray(encryptedpassword, publickey)
print(publickey)
print(secretkey)
print(passwordarray)
passwo... |
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
DATABASE,
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
def send_payment(address, db, ip):
account_id = get_account_id()
try:
spendable_txo = get_spendable... | The code implements a cryptocurrency faucet with CAPTCHA verification and rate limiting. It retrieves user IP addresses, validates hCaptcha responses, checks IP and address-based cooldown periods via a database, and distributes MOB tokens if all checks pass. | def faucet():
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip = request.remote_addr
print('IP:', ip)
if request.method == 'POST':
if HCAPTCHA_SITE_KEY:
# Verify captcha
token = request.form['h-capt... |
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
DATABASE,
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
def send_payment(address, db, ip):
account_id = get_account_id()
try:
spendable_txo = get_spendable... | The code handles batch payments by splitting input addresses, sending payments to each, tracking successes/failures, and displaying feedback messages. It processes POST requests, uses a database, and redirects to the same page, showing results via flashed messages. | def batch():
if request.method == 'POST':
db = get_db()
addresses = request.form['address'].split()
successes = []
failures = []
print(addresses)
for address in addresses:
if send_payment(address, db) == 1:
successes.append(address)
... |
def game_init(self):
self.score = 0 # How many asteroid destroyed
self.A_TIME = 1000
self.asteroids_timer = self.A_TIME
self.lives = 1
self.is_dead = False
self.bullet_count = 5
self.shot_rate = 50
self.shot_tim = 0
self.can_shot = True
... | The code runs a game loop that initializes the game, updates game state (including shooting mechanics, collision checks, asteroid generation), processes AI decisions based on vision input, handles user inputs (shooting, resetting lives, pausing), and renders the game window. The loop continues until the player dies, tr... | def play_game(self, generation=0):
self.game_init()
while not self.is_dead:
self.clock.tick(self.FPS)
if not self.can_shot:
self.shot_rate -= 1
if self.shot_rate <= 0:
self.can_shot = True
self.shot_rate =... |
def centered_rect(rect):
x,y,w,h = rect
x -= w // 2
y -= h // 2
return pygame.Rect((x,y,w,h))
def draw_hovered(self, win):
x, y = self.pos
w, h = self.size[0] + 5, self.size[1] + 5
rect = centered_rect((x,y,w,h))
pygame.draw.rect(win, colors['grey1'], rect, 3)
... | The main task of the code is to draw a rectangle on a Pygame window using specified position and size, apply a hover effect if triggered, and render associated text if present. It uses `centered_rect` to create the rectangle, `pygame.draw.rect` for rendering, and `write_text` for text display, integrating visual elemen... | def draw(self, win):
x, y = self.pos
w, h = self.size
rect = centered_rect((x,y,w,h))
pygame.draw.rect(win, self.col, rect)
if self.HOVERED:
self.draw_hovered(win)
if self.text is not None:
write_text(win, self.text, self.pos, self.text_col, sel... |
def modify_todo(self):
while True:
print('Enter [e] to enter a new task, [l] to list all tasks, [d] to delete a task, or [b] to go back:')
command = input()
if command.lower() == 'e':
self.todo_list = self.enter_task(self.todo_list)
elif command.... | The code runs an infinite loop prompting the user to manage tasks via commands: 'td' for to-do lists, 'ap' for appointments, 'dt' for done tasks, or 's' to save and exit. It executes corresponding methods based on input, validates commands, and terminates on 's' after saving data. | def run(self):
while True:
print('Enter [td] for to do list, [ap] for with appointments, [dt] for done tasks, or '
'[s] to save and exit:')
command = input()
if command.lower() == 'td':
self.modify_todo()
elif command.lower() ==... |
def load_save_file(self):
todo_list = []
appointments = {}
daily_done_tasks = []
notes = {}
if os.path.exists('organiser.txt'):
file = open('organiser.txt', 'r', encoding='utf-8')
data = file.read()
file.close()
if data:
... | The code initializes a GUI application by loading saved data (to-do list, appointments, completed tasks, notes) from a file, creating and positioning UI widgets, and populating text fields with the loaded data for display. | def __init__(self):
self.todo_list, self.appointments, self.daily_done_tasks, self.notes = self.load_save_file()
self.create_widgets()
self.place_widgets()
self.list_items(self.todo_text_field, self.todo_list)
appointments_as_list = self.format_appointment_to_string()
s... |
def open_game(self):
subprocess.Popen(
"cd ~ && cd Downloads/ruffle-nightly-2023_08_26-linux-x86_64/ && ./ruffle", shell=True)
def board_is_moving(self):
img = ImageGrab.grab()
img = img.crop(self.board_box)
img = img.resize((img.size[0]//4, img.size[1]//4), Image.BILINEAR)
... | The code automates solving a puzzle game by training a recognizer, capturing and resizing the game board image, using a solver to determine optimal moves, and executing those moves until the game ends. It tracks the number of moves made and prints the total upon completion. | def main(self):
self.recognizer.train()
game_solver = solver.Solver()
moves = 0
# self.grab_board()
self.open_game()
ready = input('Ready? (y/n)')
if ready == 'y':
print('Starting game...')
while True:
if not self.board_is_m... |
def get_all_subjects(source: Path) -> List[str]:
"""
Retrieves all unique subjects from a CSV file.
Args:
source (Path): The path to the CSV file.
Returns:
List[str]: A list of unique subjects.
Raises:
KeyError: If the subject column is not found in the CSV file.
"""
... | The code generates a subject mapping by aggregating subjects from specified sources and addon configurations, combining them with a site map, and saving the result as a JSON file. It reads configuration parameters, validates source files, collects subject data, enriches the map with predefined entries, and writes the f... | def generate_subject_map(config_file: Path) -> None:
"""
Generate subject mapping based on the provided configuration file.
Args:
config_file (Path): The path to the configuration file.
Returns:
None
"""
config_params = utils.config(config_file, "general")
mapping_config = ... |
def get_user_input():
"""Ask the user if they want to provide a URL or a file."""
choice = input("Do you want to provide a URL or a file path? Enter 'url' or 'file': ").strip().lower()
return choice
def process_url(url, history_folder):
"""Process the privacy policy by scraping directly from the provide... | The main task of the code is to execute a script that processes privacy policy data by either scraping a provided URL or analyzing an HTML file. It prompts the user to choose between inputting a URL or a file path, creates a "history" directory for storage, and invokes corresponding processing functions. The script ens... | def main():
"""Main execution logic that will take user input and run the correct process."""
print("Script started.")
user_choice = get_user_input()
if user_choice == 'url':
url = input("Enter the URL of the privacy policy to scrape: ").strip()
history_folder = os.path.join(os.getcwd()... |
def get_user_input():
"""
Prompt the user to specify whether they want to provide a URL or a file path.
Returns:
choice (str): The user's choice as either 'url' or 'file'.
"""
choice = input("Do you want to provide a URL or a file path? Enter 'url' or 'file': ").strip().lower()
return ch... | The main task of the code is to orchestrate a script that processes user input to either scrape a privacy policy from a provided URL or analyze an HTML file. It directs execution to `process_url` or `process_file` based on user choice, manages a "history" directory for storage, and ensures the script starts and ends wi... | def main():
"""
Main function to orchestrate the process based on user input. This function directs whether to process a URL or a file based on user's choice.
Returns:
None: Completes the user-directed action and terminates.
"""
print("Script started.")
user_choice = get_user_input()
... |
def start_game_loop(self):
while self.is_game_over() == bool(False):
self.next_move()
def announce_end_of_game(self):
print("Game is over.")
def announce_winner(self):
if self.match.game_is_over and self.someone_won():
if self.match.winner == "player":
pri... | The code's main task is to initiate a game by starting the game loop, then announcing the game's end and declaring the winner once the loop concludes. It orchestrates the game flow from start to finish, ensuring proper sequence of events for a complete match. | def start_match(self):
self.start_game_loop()
self.announce_end_of_game()
self.announce_winner() |
def VEML3328_init():
VEML3328_enableSensor()
def VEML3328_setIT(it): #integration time 0=50ms,1=100,2=200,3=400
conf = VEML3328_read(VEML3328_CONF)
conf = conf & 0x0003
it = it << 4
VEML3328_write(VEML3328_CONF, (conf | it))
def VEML3328_autoMode(): #auto measurement mode
conf = VEML3328_read(VEML3328_CON... | The main task of the code is to initialize a VEML3328 light sensor, configure it in auto mode, and collect RGB and white light data under four different interrupt settings (0–3). It records 20 samples per mode at varying intervals (0.2–0.5s), writes the data to separate CSV files (csv0–csv3), and disables the sensor af... | def main(args):
VEML3328_init()
VEML3328_setIT(0)
VEML3328_autoMode()
i = 0
time.sleep(1.0)
while i < 20:
r=getRed()
g=getGreen()
b=getBlue()
c=getWhite()
print( "red=",r," : ","grn=",g ," : ","blu=", b," : ","wht=",c)
csv0.write... |
def VEML6040_init():
VEML6040_enableSensor()
def VEML6040_setIT(it): #integration time 0=40ms,1=80,2=160,3=320,4=640,5=1280ms
conf = VEML6040_read(VEML6040_CONF)
conf = conf & 0x0003
it = it << 4
VEML6040_write(VEML6040_CONF, (conf | it))
def VEML6040_autoMode(): #auto measurement mode
conf = VEML6040_rea... | The code initializes a VEML6040 sensor, reads RGB and white light values at varying intervals (0.2–1.5s) under six interrupt settings (IT 0–5), logs each dataset to separate CSV files, and disables the sensor afterward. It tests sensor performance across different sampling rates and configurations, capturing 20 samples... | def main(args):
VEML6040_init()
VEML6040_setIT(0)
VEML6040_autoMode()
i = 0
time.sleep(1.0)
while i < 20:
r=getRed()
g=getGreen()
b=getBlue()
c=getWhite()
print( "red=",r," : ","grn=",g ," : ","blu=", b," : ","wht=",c)
csv0.write(st... |
def convert_bytes_to_id(data: bytes):
idm = binascii.hexlify(data)
return idm.decode()
def fetch_users():
try:
res = httpx.get(DB_SERVICE_BASE_URL + DB_SERVICE_USERS_PATH)
users = res.json()
return users
except Exception as e:
print(e)
return None
def on_found_use... | The code detects an NFC tag, converts its identifier to a user-friendly ID, retrieves a list of users, and checks if any user has a matching NFC ID. If a match is found, it triggers a function to handle the identified user. | def on_detect_nfc(tag: nfc.tag.Tag):
nfcId = convert_bytes_to_id(tag.identifier)
users = fetch_users()
if users is None:
return
for user in users:
if user['nfcId'] == nfcId:
on_found_user_with_same_nfc(user) |
def bareqket_fromcsv_ri_rj_exp(base_num):
name = './'+str(base_num) + '/bases.csv'
f = pd.read_csv(name)
base = []
for i in range(base_num):
base.append(f.iloc[i,0:9])
base = np.array(base)
base_ri_rj = []
for i in range(len(f)):
r1_r2 = (((f.iloc[i,0]-f.iloc[i,3])**2 + (f.il... | The code predicts wave function matrix elements using neural networks for operators like ground energy, RMS radius, or quadrupole. It processes diagonal and off-diagonal basis states, loads pre-trained models, transforms data, and constructs Kernel and norm matrices. The function returns these matrices with prediction ... | def kernel_norm_ri_rj_exp(base_num,batch_size,operator=str): #Prediction of wave function matrix elements using neural networks
if operator == 'ground_energy':
output = 2
elif operator == 'rms_radius':
output = 1
elif operator == 'quadrupole':
output = 1
start = time.time()
... |
def randAppleGen():
randAppleX = round(random.randrange(0, display_width-AppleThickness))#/10.0)*10.0
randAppleY = round(random.randrange(0, display_height-AppleThickness))#/10.0)*10.0
return randAppleX, randAppleY
def randSpikeGen():
randSpikeX = round(random.randrange(0, display_width-SpikeThickness))#/10... | This code defines the main game loop for a snake game. The loop handles user input for snake movement, checks for collisions with walls, spikes, and self, updates the game state, renders the game elements (snake, apple, spikes), and manages game over/restart logic. The primary task is to control the snake to eat apples... | def gameLoop():
global direction
gameExit = False
gameOver = False
lead_x = display_width/2
lead_y = display_height/2
lead_x_change = 0
lead_y_change = 0
snakeList = []
snakeLength = 1
randAppleX, randAppleY = randAppleGen()
randSpikeX, randSpikeY = randSpikeGen()
while n... |
def set_seed(args):
r"""
Fix the random seed for reproduction.
"""
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
if args.n_gpu > 0:... | The code defines a main function for training and evaluating a question-answering model on the WebSRC dataset using Hugging Face models (e.g., MarkupLM). It processes SQuAD-style JSON data, handles HTML-based features, and supports training with customizable parameters like model architecture, batch size, learning rate... | def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument("--train_file", default=None, type=str, required=True,
help="SQuAD json for training. E.g., train-v1.1.json")
parser.add_argument("--predict_file", default=None, type=str, required=True,
... |
def convBlock3(input, channal_out, k_size, stride, training = True):
output = conv2d_sn(input, channal_out, k_size, k_size, stride, stride, use_sn = True, use_bias = True)
output = lrelu(output, leak = 0.1)
return output
def attention(input):
input_shape = input.get_shape().as_list()
ch = input_sha... | This code defines a forward pass for a discriminator network in a GAN. It processes input through cascading convolutional blocks (with increasing filters and downsampling) across stages, applying attention in the 256x32x32 stage. If `with_fc` is True, it flattens the output and adds a spectral-normalized linear layer f... | def forward(self, input, training = True, with_fc = True):
with tf.variable_scope('dis_{}'.format(self.d_id), reuse = self.inited):
with tf.variable_scope('stage_32x256x256'):
output = convBlock3(input, 32, 3, 1, training)
with tf.variable_scope('stage_64x128x128_1'):
... |
def linear_sn(input_,
output_size,
scope=None,
initializer=tf.contrib.layers.variance_scaling_initializer(),
bias_start=0.0,
use_sn=True,
use_bias=True):
shape = input_.get_shape().as_list()
with tf.variable_scope(scope or "Linear"):
ma... | This code defines a forward pass for a generator network in a GAN, converting a latent vector or feature map into a generated image. It uses deconvolution blocks for upsampling, includes an attention module, and applies batch normalization and ReLU activations. The network has multiple stages with progressively increas... | def forward(self, z_or_f, training = True, with_fc = True):
with tf.variable_scope('gen_{}'.format(self.g_id), reuse = self.inited):
if with_fc:
with tf.variable_scope('stage_inputfc'):
output = linear_sn(z_or_f, 512 * 256)
output = tf.reshape(... |
def load_items_set(self):
""" Read data from res/items.csv and load it into items list. Each
element of the list is a tuple that represents some item from file
and consists of 3 elements: name, volume and value. """
with open(self.ITEMS_SET_FILE, newline='') as csv_file:
file... | This code initializes a genetic algorithm by setting a random seed, loading item data, creating an initial population, and iteratively evolving it through selection, crossover, mutation, and population renewal for a specified number of generations. | def __init__(self):
seed(self.RANDOM_SEED) # random.seed()
self.load_items_set()
self.create_starting_population()
for i in range(self.POPULATIONS_LIMIT):
self.panmixia_selection()
self.population_crossover()
self.mutate_population()
self... |
def run_analysis(filenames):
tdf = pd.DataFrame(columns=('Vendor', 'Adversary', 'Substep', 'Criteria', 'Tactic', 'TechniqueId', 'TechniqueName', 'SubtechniqueId', 'Detection', 'Modifiers'))
if not os.path.exists(os.path.join(os.getcwd(), 'results/vendor_results.json')):
vendor_results = {}
seg_d... | The code evaluates vendor and technique effectiveness against specific adversaries by generating rankings, calculating weighted scores (detection, correlation, automation), and exporting results to CSV files. It handles two special adversaries with tailored data formatting, computes protection scores, and generates vis... | def run_eval():
vendor_results, tactic_results, vendor_protections = run_analysis(filenames)
rankings = {}
for adversary in vendor_results.keys():
ranking = make_vendor_ranking(vendor_results, adversary)
rankings[adversary] = ranking
with open(f'results/{adversary}_vendor_Rankings.cs... |
def page_general(data,
data_biner,
average_purchase_amount,
average_review_rating,
average_previous_purchases,
total_customers,
theme):
# Implementasi khusus untuk halaman 'General'
additional_paragraph = """... | (The main task of the code is to create a Streamlit dashboard for customer segmentation analysis. It loads clustered customer data, calculates key metrics (e.g., average spending, reviews), maps states to abbreviations, and renders interactive pages via a sidebar menu. Each page visualizes different aspects of customer... | def main():
# Konfigurasi halaman Streamlit
st.set_page_config(
page_title="Customer Segmentation Dashboard",
page_icon="🧊",
layout="wide",
menu_items={'Get Help': 'https://mahaseenlab.com/',
'About': "# Masdar's Personal Project"},
initial_sidebar_st... |
def get_instance_type(instance_name):
if instance_name[:2]=='pr':
return 'Cordeau'
elif instance_name[0] in ['r', 'c']:
return 'Solomon'
elif instance_name[0] in ['t']:
return 'Gavalas'
raise Exception('weird instance')
def get_instance_df(instance_nam... | The main task of the code is to process instance data by generating a distance matrix and converting raw instance features into PyTorch tensors for device-specific computation. It extracts spatial-temporal features (x, y, duration, time intervals, profile) from a DataFrame, computes pairwise distances, and returns both... | def get_instance_data(instance, path, device):
instance_type = get_instance_type(instance)
df_inst = get_instance_df(instance, path, instance_type)
distm = get_distance_matrix(df_inst, instance_type)
raw_data = df_inst[['x', 'y', 'duration', 'ti', 'tf', 'prof', 'Total Time']].values
raw_data = torch... |
def compress(text, algorithm):
if algorithm == "bwt":
bwt = bwt_compress(text)
mtf = mtf_encode(bwt)
rle = rle_compress(mtf)
return rle
elif algorithm == "huffman":
character_freq = {char: text.count(char) for char in set(text)}
root_node = huffman(character_freq)... | The function `measure_compression_time` reads a text file, applies a specified compression algorithm (BWT, RLE, Huffman, or LZW), measures the time taken for compression, and returns the original text length and compression duration. It supports multiple compression methods, calculates Huffman frequencies, and timestam... | def measure_compression_time(filename, algorithm):
with open(filename, 'r') as file:
text = file.read()
start_compress = time.time()
if algorithm in ["bwt", "rle"]:
compressed = compress(text, algorithm)
elif algorithm == "huffman":
character_freq = {char: text.count(char) for c... |
def plurality_value(attributes,data,resultAttr):
"""Return the predicted decision of example"""
major_freq = get_frequency(attributes,data,resultAttr)
maximum = 0
major = ""
for key in major_freq.keys():
if major_freq[key] > maximum:
maximum = major_freq[key]
major = key
return major
def best_attribute(a... | This function constructs a decision tree recursively by selecting the best attribute to split the dataset, handling base cases for empty data or uniform result values, and generating subtrees for each attribute value, returning the tree as a dictionary structure. | def decision_tree_learning(data, attributes, resultattr, parent_data, original_attribute, old_data, parent_attribute):
"""Return the decision tree in a dictionary form"""
index_result = attributes.index(resultattr)
result_vals = [row[index_result] for row in data]
if not data:
return plurality_value(parent_attri... |
def is_one_pair(hands):
hands_num = [hand[0] for hand in hands]
c = Counter(hands_num)
result = c.values()
return len(result) == 4
def is_two_pair(hands):
hands_num = [hand[0] for hand in hands]
c = Counter(hands_num)
result = c.values()
return max(result) == 2 and len(result) == 3
def ... | This function evaluates a poker hand and returns a numerical rank based on standard poker rules, checking for specific hand types in descending order of strength: straight flush (8), four of a kind (7), full house (6), three of a kind (3), straight (4), flush (5), two pair (2), one pair (1), and no valid hand (0). | def judge_hands(hands):
if is_one_pair(hands):
judgement = 1
elif is_two_pair(hands):
judgement = 2
elif is_straight_flush(hands):
judgement = 8
elif is_three_card(hands):
judgement = 3
elif is_straight(hands):
judgement = 4
elif is_flush(hands):
j... |
def collect_train_episode(self, max_samples=None):
"""
Collects a maximum of `max_samples` training transitions (from reset to terminated or truncated)
This method stores the episode and the training return in the local `Buffer` of the worker
for sending to the `Server`.
Args:
... | The code runs worker episodes, sending data to a server while handling test intervals, weight updates, and logging. It operates in expert mode (no model updates) or standard mode, with verbose logging enabled/disabled, and optionally runs test episodes at specified intervals. The function manages episode collection, da... | def run(self, test_episode_interval=0, nb_episodes=np.inf, verbose=True, expert=False):
"""
Runs the worker for `nb_episodes` episodes.
This method sends episodes continuously to the Server, and checks for new weights between episodes.
For synchronous or more fine-grained sampling, use ... |
def reset(self, collect_samples):
"""
Starts a new episode.
Args:
collect_samples (bool): if True, samples are buffered and sent to the `Server`
Returns:
Tuple:
(nested structure: observation retrieved from the environment,
dict: informat... | The main task of the code is to collect a specified number of steps in a synchronized manner with a Trainer, handling initial steps, episode resets, and sending collected samples to the server. It manages step limits, model update ratios, and optionally runs test episodes periodically. The method ensures synchronizatio... | def run_synchronous(self,
test_episode_interval=0,
nb_steps=np.inf,
initial_steps=1,
max_steps_per_update=np.inf,
end_episodes=True,
verbose=False):
"""
Collect... |
def get_config(self, return_defaults: bool = False) -> dict:
"""
Returns a configuration for the Pipeline that can be used with `Pipeline.load_from_config()`.
:param return_defaults: whether to output parameters that have the default values.
"""
pipeline_name = "pipelin... | This method adds a node to a pipeline graph, validating the node's name, ensuring a single root node for the first addition, and updating the pipeline's structure. It checks for duplicate names (excluding identical components), configures component definitions, names nested components, and integrates the node into the ... | def add_node(self, component: BaseComponent, name: str, inputs: List[str]):
"""
Add a new node to the pipeline.
:param component: The object to be called when the data is passed to the node. It can be a Haystack component
(like Retriever, Reader, or Generator) or a use... |
def run( # type: ignore
self,
query: Optional[str] = None,
file_paths: Optional[List[str]] = None,
labels: Optional[MultiLabel] = None,
documents: Optional[List[Document]] = None,
meta: Optional[Union[dict, List[dict]]] = None,
params: Optional[dict] = None,
... | The main task of the code is to execute a pipeline in batch mode, processing multiple queries or documents sequentially through pipeline nodes. It handles data flow between nodes, manages input parameters, debug settings, and aggregation of results. The function processes inputs like queries, documents, or labels, appl... | def run_batch( # type: ignore
self,
queries: Optional[List[str]] = None,
file_paths: Optional[List[str]] = None,
labels: Optional[Union[MultiLabel, List[MultiLabel]]] = None,
documents: Optional[Union[List[Document], List[List[Document]]]] = None,
meta: Optional[Union[Di... |
def run( # type: ignore
self,
query: Optional[str] = None,
file_paths: Optional[List[str]] = None,
labels: Optional[MultiLabel] = None,
documents: Optional[List[Document]] = None,
meta: Optional[Union[dict, List[dict]]] = None,
params: Optional[dict] = None,
... | This function evaluates a pipeline's performance by running it in debug mode for each query, collecting data to calculate metrics like accuracy and semantic answer similarity (SAS). It supports isolated node evaluation to identify bottlenecks, uses custom parameters for document matching, and returns an EvaluationResul... | def eval(
self,
labels: List[MultiLabel],
documents: Optional[List[List[Document]]] = None,
params: Optional[dict] = None,
sas_model_name_or_path: Optional[str] = None,
sas_batch_size: int = 32,
sas_use_gpu: bool = True,
add_isolated_node_eval: bool = Fals... |
def run_batch( # type: ignore
self,
queries: Optional[List[str]] = None,
file_paths: Optional[List[str]] = None,
labels: Optional[Union[MultiLabel, List[MultiLabel]]] = None,
documents: Optional[Union[List[Document], List[List[Document]]]] = None,
meta: Optional[Union[Di... | The `eval_batch` function evaluates a pipeline's performance using labeled data by running it in debug mode, generating metrics like SAS (Semantic Answer Similarity) if a model is specified. It processes predictions in batches, constructs evaluation dataframes for each node's output, and optionally assesses isolated no... | def eval_batch(
self,
labels: List[MultiLabel],
documents: Optional[List[List[Document]]] = None,
params: Optional[dict] = None,
sas_model_name_or_path: Optional[str] = None,
sas_batch_size: int = 32,
sas_use_gpu: bool = True,
add_isolated_node_eval: bool ... |
def ReverseComplement(Pattern):
Pattern = Reverse(Pattern) # reverse all letters in a string
Pattern = Complement(Pattern) # complement each letter in a string
return Pattern
def printAllKLength(set, k):
n = len(set)
printAllKLengthRec(set, "", n, k)
def HammingDistance(Seq1,Seq2):
count = 0
... | The main task of the code is to identify the most frequent k-length patterns in a given DNA text, considering both their reverse complements and allowing up to d mismatches. It generates all possible k-length sequences, counts how many times each matches any substring or its reverse complement within the Hamming distan... | def FrequentWordswithMismatchesandReverseComplements(Text, k, d):
freqMap = {}
patterns = []
maxPatterns = []
set = ['A', 'C','G', 'T']
n = len(Text)
for i in range(0,n-k+1):
Pattern = Text[i:i+k]
patterns.append(Pattern)
patterns.append(ReverseComplement(Pattern))
pr... |
def Profile(Motifs):
count = Count(Motifs)
profile = {}
symbol_str = "ACGT"
for i in range(len(symbol_str)):
profile[symbol_str[i]] = []
for j in range(len(count[symbol_str[i]])):
profile[symbol_str[i]].append(0)
profile[symbol_str[i]][j] = count[symbol_str[i]][j]... | (GreedyMotifSearch identifies the best set of k-length motifs (one per DNA string) by iteratively selecting the most probable k-mers based on a profile matrix derived from previously selected motifs. It initializes with the first k-mers from each string, then iterates over all possible starting positions in the first s... | def GreedyMotifSearch(Dna, k, t):
BestMotifs = []
for i in range(0, t):
BestMotifs.append(Dna[i][0:k])
n = len(Dna[0])
for i in range(n-k+1):
Motifs = []
Motifs.append(Dna[0][i:i+k])
for j in range(1, t):
P = Profile(Motifs[0:j])
Motifs.append(Prof... |
def ProfileWithPseudocounts(Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = CountWithPseudocounts(Motifs)
sum_value = sum(profile[item][0] for item in profile)
for symbol in "ACGT":
for i in range(k):
profile[symbol][i] = profile[symbol][i]/sum_value
return profile
def ... | This function performs a greedy motif search with pseudocounts to find the best set of k-mers from t DNA strings. It initializes best motifs, iterates through all possible k-mer positions in the first DNA string, constructs motifs using pseudocount-based profiles, and updates the best motifs if the current set has a lo... | def GreedyMotifSearchWithPseudocounts(Dna, k, t):
BestMotifs = []
for i in range(0, t):
BestMotifs.append(Dna[i][0:k])
n = len(Dna[0])
for i in range(n-k+1):
Motifs = []
Motifs.append(Dna[0][i:i+k])
for j in range(1, t):
P = ProfileWithPseudocounts(Motifs[0:j]... |
def RandomMotifs(Dna, k, t):
motifs = []
for i in range(t):
start = random.randint(0, len(Dna[i]) - k)
motifs.append(Dna[i][start:start + k])
return motifs
def ProfileWithPseudocounts(Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = CountWithPseudocounts(Motifs)
sum_valu... | The main task of the code is to iteratively refine a set of motifs in DNA sequences using a randomized search with pseudocounts. It starts with random motifs, constructs a probability profile from them, generates new motifs based on this profile, and updates the best motifs if the new set has a lower score. This proces... | def RandomizedMotifSearch(Dna, k, t):
M = RandomMotifs(Dna, k, t)
BestMotifs = M
# while True:
for i in range(1000):
Profile = ProfileWithPseudocounts(M)
M = Motifs(Profile, Dna)
if Score(M) < Score(BestMotifs):
BestMotifs = M
# else:
# return Best... |
def RandomMotifs(Dna, k, t):
motifs = []
for i in range(t):
start = random.randint(0, len(Dna[i]) - k)
motifs.append(Dna[i][start:start + k])
return motifs
def ProfileWithPseudocounts(Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = CountWithPseudocounts(Motifs)
sum_valu... | The GibbsSampler function iteratively refines a set of k-length DNA motifs by randomly removing one motif, generating a probabilistic profile with pseudocounts from the remaining motifs, and replacing the removed motif with the most probable k-mer from the corresponding DNA string. It repeats this process N times, upda... | def GibbsSampler(Dna, k, t, N):
BestMotifs = []
Motifs = RandomMotifs(Dna, k ,t)
BestMotifs = Motifs.copy()
for j in range(0,N):
i = random.randint(0,t-1)
del Motifs[i]
profile = ProfileWithPseudocounts(Motifs)
Motifs.insert(i, ProfileMostProbableKmer(Dna[i], k , profile)... |
def Profile(Motifs):
count = Count(Motifs)
profile = {}
symbol_str = "ACGT"
for i in range(len(symbol_str)):
profile[symbol_str[i]] = []
for j in range(len(count[symbol_str[i]])):
profile[symbol_str[i]].append(0)
profile[symbol_str[i]][j] = count[symbol_str[i]][j]... | The code implements a **greedy algorithm** to find the best set of motifs (k-mers) from multiple DNA sequences. It initializes with the first k-mers from each sequence, then iterates through all possible starting positions in the first sequence. For each position, it constructs a motif set by selecting the most probabl... | def GreedyMotifSearch(Dna, k, t):
BestMotifs = []
for i in range(0, t):
BestMotifs.append(Dna[i][0:k])
n = len(Dna[0])
for i in range(n-k+1):
Motifs = []
Motifs.append(Dna[0][i:i+k])
for j in range(1, t):
P = Profile(Motifs[0:j])
Motifs.append(Prof... |
def ProfileWithPseudocounts(Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = CountWithPseudocounts(Motifs)
sum_value = sum(profile[item][0] for item in profile)
for symbol in "ACGT":
for i in range(k):
profile[symbol][i] = profile[symbol][i]/sum_value
return profile
def ... | The function `GreedyMotifSearchWithPseudocounts` identifies the best set of motifs (substrings of length *k*) from a collection of DNA strings (*t* sequences) using a greedy algorithm with pseudocounts. It initializes candidate motifs, iterates over all possible starting positions in the first DNA string, constructs mo... | def GreedyMotifSearchWithPseudocounts(Dna, k, t):
BestMotifs = []
for i in range(0, t):
BestMotifs.append(Dna[i][0:k])
n = len(Dna[0])
for i in range(n-k+1):
Motifs = []
Motifs.append(Dna[0][i:i+k])
for j in range(1, t):
P = ProfileWithPseudocounts(Motifs[0:j]... |
def RandomMotifs(Dna, k, t):
motifs = []
for i in range(t):
start = random.randint(0, len(Dna[i]) - k)
motifs.append(Dna[i][start:start + k])
return motifs
def ProfileWithPseudocounts(Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = CountWithPseudocounts(Motifs)
sum_valu... | The code implements the Gibbs Sampler algorithm to iteratively refine a set of motifs (k-mers) in DNA sequences. It initializes random motifs, then iteratively updates one motif at a time by sampling from a profile generated with pseudocounts. If the updated motifs have a lower score (higher similarity), they replace t... | def GibbsSampler(Dna, k, t, N):
BestMotifs = []
Motifs = RandomMotifs(Dna, k ,t)
BestMotifs = Motifs.copy()
for j in range(0,N):
i = random.randint(0,t-1)
del Motifs[i]
profile = ProfileWithPseudocounts(Motifs)
Motifs.insert(i, ProfileMostProbableKmer(Dna[i], k , profile)... |
def RandomMotifs(Dna, k, t):
motifs = []
for i in range(t):
start = random.randint(0, len(Dna[i]) - k)
motifs.append(Dna[i][start:start + k])
return motifs
def ProfileWithPseudocounts(Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = CountWithPseudocounts(Motifs)
sum_valu... | The main task of the code is to find the best set of motifs (each of length k from t DNA sequences) with the lowest score using a randomized search approach. It iteratively generates motifs, creates a probabilistic profile with pseudocounts, and refines motifs until no improvement is achieved, returning the best motifs... | def RandomizedMotifSearch(Dna, k, t):
M = RandomMotifs(Dna, k, t)
BestMotifs = M
while True:
Profile = ProfileWithPseudocounts(M)
M = Motifs(Profile, Dna)
if Score(M) < Score(BestMotifs):
BestMotifs = M
else:
return BestMotifs |
def clean_dir(dir_from, dir_to):
"""
Helper function, to take in source directory and target
directory and calls clean_file() on each file in the dir
"""
# Error checking directories
print('preprocessing data...')
if not os.path.exists(dir_from):
print('The source directory %s does ... | The code processes training data by cleaning it, extracts features and labels, concatenates them into a feature matrix, and saves the combined data as a CSV file for further analysis or machine learning tasks. | def main():
training_data = os.getcwd()+'/'+'CSDMC2010_SPAM/TRAINING/'
processed_data_targ = 'CSDMC2010_SPAM/CLEAN'
clean_dir(training_data, processed_data_targ)
features = extract_features_dir(processed_data_targ)
labels = extract_labels('CSDMC2010_SPAM/SPAMTrain.label')
feature_set = np.conca... |
def CalculateCompositionPolarizability(ProteinSequence: str) -> Dict[Any, Any]:
"""
Calculate composition descriptors based on Polarizability of AADs.
Parameters
----------
ProteinSequence : str
a pure protein sequence
Returns
-------
result : Dict[Any, Any]
contains Co... | The code calculates and compiles seven amino acid property-based composition descriptors from a protein sequence into a dictionary. It aggregates results from polarizability, solvent accessibility, secondary structure, charge, polarity, normalized VDW volume, and hydrophobicity calculations, returning a unified descrip... | def CalculateC(ProteinSequence: str) -> Dict[Any, Any]:
"""
Calculate all composition descriptors based seven different properties of AADs.
Parameters
----------
ProteinSequence : str
a pure protein sequence
Returns
-------
result : Dict[Any, Any]
contains all compositi... |
def CalculateTransitionPolarizability(ProteinSequence: str) -> Dict[Any, Any]:
"""
Calculate Transition descriptors based on Polarizability of AADs.
Parameters
----------
ProteinSequence : str
a pure protein sequence
Returns
-------
result : Dict[Any, Any]
contains Tran... | (CalculateT computes transition descriptors for a protein sequence using seven amino acid properties: polarizability, solvent accessibility, secondary structure, charge, polarity, normalized VDW volume, and hydrophobicity. It aggregates results from seven sub-functions into a dictionary, returning all descriptors for a... | def CalculateT(ProteinSequence: str) -> Dict[Any, Any]:
"""
Calculate all transition descriptors based seven different properties of AADs.
Parameters
----------
ProteinSequence : str
a pure protein sequence
Returns
-------
result : Dict[Any, Any]
contains all transition... |
def CalculateDistributionPolarizability(ProteinSequence: str) -> Dict[Any, Any]:
"""
Calculate Distribution descriptors based on Polarizability of AADs.
Parameters
----------
ProteinSequence : str
a pure protein sequence
Returns
-------
result : Dict[Any, Any]
contains ... | The code calculates and compiles seven distribution descriptors of amino acids (polarizability, solvent accessibility, secondary structure, charge, polarity, normalized VDW volume, hydrophobicity) from a protein sequence into a single dictionary, returning all descriptors for further analysis or feature engineering in ... | def CalculateD(ProteinSequence: str) -> Dict[Any, Any]:
"""
Calculate all distribution descriptors based seven different properties of AADs.
Parameters
----------
ProteinSequence : str
a pure protein sequence
Returns
-------
result : Dict[Any, Any]
contains all distribu... |
def _prep_cave(self, address_start, address_end):
"""
Initialize a kernel code cave where larger patches will reside.
"""
cave_size = address_end - address_start
cave_trap = b'\xCC' * cave_size
self._write_bytes(cave_trap, address_start)
self._current_cave_address... | The main task of the code is to patch the M8 kernel with TITAN by applying a series of predefined patches (INLINE, JUMP, CALL) to specific memory addresses, handling fixups for minor adjustments, and optionally configuring UDMA mode if enabled. It prepares a memory cave, iterates through kernel patches, applies them ba... | def _patch_m8(self):
"""
Patch the M8 kernel with TITAN.
"""
self._prep_cave(0x8003026F, 0x800305C8) # s/o to LoveMhz for the tip
for patch in KERNEL_PATCHES:
patch_name = patch.__name__.split('Patch_')[1] + '(...)'
print(f"[*] - 0x{patch.HOOK_ADDRESS:08X... |
def intersection(ca, cb):
result = tuple((max(a[0], b[0]), min(a[1], b[1])) for a, b in zip(ca, cb))
return result if is_valid(result) else None
def is_in(c1, c2):
return intersection(c1, c2) == c1
def is_valid(cuboid):
return all(c[0] <= c[1] for c in cuboid) | The code splits two overlapping 3D cubes (ca, cb) into non-overlapping sub-cubes by dividing their intersecting region into 27 smaller cubes (3x3x3 grid). It checks which sub-cubes lie entirely within either original cube and filters out invalid ones, returning a list of valid sub-cubes. The task is to partition inters... | def split(ca, cb):
inter = intersection(ca, cb)
if not inter:
return [ca, cb]
result = []
(xa1, xa2), (ya1, ya2), (za1, za2) = ca
(xb1, xb2), (yb1, yb2), (zb1, zb2) = cb
xx = min(xa1, xb1), max(xa1, xb1), min(xa2, xb2) + 1, max(xa2, xb2) + 1
yy = min(ya1, yb1), max(ya1, yb1), min(y... |
def filter_colors(image):
# Filter white pixels
white_threshold = 200
lower_white = np.array([white_threshold, white_threshold, white_threshold])
upper_white = np.array([255, 255, 255])
white_mask = cv2.inRange(image, lower_white, upper_white)
white_image = cv2.bitwise_and(image, image, mask=white_mask)
# Filte... | The code detects lane lines in an image by filtering white/yellow pixels, applying grayscale and CLAHE enhancement, Gaussian blur, Canny edge detection, masking with a trapezoid ROI, Hough Transform for line detection, and separating/drawing left/right lines on the original image. | def line_detect(img_ori):
#leave white and yellow pixels
image = filter_colors(img_ori)
#gray scale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#clahe
clahe = cv2.createCLAHE(clipLimit=5)
img_clahe = clahe.apply(gray)+30
#gaussian smoothing
img_blur = cv2.GaussianBlur(img_clahe, (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.