dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def is_service_dir(dirpath):
if not os.path.isdir(dirpath):
return False
if not os.path.exists(os.path.join(dirpath, 'service.yaml')):
return False
return True
def deploy_service(service_directory, service_name=None):
service_name = service_name or os.path.basenam... | This function recursively deploys service directories by checking if a given root directory is a service directory. If so, it deploys it; otherwise, it processes each subdirectory recursively. It handles exceptions during deployment and logs errors. | def deploy_root_service_dir(rootdir):
if is_service_dir(rootdir):
try:
deploy_service(rootdir)
except Exception as e:
logger.error(e)
elif os.path.isdir(rootdir):
service_directories = os.listdir(rootdir)
for directory in se... |
def make_shape_even(image):
"""Pad the image to have even shapes."""
height, width = image.shape[0], image.shape[1]
padh = 1 if height % 2 != 0 else 0
padw = 1 if width % 2 != 0 else 0
image = jnp.pad(image, [(0, padh), (0, padw), (0, 0)], mode='reflect')
return image
def mod_padding_symmetric(image, factor... | The function processes an image by normalizing, padding, applying a model (with optional ensemble), unpadding, calculating PSNR (if a target exists), and saving results. It handles image augmentation, model inference, and post-processing to restore original resolution, returning the PSNR score. | def _process_file(i):
print(f'Processing {i + 1} / {num_images}...')
input_file = input_filenames[i]
input_img = np.asarray(Image.open(input_file).convert('RGB'),
np.float32) / 255.
if FLAGS.has_target:
target_file = target_filenames[i]
target_img = np.asarray(Imag... |
def get_table(self):
try:
self.connect()
if self.dynamo is None:
return self.dynamo
return self.dynamo.Table('tbo_story_info')
except:
return None
def error_message(self,extra_info=None):
result = {"message" : "Error",'extra_info':e... | This function inserts a story into a DynamoDB table after validating input data structure, checking table existence, and ensuring the story ID is unique. It returns success/failure messages based on validation results and insertion outcomes. | def insert_story(self,reqData):
'''
Inserts story to table
reqData structure for insert
{
'story_id' : 'string',
'story_description' : 'string',
'story_related_pics' : ['string urls'],
'story_comments' : {'user_name+comment_time' : 'entire... |
def get_table(self):
try:
self.connect()
if self.dynamo is None:
return self.dynamo
return self.dynamo.Table('tbo_story_info')
except:
return None
def error_message(self,extra_info=None):
result = {"message" : "Error",'extra_info':e... | This function updates specific fields of a story in a DynamoDB table based on the provided request data. It checks if the story exists, constructs appropriate update expressions for 'story_description', 'story_related_pics', or 'story_comments', and handles conditional checks to prevent duplicate comments. It returns s... | def update_story(self,reqData):
'''
Updates story
reqData structure for update
{
'story_id' : 'string',
'field_updated': 'story_description' or 'story_related_pics' or 'story_comments',
'new_value' : "value from front-end or {'user_name+comment_time' :... |
def get_table(self):
try:
self.connect()
if self.dynamo is None:
return self.dynamo
return self.dynamo.Table('tbo_story_info')
except:
return None
def error_message(self,extra_info=None):
result = {"message" : "Error",'extra_info':e... | The main task of the code is to delete specific elements (comments or related pictures) from a story in a database table based on the provided parameters. It validates the story's existence, constructs appropriate DynamoDB update expressions to remove targeted data, handles conditional checks, and returns success or er... | def delete_story(self,reqData):
'''
reqData structure for delete
{
'story_id' : 'string',
'field_delete': story_related_pics' or 'story_comments',
'delete_value' : "value from front-end or {'user_name+comment_time' : 'entire_comment'}"
}
'''
... |
def get_table(self):
try:
self.connect()
if self.dynamo is None:
return self.dynamo
return self.dynamo.Table('tbo_story_info')
except:
return None
def error_message(self,extra_info=None):
result = {"message" : "Error",'extra_info':e... | The main task of the code is to retrieve a specific story from a database table using the provided story_id. It checks if the table exists, verifies the story_id's existence, handles database errors, and returns the corresponding story item if successful. | def select_story(self,story_id):
table = self.get_table()
if table is None:
return self.error_message("Unable to connect to database")
check_flag = self.story_id_exists(table,story_id)
if check_flag is None:
return self.error_message('Story id does not exists')
... |
def emptySlot():
horizontal=sheet1.min_row+1
vertical=sheet1.min_column+1
slots=[]
slotsNames=[]
for x in range(sheet1.min_row+1,sheet1.max_row+1):
for y in range(sheet1.min_column+1,sheet1.max_column+1):
if len(Weekdays(weekdays)[1]) ==2:
if Weekdays(weekdays)[1]... | The code generates valid subject schedules by combining filtered time slots, ensuring no duplicates, then writes each valid schedule into separate Excel sheets. It handles cases where no schedule is possible and saves the output file. | def PuttingValues():
sheet=book.active
subjects=["Math","Math2","Physics","Csen","Production","Elct"]
emptyS=emptySlot()[1]
subjects_slots = [filter_slots(math),filter_slots(math2),filter_slots(physics),filter_slots(cs),filter_slots(production),filter_slots(elct)]
#the next function generates a lis... |
def emptySlot():
horizontal=sheet1.min_row+1
vertical=sheet1.min_column+1
slots=[]
slotsNames=[]
for x in range(sheet1.min_row+1,sheet1.max_row+1):
for y in range(sheet1.min_column+1,sheet1.max_column+1):
if len(Weekdays(weekdays)[1]) ==2:
if Weekdays(weekdays)[1]... | The main task of the code is to generate valid schedules by combining subject-specific slot lists (after removing holidays) into non-repeating combinations, then writing these schedules into an Excel sheet. It iterates through valid combinations, maps subjects to slots, populates the spreadsheet with subject names, cre... | def PuttingValues():
sheet=book.active
subjects=["math","math2","physics","cs","production","elct"]
emptyS=emptySlot()[1]
a = [removeHolidayS(math),removeHolidayS(math2),removeHolidayS(physics),removeHolidayS(cs),removeHolidayS(production),removeHolidayS(elct)]
options=list(itertools.product(*a))
... |
def updateScoreBoard(winner, outputCheck=False):
jsonName = 'scoreBoard.json'
jsonDefault = {
"playerNames":[],
"playerScore":[]
}
keys = list(jsonDefault.keys())
if not os.path.exists(jsonName):
createJSON(jsonDefault, jsonName)
else:
if not validateJSON(keys, j... | The main task of the code is to display a sorted scoreboard of players and their wins. It updates the score for 'JoJo', retrieves JSON data containing player names and scores, converts it into a list of tuples, sorts the list, and prints the ranked results in a formatted manner. | def showScoreBoard():
updateScoreBoard('JoJo', True)
jsonName = 'scoreBoard.json'
content = getJSONContent(jsonName)
contentList = list(zip(content['playerNames'], content['playerScore']))
sortContent(contentList)
print('Scoreboard:')
for i in range(0, len(contentList)):
print(f' ... |
def get_args():
"""This function parses and return arguments passed in"""
# Assign description to the help doc
parser = argparse.ArgumentParser(
description='Convert images to laser-ready bitmaps using half-toning')
# Add arguments
parser.add_argument("-f", "--file", required=True)
parse... | The main task of the code is to process an image based on user-specified parameters, including resizing, color adjustments (red/green/blue weights, tones), brightness/saturation thresholds, and previewing. It parses command-line arguments, validates input, extracts dimensions, and conditionally applies either a compreh... | def main():
args = get_args()
filepath = args.file
size = args.size
line_gap = float(args.line_gap)
overflow = args.overflow
all_options = args.all_options
minimum_brightness = float(args.minimum_brightness)
percentile_saturation = float(args.percentile_saturation)
brightener = args... |
def get_pagination(request):
from_ = request.params.get('from') or 0
size = request.params.get('limit', 25)
if size in ('all', ''):
size = None
else:
try:
size = int(size)
except ValueError:
size = 25
return from_, size
def search(context, request, sea... | The main task of the code is to generate a report by validating input parameters, querying data via a search function, and formatting the response. It enforces a single valid document type without subtypes, adjusts pagination limits, and modifies the search result structure to represent a report with specific metadata,... | def report(context, request):
doc_types = request.params.getall('type')
if len(doc_types) != 1:
msg = 'Report view requires specifying a single type.'
raise HTTPBadRequest(explanation=msg)
# schemas for all types
types = request.registry[TYPES]
# Get the subtypes of the requested t... |
def get_value(self, state):
"""
Compute your agent's estimate of V(s) using current q-values
V(s) = max_over_action Q(state,action) over possible actions.
Note: please take into account that q-values can be negative.
"""
possible_actions = self.get_legal_actions(state)
... | The main task of the code is to perform a Q-value update using temporal difference learning. It calculates the TD error (delta) as the difference between the observed reward plus discounted future value (V(s')) and the current Q-value. The agent then adjusts its weights using the learning rate, delta, and feature vecto... | def update(self, state, action, reward, next_state):
"""
You should do your Q-Value update here:
Q(s,a) := (1 - alpha) * Q(s,a) + alpha * (r + gamma * V(s'))
"""
# agent parameters
gamma = self.discount
learning_rate = self.alpha
#
# INSERT CO... |
def download_img(url: str) -> Optional[Image.Image]:
import io
from urllib.request import Request, urlopen
try:
with urlopen(Request(url, headers={"User-Agent": "Mozilla/5.0"}), timeout=5) as req:
byte_arr = bytearray(req.read())
except Exception as e:
logger.error(f"Downloa... | The main task of the code is to download an image from a given URL, convert it to grayscale, rescale it, and perform preprocessing checks, returning the processed image as a numpy array if successful or None if any step fails. | def image_from_silhouette_url(url: str) -> Optional[np.ndarray]:
logger.debug(f"Downloading image from {url}")
im = download_img(url)
if im is None:
logger.debug("Image failed to download")
return None
try:
im = grayscale_img(im)
except Exception as e:
logger.debug(f"... |
def check_swapping_css_inputs(Sigma,
k,
num_inits,
max_iter,
S_init,
include,
exclude,
tol):
"""
... | The function `swapping_css` approximately finds a size-$k$ subset of variables from a covariance matrix `Sigma` that minimizes the CSS (Covariance Selection Subset) objective using iterative swapping. It allows specifying mandatory (`include`) and excluded variables (`exclude`), supports multiple random initializations... | def swapping_css(Sigma,
k,
num_inits=1,
max_iter=100,
S_init=None,
include=np.array([]),
exclude=np.array([]),
tol=TOL):
"""
Given a `(p, p)`-covariance matrix `Sigma` uses iterative swapp... |
def check_swapping_subset_factor_inputs(Sigma,
k,
cutoff,
max_iter,
num_inits,
S_init,
... | The function `swapping_subset_factor_selection` identifies a subset of size `k` from a covariance matrix `Sigma` to minimize the sum of log determinants of the residual covariance matrix and the selected subset's covariance. It uses iterative swapping starting from an initial subset, adhering to constraints on included... | def swapping_subset_factor_selection(Sigma,
k,
cutoff,
max_iter=100,
num_inits=1,
S_init=None,
in... |
def deriv(x):
a = 10
while(a>10**-6):
a = (f(x+a)-f(x))/a
return(a)
def newton_step(xi):
xii = f(xi)/deriv(xi)
return xii | The code attempts to iteratively refine a guess using Newton-Raphson method to find a root, appending intermediate values to rootlist. However, it contains logical errors: infinite recursion via self-calls, undefined 'deriv' and 'newton_step' functions, and a flawed convergence condition. The primary task is likely to ... | def newton(guess):
rootlist.append(guess)
rootlist.append(newton(guess))
while(deriv(abs(guess)-newton(guess))>10**-6):
rootlist.append(newton_step()) |
def check(self, type):
"""Look at the current token to see if it matches, but don't
consume it
"""
if self.is_at_end():
return False
return self.peek().tokentype == type
def advance(self):
"""Consume current token and return it"""
if not self.is_at_... | The code's main task is to check if the current token matches the specified type. If it does, the method advances the parser; otherwise, it raises an error with the provided message, indicating a mismatch. This ensures proper syntax validation by verifying expected tokens during parsing. | def consume(self, type, message):
"""Look for the closing paren and report error if some
other token is found
"""
if self.check(type):
return self.advance()
else:
self.error(self.peek(), message) |
def advance(self):
"""Consume current token and return it"""
if not self.is_at_end():
self.current += 1
return self.previous()
def is_at_end(self):
"""Indicate when we've consumed all the tokens"""
return self.peek().tokentype == tokentypes.TokenType.EOF
def pee... | The main task of the code is to synchronize the parser after an error by discarding tokens until it finds either a semicolon or the start of a new statement (e.g., keywords like CLASS, FUN, VAR, etc.), allowing the parser to resume processing from a valid code position. | def synchronize(self):
"""If we encounter an error, discard tokens until we find the
beginning of the next statement
"""
self.advance()
while not self.is_at_end():
if self.previous.type == tokentypes.TokenType.SEMICOLON:
return
t... |
def create_graphs(self):
style.use("seaborn-bright")
self.fig = Figure((6.5, 5), dpi=100)
self.fig.set_tight_layout("tight")
self.ax = self.fig.add_subplot(111)
self._graph_title = "Serial Data: No port selected."
self.canvas = FigureCanvasTkAgg(self.fig, master=self.mas... | The code initializes a GUI application for real-time serial data plotting. It sets up the main window with a title, size, and background, creates graphs and widgets for data visualization, refreshes serial port listings, and starts plotting data. The class manages serial port connections, data storage, and dynamic grap... | def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title("Real Time Serial Data Plot")
self.master.geometry("600x500")
self.master.configure(background="grey")
self.pack()
self.current_port = None
self.current_baud ... |
def binary_image(self, arg, *argv):
# combines multiple binary vectors together to create one binary vector
# arg : first binary vector
# *argv : other binary vectors to be be combined
# return : binary vector same shape as arg
# Combine the two binary thresholds
combine... | This function identifies left and right lane lines in a binary/warped image by either detecting new lines or refreshing existing polynomial fits. It converts multi-channel images to binary, checks for pre-existing lane fits, and uses find_lane_lines or refresh_lane_lines accordingly. Returns quadratic functions represe... | def lane_lines(self, image, plot_line=False):
# finds the location of the lanes lines
# image : image that needs o be search for line. Should be a warped image
# plot_line : True => plots the found lines onto the image for visulisation
# return : quadratics functions of the left and righ... |
def get_ticker_data_from_cache(df: pd.DataFrame, symbol: str) -> pd.DataFrame:
"""
Return ticker data from a dataframe containing all ticker data - lazy function
Args:
df:
symbol:
Returns:
df_sub
"""
df_sub = (
df[df["symbo... | The function generates future buy/sell signals for a given stock using SMA crossover strategies. It extracts historical data, extends it with forecasted days, calculates long-term (50/200) and short-term (10/50) SMA crossovers, identifies crossover positions, and splits results into buy (positive long crossover) and se... | def get_future_signals(
self,
df_all_tickers: pd.DataFrame,
ticker: str,
days_to_forecast: int,
long_signal: str = "50_200",
short_signal: str = "10_50",
) -> (pd.DataFrame, pd.DataFrame):
"""
Get future buy/sell signals for a g... |
def copy(obj):
if isinstance(obj, go.Figure):
import copy
copied = go.Figure(obj)
copied._grid_ref = copy.deepcopy(copied._grid_ref)
if hasattr(obj, "_fit_results"):
copied._fit_results = copy.deepcopy(obj._fit_results)
for trace, trace_copied in zip(
... | The function `vstack` combines multiple figures into a single vertically stacked figure by adjusting their positions and sizes. It copies elements like images, annotations, shapes, and fit results from each input figure into the new combined figure, ensuring proper alignment and spacing. The function iteratively merges... | def vstack(fig, *other_fig, fraction=0.5, vertical_spacing=None):
new_fig = copy(fig)
figs = other_fig
# assert len(figs) == 1
# new_fig_shape = _get_subplot_shape(new_fig)
if vertical_spacing is None:
vertical_spacing = default_total_vertical_spacing / 2
for i, fig in enumerate(figs)... |
def copy(obj):
if isinstance(obj, go.Figure):
import copy
copied = go.Figure(obj)
copied._grid_ref = copy.deepcopy(copied._grid_ref)
if hasattr(obj, "_fit_results"):
copied._fit_results = copy.deepcopy(obj._fit_results)
for trace, trace_copied in zip(
... | The main task of the code is to horizontally stack multiple figures into a single combined figure by aligning them side-by-side. It adjusts subplot positions, scales elements, and merges visual components (images, annotations, shapes) and internal data (fit results) from each input figure into the new figure, ensuring ... | def hstack(fig, *other_figs, fraction=0.5, horizontal_spacing=None) -> go.Figure:
new_fig = copy(fig)
# figs = [other_fig]
figs = other_figs
# assert len(figs) == 1
# new_fig_shape = _get_subplot_shape(new_fig)
if horizontal_spacing is None:
horizontal_spacing = default_total_horizonta... |
def prim_dijkstra(alpha, points, source_set, nearest_neighbours, T):
N = len(points)
keys = [float("inf") for i in range(len(points))]
pathlengths = [float("inf") for i in range(len(points))]
parents = [0 for i in range(len(points))]
visited = [False for i in range(len(points))]
keys[0] = 0
... | The code computes and normalizes the wirelength (WL) and skew of a tree structure generated by the `prim_dijkstra` algorithm. It uses alpha=0 to normalize WL (minimum WL tree) and alpha=1 to normalize skew (minimum radius tree). For a given alpha and source set, it calculates the actual WL and skew, then returns their ... | def solve(N, alpha, source_set, input_df):
# Store the x and y coordinates
X = input_df[[f"x{i}" for i in range(N)]].values[0].tolist()
Y = input_df[[f"y{i}" for i in range(N)]].values[0].tolist()
# Calculate the normalized values:
# Since alpha = 0 yields a minimum WL tree, the wirelength value is... |
def train(
self,
reward_shaping=True,
eps_greedy=True,
initial_time=None,
max_elapsed=float("inf")
):
rewards = []
for episode in range(self.num_episodes):
# Reset the environment
state = self.environment.reset()
episode_rew... | The main task of the code is to select the best vertices by training a reinforcement learning model with optional reward shaping and epsilon-greedy strategies, then refining the solution using local search if specified. It returns the optimized state from local search or the initial state, depending on the refinement f... | def select_best_vertices(
self,
# Whether to include reward shaping during training
reward_shaping=True,
# Whether to include epsilon greedy during training
eps_greedy=True,
# Whether to refine solution from RL with local search
refine_soln=True
):
# ... |
def _accept_new_connection(self) -> None:
client_socket, _ = self._server_socket.accept()
client_socket.setblocking(False)
file_descriptor = client_socket.fileno()
self._client_sockets[file_descriptor] = client_socket
self._requests[file_descriptor] = b''
self._responses[... | The main task of the code is to run an infinite event loop using Linux's `epoll` system call to handle server operations. It listens for I/O events (e.g., new connections, data ready, shutdowns) on sockets, processes them asynchronously, and manages client interactions in a single thread. The loop ensures non-blocking ... | def _start_event_loop(self) -> None:
"""Starts server infinite event loop in which it accepts new conections or reads client data.
This is done using `epoll` linux system call. I/O operations are performed only when there
is data ready to read and therefore all socket reads should be non... |
def restart(self):
self.has_created_game = False
self.board = Board()
self.piece = None
self.black_time_spent = 0
self.white_time_spent = 0
self.user_input = ''
self.active_input = False
self.lobby_index = 0
self.list_start_index = 0
self.i... | This code implements a single-player game loop where the player and AI alternate turns. It handles events like quitting, restarting, and mouse clicks for player moves. If no valid moves remain or time runs out, it displays an ending screen. The AI calculates its best move, updates the game state, and renders the board ... | def singleplayer_game(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.restart()
captures, standard... |
def update_time(self):
time = clock.tick(15)
if self.draw_current_screen != self.singleplayer_game and self.draw_current_screen != self.multiplayer_game: # type: ignore
return
if self.board.moving_side == PieceColor.WHITE:
self.white_time_spent += time
else:
... | This code handles a multiplayer game loop in Pygame, processing events like quitting, receiving opponent moves, generating valid moves, checking game end conditions, handling player input for their turn, updating timers, and rendering the game board with timers for both players. | def multiplayer_game(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.USEREVENT:
if event.name == 'other_player_move':
move = Move.from_string(event.data)... |
def _most_common_label(self, y):
'''
Returns most common label in array of labels, y.
'''
counter = Counter(y)
label = counter.most_common(1)[0][0] # most_common outputs an ordered list of tuples [(1st_most_common_label, count), (2nd_most_common_labe, count)]
return l... | This function recursively constructs a decision tree by checking stopping criteria (sample count, depth, purity), selecting random features, finding optimal splits, and recursively building left/right subtrees. It returns a Node representing either a leaf (with majority label) or an internal node with split details and... | def _grow_tree(self, X, y, depth=0):
'''
Checks to see if any stopping criteria are met.
Otherwise, continues building the decision tree.
'''
n_samples, n_features = X.shape
n_labels = len(np.unique(y))
# Check the stopping criteria
if n_samples<=self.min... |
def _create_clusters(self, centroids):
# Assign each samples to its closest centroid.
clusters = [[] for _ in range(self.K)]
for idx, sample in enumerate(self.X):
centroid_idx = self._closest_centroid(sample, centroids)
clusters[centroid_idx].append(idx)
return cl... | This code implements the K-means clustering algorithm to predict cluster labels for input features. It initializes centroids randomly, iteratively assigns samples to the nearest centroid, updates centroids based on cluster means, and stops when centroids converge. The final output is an array of predicted cluster indic... | def predict(self, X):
'''
Predict label values given array of features X.
Parameters
----------
X: np.array of shape (n_samples, n_features)
Returns
-------
Predictions: 1-d np.array of predicted labels.
'''
self.X = X
self.n_sa... |
def __buildContext(self):
"""
Build context
"""
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.verify_mode = ssl.CERT_REQUIRED
context.load_cert_chain(certfile=self.__server_cert, keyfile=self.__server_key)
context.load_verify_locations(cafi... | The code initializes a secure server by configuring SSL/TLS parameters, loading server certificates and keys, building an SSL context, creating a bound socket, and establishing a connection. It sets up attributes for address, port, certificates, data buffers, and connection status, preparing the server to handle encryp... | def __init__(self,port,serverCert,serverKey,clientsCrt):
"""
Constructor
"""
self.__listen_addr = '127.0.0.1'
self.__listen_port = port
self.__server_cert = serverCert
self.__server_key = serverKey
self.__client_certs = clientsCrt
self.__context ... |
def _pad_img(img, window_size, subdivisions):
aug = int(round(window_size * (1 - 1.0/subdivisions)))
more_borders = ((aug, aug), (aug, aug), (0, 0))
ret = np.pad(img, pad_width=more_borders, mode='reflect')
return ret
def _rotate_mirror_do(im):
mirrs = []
mirrs.append(np.array(im))
mirrs.app... | The function `smooth_windowing` processes an input image using a sliding window approach with multiple transformations (rotations, mirroring) to apply a prediction function (`pred_func`) across overlapping regions. It pads the image, divides it into subdivisions, predicts on each window, reconstructs results, merges tr... | def smooth_windowing(input_img, window_size, subdivisions, nb_classes, pred_func):
pad = _pad_img(input_img, window_size, subdivisions)
pads = _rotate_mirror_do(pad)
res = []
for pad in tqdm(pads):
# For every rotation:
sd = _windowed_subdivs(pad, window_size, subdivisions, nb_classes, p... |
def get_best_action(self, parent):
# calculate UCB1 heuristic for each node in parent's children
ucb1_values = [self.ucb1(child) for child in parent.children]
# determine best action from index of maximum UCB1 value
best_action = parent.children[ucb1_values.index(max(ucb1_values))]
... | The code traverses a tree structure starting from the root node, alternately selecting action nodes (odd depths) or state nodes (even depths). It decides to branch (expand action nodes) or plunge (randomly select child states) based on depth and node type, expanding nodes when necessary. The traversal continues until a... | def traverse(self):
curr_node = self.root
# print("Traversing tree...")
# print("At root node...")
# print("Action for root node: ", self.root.children[0].action)
# While the current node has children or is an action node
while curr_node.children or (curr_node.depth % 2) ... |
def get_houses_dataset(file):
f = open(file,"r")
csv_reader = csv.reader(f, delimiter=',')
count_line = 0
dataset = {}
house_row = -1
for line in csv_reader:
if (count_line == 0):
len_data = len(line)
for row_index in range (0, len(line)):
if (line[row_index] == "Hogwarts House"):
house_row = r... | The main task of the code is to process a dataset file containing Hogwarts house information, generating either a histogram of all houses or a specific subject's distribution graph based on command-line arguments. It validates the input file, parses user-specified lessons from a predefined list, and visualizes data usi... | def main():
lessons = ["Arithmancy", "Astronomy", "Herbology", "Defense Against the Dark Arts",
"Divination", "Muggle Studies", "Ancient Runes", "History of Magic", "Transfiguration",
"Potions", "Care of Magical Creatures", "Charms", "Flying"]
parser = argparse.ArgumentParser()
parser.add_argument("file", help="d... |
def conv_bn_relu(x, filters, size, scale, name):
x = conv(x, filters, size, name)
x = bn_relu(x, scale, name)
return x
def conv_bn(x, filters, size, scale, name):
x = conv(x, filters, size, name)
x = batch_norm(x, scale, name)
return x
def squeeze_excite_block(inp, filters, ratio, name):
... | This function constructs a residual neural network with 'blocks' number of residual blocks. Each block applies two convolutional layers with batch normalization, optionally includes a squeeze-and-excite module, and uses a shortcut connection to add the input tensor. The network progressively transforms the input tensor... | def build_post_net(x, blocks,filters):
for i in range(blocks-1):
inp = x
x = conv_bn_relu(x,filters,3,False,"res"+str(i+1)+"_1")
x = conv_bn(x,filters,3,True,"res"+str(i+1)+"_2")
if USE_SE:
x = squeeze_excite_block(x,filters,filters//32,"res"+str(i+1)+"_se")
x = ... |
def conv_bn_relu(x, filters, size, scale, name):
x = conv(x, filters, size, name)
x = bn_relu(x, scale, name)
return x
def pool_layer(x, name):
x = Permute((3,1,2),name=name+"_permute")(x)
x = GlobalAveragePooling2D('channels_first', name=name+"_avg_pool")(x)
return x
def dense(x, n, name, ac... | This code processes input `x` through convolutional and pooling layers, followed by dense layers to generate a 3-class probability distribution via softmax, likely for evaluating game states in a neural network like AlphaGo. | def value_head(x):
vx = conv_bn_relu(x,128,1,False,"value")
vx = pool_layer(vx,"value")
# value head
x = Flatten(name='value_flatten')(vx)
x = dense(x, 128, "value_dense_1")
x = dense(x, 32, "value_dense_3")
value = dense(x, 3, "value", act='softmax')
return value |
def conv(x, filters, size, name):
x = Conv2D(filters=filters, kernel_size=size,
strides=(1,1), padding="same",
use_bias=False,
kernel_initializer=K_INIT,
kernel_regularizer=L2_REG,name=name+"_conv")(x)
return x
def bn_relu_conv(x, filters... | The main task of the code is to construct a pre-net module with residual blocks. It iteratively applies convolutional layers (with batch normalization and ReLU), squeeze-and-excitation blocks (if enabled), and shortcut connections to build a residual network. The final output is normalized and activated, forming a feat... | def build_pre_net(x, blocks,filters, pol_channels):
for i in range(blocks-1):
inp = x
if i == 0:
x = conv(x,filters,3,"res"+str(i+1)+"_1")
else:
x = bn_relu_conv(x,filters,3,False,"res"+str(i+1)+"_1")
x = bn_relu_conv(x,filters,3,True,"res"+str(i+1)+"_2")
... |
def fill_planes_nnue(iplanes, ivalues, cidx0, cidx1, pid, b):
""" Compute input planes for NNUE training """
cidx0 = fill_planes_nnue_one(iplanes[0,:,:], ivalues[0,:], cidx0, pid, b, b.turn)
cidx1 = fill_planes_nnue_one(iplanes[1,:,:], ivalues[1,:], cidx1, pid, b, not b.turn)
return cidx0,cidx1
def fi... | The code processes a list of chess examples into input/output arrays for a neural network, handling different head types (value, policy, score). It parses FEN strings, adjusts results/values based on player, and fills policy/score arrays with move probabilities. Input planes are generated using chess.Board or FEN parsi... | def fill_examples(examples, spid):
#arrays
N = len(examples)
if HEAD_TYPE == 3:
S = 32 + (32 if NNUE_FACTORIZER else 0) + NNUE_FACTORIZER_EXTRA * 64
iplanes = np.zeros(shape=(2,N*S,2), dtype=np.int32)
ivalues = np.zeros(shape=(2,N*S), dtype=np.int8)
else:
iplanes = np.ze... |
def conv_bn_relu(x, filters, size, scale, name):
x = conv(x, filters, size, name)
x = bn_relu(x, scale, name)
return x
def build_pre_net(x, blocks,filters, pol_channels):
for i in range(blocks-1):
inp = x
if i == 0:
x = conv(x,filters,3,"res"+str(i+1)+"_1")
else:
... | The code constructs a neural network model with a residual tower and multiple heads. It creates an input layer, applies convolutional blocks, builds residual blocks (pre/post-activation), generates a value head, and conditionally adds policy/score heads based on HEAD_TYPE. The model outputs value, policy, and/or score ... | def build_net(main_input_shape, blocks, filters, pol_channels, HEAD_TYPE):
main_input = Input(shape=main_input_shape, name='main_input')
x = main_input
# input convolution block
x = conv_bn_relu(x,filters,3,True,"input")
# residual tower
if USE_PRE_ACTIVATION:
x = build_pre_net(x, bl... |
def fillup_qregs(self, dag):
reg = QuantumRegister(len(self.coupling_map.physical_qubits) - len(dag.qubits), 'r')
dag.add_qreg(reg)
def generate_sabre_layout(self, dag, front_layer, layout):
return self.sabre_swap(front_layer, layout, dag, self.coupling_map)[1]
def generate_heuristic_layout(self... | The main task of the code is to apply a quantum circuit layout optimization strategy (trivial, Sabre, or heuristic) to a DAG-based quantum circuit, generate an initial layout, and then execute the Sabre-swapping algorithm to optimize the circuit's mapping onto a given coupling map, returning the optimized circuit and l... | def run(self, dag):
# append overflow register
self.fillup_qregs(dag)
front_layer = dag.front_layer()
layout: Layout
# get the initial layout from the dag based on different strategies
if (self.layout_strategy == 'trivial'):
layout = Layout.generate_trivial_... |
def init_variable(self):
for i in range(len(self.board)):
for j in range(len(self.board[0])):
if self.board[i][j] == '':
self.unassigned_variables.append((i, j))
self.domains[(i, j)] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def init_constraint(self):
... | This code initializes a constraint satisfaction problem (CSP) solver with configurable strategies for solving puzzles like Sudoku. It sets up variables, constraints, and domains, then selects between backtracking algorithms with optional heuristics: forward checking, pruning filters, and minimum-remaining-values (MLV) ... | def __init__(self, board, forward_checking=False, pruning_filter=False, mlv_ordering=False):
self.step = 0
self.constraint = dict()
self.unassigned_variables = list()
self.variable_assignments = dict()
self.domains = dict()
self.priorities = dict()
self.board = bo... |
def pyramid_align(img1, img2, metric):
if img1.shape[0] < 500:
return get_best_match(img1, img2, metric)
else:
shift = 2 * pyramid_align(rescale(img1, 0.5),
rescale(img2, 0.5),
metric)
return shift + get_best_match(shif... | The code aligns the red and blue channels of a BGR image to a reference green channel coordinate by dividing the image into regions, applying pyramid alignment or best match based on size, calculating adjusted coordinates, and combining them into an RGB image. It returns the aligned image and adjusted coordinates for b... | def align(bgr_image, g_coord):
line = bgr_image.shape[0] // 3
edge = int(0.1 * bgr_image.shape[1])
img_rgb = {
'b': bgr_image[edge: line - edge, edge: -edge],
'g': bgr_image[line + edge: 2 * line - edge, edge: -edge],
'r': bgr_image[2 * line + edge: 3 * line - edge, edge: -edge],
... |
def initial_friend_SC(G, feature, run, dname):
rnd = int(1000*random.random())
print("initial SC seed:", rnd)
random.seed(rnd)
pending = friend_pending(G)
random.shuffle(pending)
full_nodes = set(G.nodes()) - set(pending)
for i in range(5):
for j in pending:
if G.nodes[j... | This function processes a graph and associated data by initializing a subgraph, calculating node ratios, modifying interactions, and post-processing results. It filters input data, adjusts graph structure with specific strategies, and saves processed outputs. | def RC(sample, capital_full, G_full, likers, p_as, i, attack_sir, attack_state, attack_report, dname, out, feat=0):
capital = capital_full.loc[sorted(sample)]
G = nx.Graph(G_full.subgraph(sorted(sample)))
print('RC:')
G = initial_friend_SC(G, 'relational', i, dname)
print('RC:')
print('Full rati... |
def initial_friend_SC(G, feature, run, dname):
rnd = int(1000*random.random())
print("initial SC seed:", rnd)
random.seed(rnd)
pending = friend_pending(G)
random.shuffle(pending)
full_nodes = set(G.nodes()) - set(pending)
for i in range(5):
for j in pending:
if G.nodes[j... | The main task of the code is to process a subgraph of a social network by initializing friend relationships, calculating the proportion of 'full' nodes, simulating interactions (e.g., likes, attacks), and post-processing results for analysis. It operates on sampled nodes, leveraging graph structures and metadata to mod... | def STC(sample, capital_full, G_full, likers, p_as, i, attack_sir, attack_state, attack_report, dname, out, feat=1):
capital = capital_full.loc[sorted(sample)]
G = nx.Graph(G_full.subgraph(sorted(sample)))
print('STC:')
G = initial_friend_SC(G, 'human', i, dname)
print('STC:')
print('Full ratio:... |
def initial_friend_SC(G, feature, run, dname):
rnd = int(1000*random.random())
print("initial SC seed:", rnd)
random.seed(rnd)
pending = friend_pending(G)
random.shuffle(pending)
full_nodes = set(G.nodes()) - set(pending)
for i in range(5):
for j in pending:
if G.nodes[j... | The function processes a subgraph of a social network (G) and associated capital data (capital) for a specific task (CC). It filters nodes based on the sample, applies cognitive and interaction models (initial_friend_SC, interaction_SC), calculates the ratio of 'full' nodes in the graph, and performs post-processing to... | def CC(sample, capital_full, G_full, likers, p_as, i, attack_sir, attack_state, attack_report, dname, out, feat=2):
capital = capital_full.loc[sorted(sample)]
G = nx.Graph(G_full.subgraph(sorted(sample)))
print('CC:')
G = initial_friend_SC(G, 'cognitive', i, dname)
print('CC:')
print('Full ratio... |
def initial_friend_SC(G, feature, run, dname):
rnd = int(1000*random.random())
print("initial SC seed:", rnd)
random.seed(rnd)
pending = friend_pending(G)
random.shuffle(pending)
full_nodes = set(G.nodes()) - set(pending)
for i in range(5):
for j in pending:
if G.nodes[j... | The function processes a subgraph of a social network by initializing friend relationships, analyzing interaction patterns, calculating the ratio of 'full' nodes, and post-processing data for a specific task like attack simulation or social network analysis, using parameters such as sample nodes, capital data, and inte... | def SC(sample, capital_full, G_full, likers, p_as, i, attack_sir, attack_state, attack_report, dname, out, feat=3):
capital = capital_full.loc[sorted(sample)]
G = nx.Graph(G_full.subgraph(sorted(sample)))
print('SC:')
G = initial_friend_SC(G, 'capital', i, dname)
print('SC:')
print('Full ratio:'... |
def initial_friend_TP(G, topics, run, dname):
rnd = int(1000*random.random())
print("initial TP seed:", rnd)
random.seed(rnd)
# adjacency matrix to save similarity
size = max(G.nodes()) + 1
product_matrix = np.zeros((size, size))
for x in G.nodes():
dot_x = topics.loc[x]
for... | This function processes a graph and associated data by initializing friend relationships, calculating a 'full' node ratio, modeling interactions, and post-processing results. It filters a subgraph, applies topic-based transformations, and outputs processed data for analysis. | def TP(sample, capital_full, G_full, likers, topics, p_as, i, attack_sir, attack_state, attack_report, dname, out, feat=6):
capital = capital_full.loc[sorted(sample)]
G = nx.Graph(G_full.subgraph(sorted(sample)))
print('TP:')
G = initial_friend_TP(G, topics, i, dname)
print('TP:')
print('Full ra... |
def initial_friend_SA(G, run, dname):
rnd = int(1000*random.random())
print("initial SA seed:", rnd)
random.seed(rnd)
# adjacency matrix to save similarity
size = max(G.nodes()) + 1
product_matrix = np.zeros((size, size))
for x in G.nodes():
dot_x = [G.nodes[x]['human'], G.nodes[x][... | The function performs a social analysis (SA) on a graph subset, initializing friend relationships, calculating the 'full' node ratio, simulating interactions, and post-processing results. It processes a sampled graph, modifies node relationships, evaluates network completeness, and outputs processed data for analysis. | def SA(sample, capital_full, G_full, likers, p_as, i, attack_sir, attack_state, attack_report, dname, out, feat=5):
capital = capital_full.loc[sorted(sample)]
G = nx.Graph(G_full.subgraph(sorted(sample)))
print('SA:')
G = initial_friend_SA(G, i, dname)
print('SA:')
print('Full ratio:', len([n fo... |
def initial_friend_TR(G, run, dname):
rnd = int(1000*random.random())
print("initial TR seed:", rnd)
random.seed(rnd)
pending = friend_pending(G)
random.shuffle(pending)
full_nodes = set(G.nodes()) - set(pending)
for i in range(5):
for j in pending:
if G.nodes[j]['edges'... | The function TR processes a subgraph and associated data by filtering nodes, calculating node attributes, applying interaction transformations, and post-processing results. It subsets a graph (G) and capital data based on a sample, computes a "full ratio" metric, modifies the graph with interaction rules, and outputs p... | def TR(sample, capital_full, G_full, likers, p_as, i, attack_sir, attack_state, attack_report, dname, out, feat=4):
capital = capital_full.loc[sorted(sample)]
G = nx.Graph(G_full.subgraph(sorted(sample)))
print('TR:')
G = initial_friend_TR(G, i, dname)
print('TR:')
print('Full ratio:', len([n fo... |
def read_csv_files(self) -> list[pl.DataFrame]:
entity_columns = ["entity1", "relation", "entity2"]
corpus_columns = ["entity1", "description"]
def read_entity_file(file_name: str, entity_columns=entity_columns) -> pl.DataFrame:
return pl.read_csv(f"{self.root}/{file_name}", sep="\t... | This code processes CSV data into PyTorch Geometric graph tensors. It reads datasets, transposes entity IDs, splits data into train/validate/test sets, converts edges to tensors, creates node ID tensors, applies filters/transformations, collates data, and saves processed tensors and corpus text for graph-based machine ... | def process(self):
datasets, corpus_text = self.read_csv_files()
datasets, self.corpus_text = self.transpose_entity_ids_to_range(datasets, corpus_text)
train_data, validate_data, test_data = datasets
# PyG needs data as torch tensors of longs
train_edges = torch.tensor(self.get... |
def generate_blank_schedule(self, start_date, end_date):
'''
Generate a blank schedule
Input:
* start_date (datetime obj): the starting date for the schedule
* end_date (datetime obj): the ending date for the schedule
Output:
* days (dict): dicti... | The main task of the code is to initialize a Schedule object by setting up a blank schedule structure between the provided start and end dates, configuring sleep/energy preferences, and initializing empty lists for events and tasks. It extracts sleep parameters from input preferences, creates a Preferences object, and ... | def __init__(self, schedule_start_date, schedule_end_date, preferences, events = [], tasks = []):
'''
Initialize a Schedule object
Inputs:
* start_date (datetime obj): the starting date for the schedule
* end_date (datetime obj): the ending date for the schedule
... |
def check_unload(self,sp):
self.set_mapping_stress(sp)
self.set_parameters(sp)
self.set_parameter_nm(sp)
self.set_parameter_TZ(sp)
dL1 = np.einsum("ij,ij",sp.Tij,sp.dstrain)
if dL1 < 0.0:
elastic_flag1 = True
self.alpha = np.copy(sp.rij)
e... | The function computes plastic deformation by first checking unloading conditions, calculating plastic stiffness, solving for strain/stress with constant stiffness, updating state parameters, and returning the resulting deformation and updated state parameters. | def plastic_deformation(self,dstrain_given,dstress_given,deformation,sp0):
ef1,ef2 = self.check_unload(sp0)
sp = StateParameters(self.strain,self.stress,dstrain_given,dstress_given,ef1=ef1,ef2=ef2)
Ep = self.plastic_stiffness(sp)
dstrain_ep,dstress_ep = self.solve_strain_with_consttain(d... |
def elastic_deformation(self,p,dstrain,dstress,deformation):
Ee = self.elastic_stiffness(p)
dstrain_elastic,dstress_elastic = self.solve_strain_with_consttain(dstrain,dstress,Ee,deformation)
return dstrain_elastic,dstress_elastic
def yield_surface(self,stress,evp):
p,R = self.set_stress_... | The code computes plastic deformation by first determining elastic deformation, then checking if the material is within the yield surface or undergoing unloading. If not, it calculates plastic loading using stiffness and solves for strain with constant stress, returning the resulting strains, stresses, and plastic stra... | def plastic_deformation(self,p,dstrain_given,dstress_given,deformation):
# 1. elastic deformation
dstrain_elastic,dstress_elastic = self.elastic_deformation(p,dstrain_given,dstress_given,deformation)
stress = self.stress + dstress_elastic
evp = np.copy(self.evp)
# 2. check yield... |
def isotropic_compression(self,e0,compression_stress,nstep=1000):
dcp = compression_stress / nstep
self.e = np.copy(e0)
dstress_vec = np.array([dcp,dcp,dcp,0,0,0])
dstress = self.vector_to_matrix(dstress_vec)
for i in range(0,nstep):
p,_ = self.set_stress_variable(s... | This code simulates triaxial compression testing on a material, calculating stress-strain responses and plastic deformation. It applies incremental strain (de), updates stress states, tracks shear strain (gamma), stress ratio (R), and void ratio (ev) over (emax/de) steps. Results are optionally printed or plotted to vi... | def triaxial_compression(self,e0,compression_stress,de=0.0001,emax=0.20,print_result=False,plot=False):
self.isotropic_compression(e0,compression_stress)
self.e0 = np.copy(e0)
self.e = np.copy(e0)
p,_ = self.set_stress_variable(self.stress)
self.beta,self.H2 = p,p
nstep... |
def isotropic_compression(self,compression_stress,nstep=1000):
dcp = (compression_stress - self.p0) / nstep
dstress = np.diag(np.array([dcp,dcp,dcp]))
p = self.p0
self.e = np.copy(self.e0)
ev,evp = 0.0,0.0
for i in range(0,nstep):
deve = self.kappa/(1.+self.... | This function performs triaxial compression simulations by applying incremental strain, calculating stress-strain responses, plastic deformation, and yield surface evolution. It initializes isotropic compression, then applies deviatoric strain steps, updates stress/strain states, tracks shear strain (gamma), deviatoric... | def triaxial_compression(self,compression_stress,de=0.0002,emax=1.00,print_result=False,plot=False):
print("+++ initial compression +++")
self.isotropic_compression(compression_stress)
self.e_init = np.copy(self.e)
print("+++ triaxial compression +++")
nstep = int(emax/de)
... |
def enter_position(self, *positions: str):
"""
Enters all positions given, into positions input
Args:
*positions (str): Positions that you look for
"""
for pos in positions:
self.get_position_input_field().click()
self.get_position_input_field(... | The code automates job search by entering multiple positions and locations into input fields, submitting the form, clearing the inputs, and returning a ResultPage object containing the job search results. | def search_for_job(self, positions: list[str], locations: list[str]) -> ResultPage:
"""
Method which enters all information given into input fields, submits, and clears the form
Args:
positions (list[str]): positions to be entered
locations (list[str]): locations to be en... |
def setInitialData(self, teachers_data: tuple, subjects_data: tuple) -> None:
"""
Set the initial data of the graph
:param teachers_data: Tuple in format (teachers: list, subjects_offered: list, subjects: list)
:param subjects_data: Tuple in format (subjects_info: list, num_of_classes: ... | The code's main task is to process teacher and subject data from CSV files, initialize internal data structures, and compute successful shortest paths between nodes 0 and (num_vet - 1) to format and analyze the dataset, likely for optimizing teacher-subject assignments or scheduling. | def run(self, teachers_file: str, subjects_file: str) -> None:
"""
Script main function
:param teachers_file: name of the csv teachers file in /dataset
:param subjects_file: name of the csv subjects file in /dataset
"""
self.setInitialData(self.readTeachers(teachers_file... |
def normalize(self, image: np.ndarray):
return cv2.normalize(
image, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.COLOR_GRAY2BGR
)
def multi_scale(self, sigmas: list[float] = [15, 80, 250], normalize: bool = False):
msr = np.zeros_like(self.image, dtype=np.float64)
for u in sigma... | This function performs multi-scale color restoration on an image by combining multi-scale processing with color correction. It normalizes the image using parameters like sigma_scales, alpha, beta, and applies color balancing to enhance color fidelity and detail. The result is a restored image with improved color accura... | def multi_scale_color_restoration(
self,
sigma_scales: list[float] = [15, 80, 250],
alpha: float = 125,
beta: float = 46,
G: float = 192,
b: float = -30,
low_per: float = 1,
high_per: float = 1,
):
self.image = self.image.astype("float64") + 1.... |
def is_x_inside(self, x) -> bool:
if x >= 0 and x <= self.x_bound:
return True
return False
def is_y_inside(self, y) -> bool:
if y >= 0 and y <= self.y_bound:
return True
return False
def update_map(self, action: CameraAction):
if action == CameraAction.L... | This function moves a camera in a specified direction (left, right, up, down) if within bounds, updates its position, and checks if 90% of white pixels are visible. It returns True when the camera has viewed at least 90% of all white pixels. | def perform_action(self, action: CameraAction) -> bool:
action_succes = False
if action == CameraAction.LEFT:
if self.is_x_inside(self.position[0] - self.step):
self.position[0] -= self.step
action_succes = True
elif action == CameraAction.RIGHT:
... |
def new_section(self, text:str) -> dict:
"""
Creates a new section under the root node
:param text: Title for the new Section
:type text: str
:returns: dict of section info
:rtype: dict
"""
section_id = self._gen_id()
section = {
'id... | This function creates a new node in a hierarchical tree structure by determining the appropriate node type (section, document, or idea) based on the depth of the parent node. It routes creation to `new_section`, `new_document`, or `new_idea` methods depending on the parent's depth, ensuring proper nesting and metadata ... | def new_node(self, # pylint: disable=too-many-arguments
parent_id:str, text:str,
idea_type:str="", note:str="",
color:str="", color_theme_type:str=""
) -> dict:
"""
Generic node creator
"""
parent_depth = len(self.tree_paths[parent_id])
if parent_dep... |
def _reset_state(self) -> None:
"""
Reset internal data
The internal data structures are documented more
extensively in the README
file_data, nodes
The contents of files and changes to be written
Do not overload with internal data
structure, filename... | The main task of the code is to reset internal data structures and reload them from Mindly files in the specified directory. It first clears existing data via _reset_state(), then sequentially loads index data, sections, and documents using _load_index(), _load_sections(), and _load_documents(). This method initializes... | def load_files(self) -> None:
"""
Sets internal data to empty, then runs setup methods
to populate them from Mindly files in data_dir
Is run in __init__ and can be called to reset and reload
"""
# Set empty internal data
self._reset_state()
# Populate i... |
def _set_defaults(self) -> None:
self.proxy_defaults = {
'section': '',
'hasNote': False,
'hasWebLink': False,
'color': "blue0"
}
self.idea_defaults = {
'ideaType': 1,
'note': '',
'color': "blue0",
'... | The main task of the code is to initialize an object by setting up a data directory path, tracking modified files, applying default configurations, resetting internal state, and loading Mindly data from the specified directory. | def __init__(self, data_dir:str|os.PathLike):
"""
Set initial state, then load Mindly data
:param data_dir: path to Mindly data
:type data_dir: str|os.PathLike
"""
self.data_dir = data_dir
# keys are filenames marked as having changes to be written
self... |
def mean_case_length(case_json):
"""
Returns the average length of cases (in sentences)
case_json: dict with fields case_name, case_summary, score
"""
lengths_list = list()
for case in case_json:
length_of_text = len(sent_tokenize(case['case_summary']))
lengths_list.append(lengt... | The function `wrap_summary` calculates the average and standard deviation of case lengths from the input results and uses these statistics to summarize the cases. | def wrap_summary(results):
avg = mean_case_length(results)
std_dev = std_dev_case_length(results)
return summarize_cases(results, avg, std_dev) |
def wait_load_elem(self, element, timeout=10):
for _ in range(timeout):
try:
var = self.driver.find_element_by_xpath(element)
if var.location_once_scrolled_into_view:
return var
except:
sleep(1)
def find_elem(self, eleme... | The code locates a web element using XPath containing the specified text, verifies its presence and load status, clicks it if found, and returns True upon successful interaction. | def click_by_text(self, text):
element = f"//*[contains(text(), '{text}')]"
if self.wait_load_elem(element) and self.find_elem(element) and self.click(element):
sleep(1)
return True |
def isBlockExist(self, selection, option=None):
if selection == "ApplyStandardization" or selection == "ApplySelectedStandardization":
for block in self.model["Blocks"]:
if block["Category"] == "Transform":
attributes = processComplexJson(block["Attributes"])
... | The function creates or modifies a transformation block in a data pipeline based on the specified operation (e.g., standardization, outlier removal, null handling). It checks if an existing block matches the selection and parameters, updates it if found, or generates a new block with unique attributes like transformati... | def addTransformationBlock(self, selection, params):
option = None
if params:
if "replaceoptions" in params:
option = params["replaceoptions"]
block = self.isBlockExist(selection, option)
if block:
if "Selected" in selection:
column... |
def DataSelection(self, dataset):
self.X_train = None
self.X_test = None
self.y_train = None
self.y_test = None
self.scores = None
return self.jsonModel.addDataBlock(dataset)
def returnRes(self, action):
if action:
return {"messageType": "Info", "mess... | The code processes input text by detecting intent, updating internal state, and executing corresponding actions like data selection, transformation, model selection, or block removal. It handles repeated text by resetting state and returns results based on detected intent. | def process(self, text):
if self.text == text:
self.text = ""
ActionItem = detect_intent(text)
if (ActionItem["Action"] == "DataSelection"):
self.DataSelection(ActionItem["value"])
return self.returnRes(ActionItem)
self.text = text
... |
def get_folder_script_path():
folder_script_path_relative = os.path.dirname(__file__)
folder_script_path = os.path.realpath(folder_script_path_relative)
return folder_script_path
def get_config_data(path_file_config):
"""get default configuration data from file config.ini
Returns:
dict: c... | The code processes a folder to split its contents into independent ZIP files based on a configuration file. It reads settings like file size, mode, ignored extensions, and output directory. The loop prompts for input folders, validates paths, and executes the ZIP splitting using the `run` function. After each operation... | def main():
folder_script_path = get_folder_script_path()
path_file_config = os.path.join(folder_script_path, "config.ini")
config_data = get_config_data(path_file_config)
mb_per_file = int(config_data["file_size"])
mode = config_data["mode"]
ignore_extensions = config_data["ignore_extensions"... |
def refuel_zerius(self):
w3 = self.w3(ZERIUS_SOURCE_CHAIN)
self.wait_for_eth_gas_price(w3)
balance = w3.eth.get_balance(self.address)
balance = int_to_decimal(balance, NATIVE_DECIMALS)
eth_gas_mult = int_to_decimal(self.w3('Ethereum').eth.gas_price, 9) / 30 * 1.5
if ZE... | The code bridges ETH from Ethereum to another network via Zora's bridge. It checks balance, estimates fees, ensures sufficient funds, selects a random amount, and sends a deposit transaction using the Zora Bridge contract, returning success status upon completion. | def bridge(self):
if REFUEL_WITH_ZERIUS:
return self.refuel_zerius()
w3 = self.w3('Ethereum')
contract = w3.eth.contract(ZORA_BRIDGE_ADDRESS, abi=ZORA_BRIDGE_ABI)
balance = w3.eth.get_balance(self.address)
balance = int_to_decimal(balance, NATIVE_DECIMALS)
... |
def draw_word():
# Draw the word with dashes for unrevealed letters
display_word = ""
for char in secret_word:
if char in guesses:
display_word += char
else:
display_word += "-"
canvas.create_text(200, 350, text=display_word, font=("Helvetica", 20), fill="black")
... | This function handles a user's letter guess in a Hangman game. It checks if the guessed letter is in the secret word, updates the guess history, and updates the display. If correct, it shows the letter in the word; if incorrect, it increments the attempt count and draws the gallows. On the final incorrect guess, it dis... | def handle_guess(event):
# Get the guessed letter
guessed_letter = entry.get().lower()
entry.delete(0, tk.END)
# Check if the guessed letter is correct
if guessed_letter in secret_word:
guesses.append(guessed_letter)
draw_word()
else:
# Incorrect guess
incorrect_... |
def red_moves(self) -> bool:
""" True if red makes the next move """
return self.moves % 2
def blue_wins(self) -> bool:
""" True if a winning position for blue """
if self.use_uf:
return self.uf.find(self.blue_top_idx) == self.uf.find(self.blue_bot_idx)
else:
... | The function checks if the game has ended by evaluating either the game_over flag or determining the winner based on the current player's move. It returns True if the game is over, either because the game_over flag is set or if the current player (red or blue) has met the winning conditions. | def is_game_over(self):
""" True if game is finished """
return self.game_over or (self.blue_wins() if self.red_moves() else self.red_wins()) |
def is_in_board(self, q:int|hexpex.Axial, r:int|None=None) -> bool:
""" Checks that hex board position within the current board """
q, r = (q.q, q.r) if r is None else (q, r)
if True:
return q >= -self.hsize and q <= self.hsize and\
r >= -self.hsize and r <= self.h... | This function processes a move in a hexagonal game by validating the move's coordinates, updating the game board with the current player's piece, modifying the union-find structure for connectivity tracking, and checking if the game has ended. It returns True if the move is valid and successfully executed, otherwise Fa... | def make_move(self, q:int, r:int) -> bool:
""" Change game state given the next move """
if self.game_over:
print('No moves: game over')
return False
if not self.is_in_board(q, r) or self.cell_color(q, r) != 0:
print(f'Bad move: {q:+d} {r:+d} {self.is_in_board... |
def log_vram(txt=""):
alloc = torch.cuda.memory_allocated(0)
logging.debug(f"{txt} VRAM: {alloc*1e-9:5.3f}GB")
def simple_merge(
thetas: Dict[str, Dict],
weights: Dict,
bases: Dict,
merge_mode: str,
precision: int = 16,
weights_clip: bool = False,
device: str = "cpu",
work_device... | This function merges multiple neural network models using a rebasin approach, iteratively combining weights and bases, aligning parameters via permutation matching, and normalizing alpha values to update the merged model. It applies specified merge modes, handles precision settings, and optionally clips weights, return... | def rebasin_merge(
thetas: Dict[str, os.PathLike | str],
weights: Dict,
bases: Dict,
merge_mode: str,
precision: int = 16,
weights_clip: bool = False,
iterations: int = 1,
device="cpu",
work_device=None,
threads: int = 1,
):
# WARNING: not sure how this does when 3 models are... |
def load_thetas(
models: Dict[str, os.PathLike | str],
prune: bool,
device: str,
precision: int,
) -> Dict:
log_vram("before loading models")
if prune:
thetas = {k: prune_sd_model(load_sd_model(m, "cpu")) for k, m in models.items()}
else:
thetas = {k: load_sd_model(m, device)... | The function merges multiple models using specified weights and bases, applying either 'rebasin' or 'simple' merging methods. It loads model parameters, processes them based on the merge mode, and returns the merged model with pruning adjustments. Key parameters include merge mode, precision, clipping, and device setti... | def merge_models(
models: Dict[str, os.PathLike | str],
weights: Dict,
bases: Dict,
merge_mode: str,
precision: int = 16,
weights_clip: bool = False,
re_basin: bool = False,
iterations: int = 1,
device: str = "cpu",
work_device: Optional[str] = None,
prune: bool = False,
... |
def refresh_assets_info(assets_list):
cursor, connection = None, None
try:
connection = psycopg2.connect(host=hostname, dbname=database, user=username, password=pwd, port=port_id)
cursor = connection.cursor()
assets_id_in_db = get_assets_id_in_db("all")
for asset in assets_list:... | The main task of the code is to retrieve active asset data from a JSON file, filter it against existing database records, format the datapoints, and transfer them to a database. It reads 'assets.json', checks which assets are "active" in the DB, prepares their datapoints in a structured format, and inserts them into th... | def add_new_datapoints_to_db():
print("\nStarted script")
astInf = open('jsonFiles/assets.json')
assets_list = json.load(astInf)
refresh_assets_info(assets_list)
active_assets_id = get_assets_id_in_db("only_used_assets")
assets_data = []
for asset in assets_list:
if int(assets_list[f... |
def header(self):
"""
Console Interface Header Function
"""
line = '-' * 50
print('\n' + line)
print(f'IFDT - Document Type {self.doc_type} Processing..')
print(line)
def config_files(self):
"""
Function to define and process config information.
... | The main task of the code is to orchestrate a process by sequentially calling three functions: displaying a header, configuring files, and selecting a document type. It serves as a control function to initialize setup and user input steps for subsequent operations. | def main(self):
"""
Main function to call all other functions!
"""
self.header()
self.config_files()
self.doc_type_select() |
def drawBoard(board):
print(" 1 2 3")
print("")
print(board["1a"] + " | " + board["2a"] + " | " + board["3a"] + " A")
print("-----------")
print(board["1b"] + " | " + board["2b"] + " | " + board["3b"] + " B")
print("-----------")
print(board["1c"] + " | " + board["2c"] + " | " + board[... | The main task of the code is to run a tic-tac-toe game where the player and computer alternate turns based on a coin flip. If the player starts, they input moves, and the computer responds; if the computer starts, it moves first, followed by the player. The game checks for a three-in-a-row win or a full board to end th... | def main():
global board
drawBoard(board)
print("Coinflip to determine if either computer or player may start...")
coinflip = random.choice([0, 1, 0, 1, 0, 1, 0, 1, 0, 1])
if coinflip == 0:
print("Player may start...")
while not isThreeinaRow(board) and not boardDone(board):
... |
def formulate(self):
'''
Formulates the given parameters modifies the self.unobserved and self.given lists.
The formula itself is just for display purposes, the calculation is done using the
given and unobserved variables.
@returns
the string represention of the formula e.g. 2 4 3 4 4 as P(-A^+E)
... | The code solves a conjunction by first formulating it. If valid, it constructs a formula from nodes, computes summations using a function `f` with unobserved variables, and returns the result. If invalid, it returns `None`. The task involves validating input, generating logical expressions, and calculating summations f... | def solve(self):
'''
Solves the conjunction.
'''
# Formulates the given values
self.conj = self.formulate()
# if the conjuction is valid
if not self.conj == "ERROR: BAD QUERY":
# build the formula
formula = []
for node in self.nodes:
formula.append(node.get_formula())
# calculate the summ... |
def _maj_c(self,y):
occurence_count = Counter(y)
return occurence_count.most_common(1)[0][0]
def _find_best_feature_and_thr(self,X,y):
IG = -1
for i in range(len(X[0])):
for j in range(len(y)):
leftind_temp,rightind_temp,tempIG = self._information_gain(X[:,i]... | This function recursively constructs a decision tree by splitting data based on the best feature and threshold. It stops creating child nodes when the dataset is too small, maximum depth is reached, or all labels are the same. It assigns feature/threshold to the current node and recursively builds left/right subtrees f... | def _maketree(self,X,y,node,depth):
if len(X) < self.min_Node_split or depth > self.max_depth or len(np.unique(y)) == 1:
node.class_value(self._maj_c(y))
return
feaure_idx, best_thr, leftind, rightind = self._find_best_feature_and_thr(X,y)
node.feature = feaure_idx
... |
def show_boards(self):
for i in range(0, self.num_queens):
for board in self.boards:
print(str(board.getMap()[i]).replace(",", ""), end=" ")
print()
def show_fitness(self):
for board in self.boards:
board.genetic_fitness()
fitness_string... | The code runs a genetic algorithm iteratively up to a maximum number of steps to find a solution. It displays board states, fitness values, and progress at each step. If no solution is found within the step limit, it outputs a message indicating failure. | def find_a_solution(self):
while (self.no_steps < self.max_steps):
print("Step #" + str(self.no_steps))
self.show_boards()
self.show_fitness()
self.set_fitness()
self.show_states()
self.genetic_algorithm()
self.no_steps += 1
... |
def partA(self):
print("\nPart A. The sampling probabilities")
print("P(C|-s,r) = <0.8748, 0.1252>")
print("P(C|-s,-r) = <0.3103, 0.6897>")
print("P(R|c,-s,w) = <1,0>")
print("P(R|-c,-s,w) = <1,0>")
def partB(self):
print("\nPart B. The transition probability matrix")
... | The code initializes a Markov model with a transition matrix defining state probabilities and executes MCMC simulations. It sets up parameters via partA/partB methods, then runs MCMC to generate probabilistic state sequences, likely for statistical analysis or prediction tasks. | def __init__(self):
self.transition = [["S1", .34485, .5, .15515, 0],
["S2", 0, .5626, 0, .4374],
["S3", .34485, 0, .15515, .5],
["S4", 0, .0626, 0, .9374]]
sel... |
def handle_recognize(replyText,callerId,call_connection_id,context=""):
play_source = TextSource(text=replyText, voice_name="en-US-NancyNeural")
recognize_result=call_automation_client.get_call_connection(call_connection_id).start_recognizing_media(
input_type=RecognizeInputType.SPEECH,
target_part... | The function processes communication events in a call automation system, handling speech recognition, intent detection, agent escalation, and call transfers. It logs events, extracts caller data, uses AI to analyze speech, and triggers actions like playing messages or transferring calls based on event types and conditi... | def handle_callback(contextId):
try:
global caller_id , call_connection_id
app.logger.info("Request Json: %s", request.json)
for event_dict in request.json:
event = CloudEvent.from_dict(event_dict)
call_connection_id = event.data['callConnectionId']... |
def get_hallucinations(self, document_ents, summary_ents, document_tokens):
"""
Check for entities that appear in summary but not in documents
"""
hallucinated_entities = list()
if len(summary_ents) == 0:
return hallucinated_entities
# Prepare dictonary of e... | This code identifies and corrects hallucinations in a summary by replacing or removing entities not present in the document. It processes input features, detects hallucinations, applies correction methods based on the specified type, updates the summary and associated tokens/entities, and marks whether corrections were... | def correct_hallucinations(self, features):
"""
Map function wrapper
"""
document = features["document"]
summary = features["summary"]
orig_summ = summary
document_tokens = features["document_tokens"] if "document_tokens" in features else None
summary_to... |
def get_open_data_params_schema(
self, data_id: Optional[str] = None
) -> JsonObjectSchema:
self._assert_valid_data_id(data_id, allow_none=True)
params = dict(
subset=JsonObjectSchema(), # TODO make the subset schema stricter
bbox=JsonArraySchema(
ite... | This function fetches and processes a dataset from a specified URL using OGC parameters. It validates input parameters, constructs a request, retrieves data via HTTP GET, temporarily stores the response, loads it into an xarray Dataset, and returns it. Optional parameters allow saving the dataset in Zarr format. Error ... | def open_data(self, data_id: str, **open_params) -> xr.Dataset:
# Unofficial parameters for testing, debugging, etc.
# They're not in the schema so we remove them before validating.
read_file_from = open_params.pop("_read_file_from", None)
save_file_to = open_params.pop("_save_file_to", ... |
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def collect_categories(datapoints: list):
global bench_types
global shapes
for dp in datapoints:
if not dp["has_flops"]:
continue
bench_type = dp["type"]
bench_types.append(bench_type)
if... | The main task of the code is to process input JSON data, filter entries based on 'has_flops' and implementation type, and generate categorized data files for benchmark types. It reads input from a file or stdin, collects categories, filters datapoints, and writes filtered results to separate files for each benchmark ty... | def main():
if len(sys.argv) < 2:
eprint(f"Usage: {sys.argv[0]} <json>")
sys.exit(1)
input_file = sys.argv[1]
if input_file == "-":
json_data = "\n".join(sys.stdin.read())
datapoints = json.loads(json_data)
else:
datapoints = json.load(open(input_file))
col... |
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def collect_categories(datapoints: list):
global impls
global compilers
global flags
global bench_types
global shapes
for dp in datapoints:
impls.append(dp["impl"])
if not dp["has_flops"]:
flag... | The code processes JSON input data to generate filtered data files for different implementation and benchmark type combinations. It reads input from a file or stdin, filters datapoints by implementation and benchmark type, then writes results to files with optional prefix. The main task is to prepare benchmark data for... | def main():
if len(sys.argv) < 2:
eprint(f"Usage: {sys.argv[0]} <json> [<prefix>]")
sys.exit(1)
input_file = sys.argv[1]
prefix = ""
if len(sys.argv) >= 3:
prefix = sys.argv[2] + "-"
if input_file == "-":
json_data = "\n".join(sys.stdin.read())
datapoints ... |
def print_header(name):
eprint(f"\033[32;1m{name}\033[0m")
def gen_shape_scenes(conf : Config, temp_dir):
for shape in conf.shapes:
for num_shapes in conf.range_func(shape):
fname = f"{shape}-{num_shapes}.json"
scene_path = temp_dir / fname
if scene_path.exists():
... | The main task of the code is to generate shape scenes and benchmark compiler/flag combinations by counting FLOPs. It initializes data collection, runs shape scene generation, executes FLOPs counting with the first compiler, then iterates through all compilers and flags to benchmark performance, though the `datapoints` ... | def main(conf, temp_dir):
datapoints = []
print_header("Generate Shape Scenes")
gen_shape_scenes(conf, temp_dir)
print_header("Flops Counter")
# Count flops first
run_with_flags(conf, conf.compilers[0], "", True, {"has_flops": True})
for compiler in conf.compilers:
for flag in conf... |
def discretization_by_length(p_data, p_buckets_num):
v_data = p_data.copy()
for i in v_data.keys()[:-1]:
min = v_data[i].min()
max = v_data[i].max()+0.1
one_bucket_range = (max - min) / p_buckets_num
bins = [min, max]
start_val = min
for _ in range(p_buckets_num... | The function processes a dataset by applying optional discretization (using specified methods and bucket counts) and configures cross-validation parameters (stratified, shuffled, fold count). It generates descriptive titles for outputs and executes cross-validation on the processed data, returning the results. | def f_main(dataset_name, discretization_on, d_type, d_buckets_num, cv_fold_num, cv_stratified, cv_shuffle):
title = dataset_name.upper() + "\n"
img_title = dataset_name.upper()
dataset = pd.read_csv(dataset_name + '.csv', sep=',')
v_data = dataset.copy()
if discretization_on:
title += " Di... |
def write_plots4results(alg_name, ds_name, label_x_name, x, acc, f_score, recall, prec):
write_plot(alg_name=alg_name, result=[x, acc], plot_title=ds_name,
label_x=label_x_name, label_y="accuracy")
write_plot(alg_name=alg_name, result=[x, f_score], plot_title=ds_name,
label_x=labe... | The main task of the code is to evaluate the performance of AdaBoost with decision trees (cart) on multiple datasets by varying `n_estimators` and `learning_rate` parameters. It performs 10-fold cross-validation, computes accuracy, F1, precision, and recall metrics, and stores results for analysis. The code iterates th... | def test_ada_boost():
# params
seed = 1
n_estimators = [10, 20, 50, 100, 200]
learning_rate = [.5, 1., 5., 10., 15.]
# cross validation
kfold = model_selection.KFold(n_splits=10, shuffle=True, random_state=seed)
scores = ['accuracy', 'f1_macro', 'precision_macro', 'recall_macro']
# N E... |
def write_plots4results(alg_name, ds_name, label_x_name, x, acc, f_score, recall, prec):
write_plot(alg_name=alg_name, result=[x, acc], plot_title=ds_name,
label_x=label_x_name, label_y="accuracy")
write_plot(alg_name=alg_name, result=[x, f_score], plot_title=ds_name,
label_x=labe... | The code evaluates the performance of a BaggingClassifier with decision tree base estimators across multiple hyperparameters (n_estimators, max_features, max_samples, bootstrap, warm_start, bootstrap_features) using cross-validation. It tests each parameter configuration on datasets, measures accuracy, F1, recall, and ... | def test_bagging():
# params
seed = 1
max_samples = [0.2, 0.4, 0.6, 0.8, 1.0]
n_estimators = [20, 50, 100, 200, 400]
max_features = [0.2, 0.4, 0.6, 0.8, 1.0]
warm_start = [False, True]
bootstrap = [False, True]
bootstrap_features = [False, True]
# cross validation
kfold = model... |
def write_plots4results(alg_name, ds_name, label_x_name, x, acc, f_score, recall, prec):
write_plot(alg_name=alg_name, result=[x, acc], plot_title=ds_name,
label_x=label_x_name, label_y="accuracy")
write_plot(alg_name=alg_name, result=[x, f_score], plot_title=ds_name,
label_x=labe... | The code tests hyperparameters of a Random Forest classifier (e.g., n_estimators, max_depth, etc.) using cross-validation on multiple datasets. For each parameter, it evaluates accuracy, F1, precision, and recall, storing results in files and generating plots. The goal is to identify optimal hyperparameters for perform... | def test_rf():
# params
seed = 1
n_estimators = [10, 20, 50, 100, 200]
criterion = ["gini", "entropy"]
max_depth = [1, 2, 5, 10, 20]
min_samples_split = [.2, .4, .6, .8, 1.]
min_samples_leaf = [.1, .3, .5, 1]
max_features = [.2, .4, .6, .8, 1.]
max_leaf_nodes = [2, 5, 10, 20, 40]
... |
def write_bar_plots4results(alg_name, ds_name, label_x_name, x, acc, f_score, recall, prec):
write_bar_plot(alg_name=alg_name, result=[x, acc], plot_title=ds_name,
label_x=label_x_name, label_y="accuracy")
write_bar_plot(alg_name=alg_name, result=[x, f_score], plot_title=ds_name,
... | The code defines a function to evaluate ensemble learning models (Bagging, Boosting, Random Forest) using hard/soft voting. It cross-validates these combinations on datasets, comparing accuracy, F1, precision, and recall. Results are stored, visualized, and written to files for analysis. | def voting():
seed = 1
bagging = BaggingClassifier(base_estimator=cart, n_estimators=50, max_samples=1.0, max_features=0.7,
bootstrap_features=True, bootstrap=False, random_state=seed)
boosting = AdaBoostClassifier(base_estimator=cart, learning_rate=1.0, n_estimators=26, rand... |
def create_folder(folder_name):
os.mkdir("results/" + folder_name)
def load_dataset(filename, scale_data=0):
dataset = pd.read_csv(filename + '.csv', sep=',')
if scale_data == 1:
standardize(dataset)
elif scale_data == 2:
normalize(dataset)
return dataset
def cross_validation(p_data,... | The main task of the code is to perform cross-validation on datasets scaled at different levels (0, 1, 2), varying folds (2, 3, 5, 10) and stratification settings (False, True). It collects evaluation metrics (accuracy, recall, precision, F1-score) for each configuration, stores them in structured arrays, and writes th... | def main(filename):
direc = filename + "_scale"
create_folder(direc)
for scale in (0, 1, 2):
arr2 = []
arr3 = []
arr5 = []
arr10 = []
dataset = load_dataset(filename, scale)
for folds in (2, 3, 5, 10):
for stratified in (False, True):
... |
def create_folder(folder_name):
os.mkdir("results/" + folder_name)
def load_dataset(filename, scale_data=0):
dataset = pd.read_csv(filename + '.csv', sep=',')
if scale_data == 1:
standardize(dataset)
elif scale_data == 2:
normalize(dataset)
return dataset
def cross_validation_2(p_dat... | The code performs cross-validation on a dataset specified by `filename`, varying parameters like `scale`, `folds`, `stratified`, and `odleg` (distance measures). It evaluates model performance metrics (accuracy, recall, precision, F1-score) for each configuration, stores results in arrays, and saves them to a directory... | def main_2(filename):
odl = [0, 1]
direc = filename + "_odleglosc_2"
create_folder(direc)
#for scale in (0, 1, 2):
scale = 0
folds = 10
stratified = True
# arr2 = []
# arr3 = []
# arr5 = []
arr10 = []
dataset = load_dataset(filename, scale)
#for folds in (10):
#fo... |
def create_folder(folder_name):
os.mkdir("results/" + folder_name)
def load_dataset(filename, scale_data=0):
dataset = pd.read_csv(filename + '.csv', sep=',')
if scale_data == 1:
standardize(dataset)
elif scale_data == 2:
normalize(dataset)
return dataset
def cross_validation_3(p_dat... | The main task of the code is to perform cross-validation on a dataset using different voting strategies (0, 1, 2) and parameters (scale, folds, stratification). It evaluates model performance metrics (accuracy, recall, precision, F1-score) for each configuration, stores the results in arrays, and saves them to a file f... | def main_3(filename):
odleg = 1
vots = [0, 1, 2]
direc = filename + "_voting_2"
create_folder(direc)
#for scale in (0, 1, 2):
scale = 0
folds = 10
stratified = True
# arr2 = []
# arr3 = []
# arr5 = []
arr10 = []
dataset = load_dataset(filename, scale)
#for folds i... |
def agent_shoot(self) -> list:
# need to check the direction
direction = self.agent_current_cell.get_agent_direction()
position = self.agent_current_cell.get_cell_position()
# locate target pixel
if direction == 'rnorth':
target_position = (position[0], position[1]+1... | This code defines a method `move` that dispatches actions to corresponding agent functions. Based on the input `action`, it calls methods like `agent_shoot`, `agent_move_forward`, or rotation/pickup functions, enabling the agent to perform specific tasks. The primary task is to route action commands to the appropriate ... | def move(self, action):
if action == 'shoot':
return self.agent_shoot()
if action == 'moveforward':
return self.agent_move_forward()
if action == 'turnleft':
return self.agent_rotate_left()
if action == 'turnright':
return self.agent_rotate... |
def manual(self):
g = Grid(6, 7)
g.display_grid()
print("confound,stench,tingle,glitter,bumpp,scream")
print([True,False,False,False,False,False])
cmd = ['l', 'r', 'f', 's', 'p']
while True:
s = input("enter command: Left=l, Right=r, Forward=f , Pickup=p, S... | The code defines a GUI method that presents a menu for user input (1-4), validates the choice, and executes corresponding actions: manual grid operation, AI exploration, relocation testing, or program exit. It loops until a valid option is selected, then triggers the relevant method or exits. | def gui(self):
ans = ['1','2','3','4']
a = ''
while True:
print("enter a viable input (1-3)")
print("1 :Run on grid manually ")
print("2 :Let AI explore the grid by itself")
print("3 :Test relocation and reborn functionality")
print('4 ... |
def start():
"""prompt user to enter support and confidence values in percent"""
support = int(input("Please enter support value in %: "))
confidence = int(input("Please enter confidence value in %: "))
maxr = int(input("Enter the max number of rules you want to see (enter 0 to see all rules): "))
... | The code generates association rules from frequent itemsets using the Apriori algorithm. It iterates through each frequent itemset, computes all possible subsets, checks if they meet the confidence threshold (confidence = support of itemset / support of subset), and stores valid rules. Rules are formatted with support,... | def generate_association_rules():
L1,D, support, confidence, maxr = start()
s = []
r = []
length = 0
count = 1
inc1 = 0
inc2 = 0
num = 1
m = []
L= frequent_itemsets(L1, D, support)
print ("---------------------ASSOCIATION RULES------------------")
print ("----------------... |
def priorityColors(priority, text, done=False):
if done:
return c.PRIORITY_DONE(text)
if priority is None or priority <= 0:
return c.LOWEST(text)
elif priority < 2:
return c.LOW(text)
elif priority <= 4:
return c.MIDLOW(text)
elif p... | This function renders a hierarchical task structure with formatting, including priority coloring, indentation, subtasks, steps, and notes. It recursively processes nested tasks, applies indentation based on level, truncates long notes, and conditionally includes done tasks. The output combines task details, subtasks, s... | def renderTask(self, task, level=0, indent=0, include_done=False):
indentstr = ' '*indent
if level <= 0:
return '{ind}#{num}. {statement} { {info} }'.format(
ind=indentstr, num=task.num, statement=self.priorityColors(task.priority, f'"{task.statement}"'),
... |
def hash(name,n=0):
if(n==0):
return hashlib.sha512(name.encode()).hexdigest()
else:
return hashlib.sha512(name.encode()).hexdigest()[:n]
def showitems():
result = send_to_rest_api("state/{}".format(ITEMS_TABLE))
try:
return (base64.b64decode(yaml.safe_load(result)["data"])).decode()
... | This code processes a bid addition by validating timestamps, checking existing bids, and determining the winning bidder if the auction is closed. It combines a name with a timestamp, checks against existing items and bids, and prints results like "Bidding closed" or "BID TOO LOW" while identifying the winner's ID if ap... | def bidaddition(Name):
namespace = FAMILY_NAME+hash("Bidding entries",6)+hash(Name,58)
timestamp1 = datetime.datetime.now()
timestamp = str(timestamp1)
list1=[]
Name = Name + "@" + timestamp
values = Name.split('@')
k = showitems()
k=k.split(',')
#... |
def init():
style.use('ggplot')
def create_change_columns(df):
df[COL_HIGH_CLOSE] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close']
df[COL_CLOSE_OPEN] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open']
return df
def create_x_y(df):
x = np.array(df.drop([FORECAST['predict col']], 1))
... | The code fetches and preprocesses stock data for GOOGL, creates a forecast column by shifting the Close price, trains a classifier if no existing model is found, predicts future values, and visualizes the actual vs. forecasted prices. It handles missing data, selects features, and saves the trained model for future use... | def main():
init()
nsdq.read_key(API_KEY_FILE)
df = nsdq.get('WIKI/GOOGL')
df = df[FOCUS_COLUMNS]
print(df.head(10))
df = create_change_columns(df)
# select FEATURES columns
df = df[FEATURES]
df.fillna(-99999, inplace=True)
# forecast days ahead for Close column
df[FORECAS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.