dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def xaviar_initalization():
# pick from the following gaussian distribution:
# N~(0, 1/N)
# for v, (2+1)/2 = 1.5, 1/1.5 = 0.6666
v = []
for i in range(2):
v.append(r.normal(loc=0, scale=0.666))
v.append(0) # for the bias
# for w, (2+2)/2 = 2, 1/2 = 0.5
w = []
for i in range(2):
w.append([])
for j in r... | The main task of the code is to train a neural network using RMSProp optimization on a predefined dataset, visualize the total loss over epochs, and compare weight initializations (Xavier vs. constant). It initializes weights, runs RMSProp to minimize loss, and plots the loss curve. Dropout is disabled, and the code fo... | def main():
w, v = xaviar_initalization()
w2, v2 = constant_initalization(1)
dataset = [
[1, 1, 0],
[-1, 1, 1],
[1, -1, 1],
[-1, -1, 0]
]
use_dropout = False
print("---- INPUT ----")
print("dataset = {}").format(dataset)
print("w = {}").format(w)
print("v = {}").format(v)
print("use dropout = {}\n"... |
def get_new_location(self, location, action):
return self.inbounds([sum(x) for x in zip(location, action)])
def get_gridsquare_at(self, location):
gridsquares = list(filter(lambda o: o.location == location, self.objects))
not_floors_or_walls = list(filter(lambda o: (o.name != 'Floor' and o.name ... | This function checks if a given action for the red agent is valid by ensuring it avoids collisions with boxes, walls, and the blue agent's location, stays within grid bounds, and handles box movement logic. It evaluates new positions, validates against obstacles, and ensures proper box interaction rules are followed. | def is_valid_action(self, red_location, action, blue_location, moving_box = False, box_location = None, count_boxes = True):
""" Checks if given action avoids boxes, walls, and stays within the bounds of the grid """
red_new_location = self.get_new_location(red_location, action)
if moving_box: ... |
def draw_gridsquares(self):
self.screen.fill(Color.WHITE)
for location in self.world.get_all_locations():
tl = self.top_left(location)
fill = pygame.Rect(tl[0], tl[1], self.scale, self.scale)
self.screen.fill(Color.FLOOR, fill)
pygame.draw.rect(self.scree... | The main task of the code is to render a game interface by drawing grid squares, agents, and optional sidebar elements (timer, turn indicator, outcome) using Pygame. It updates the display with `pygame.display.flip()` and `update()` to visualize the current game state, including parameters like time, player turn, and o... | def on_render(self, spin = True, time = 0, whose_turn = '', outcome = ''):
self.draw_gridsquares()
self.draw_agents()
if not self.no_sidebar:
self.draw_timer(time)
self.draw_turn(whose_turn)
self.draw_outcome(outcome)
pygame.display.flip()
pyga... |
def get_all_locations(self):
return [(x, y) for x in range(self.width) for y in range(self.height)]
def is_valid_action(self, red_location, action, blue_location, moving_box = False, box_location = None, count_boxes = True):
""" Checks if given action avoids boxes, walls, and stays within the bounds of ... | The code constructs a reachability graph for a red agent's possible movements. It iterates through all locations, adds nodes for each red position, and checks valid moves (UP/DOWN/LEFT/RIGHT) considering the blue agent's position and box-counting logic. Valid moves create edges in the graph, representing accessible tra... | def make_reachability_graph(self, blue_location = (-1, -1), count_boxes = True):
self.reachability_graph.clear()
for red_location in self.get_all_locations():
self.reachability_graph.add_node(red_location)
actions = [DOWN, UP, LEFT, RIGHT]
for action in actions:
... |
def on_init(self, no_sidebar = False):
pygame.init()
self.no_sidebar = no_sidebar
if self.no_sidebar:
self.screen = pygame.display.set_mode((self.width, self.height))
else:
self.screen = pygame.display.set_mode((self.screen_width, self.height))
self.sm... | The code defines the `on_execute` method, which initializes the application, runs a game loop processing events and rendering frames while `_running` is True, and cleans up resources afterward. | def on_execute(self, no_sidebar = False):
if self.on_init(no_sidebar) == False:
self._running = False
while self._running:
for event in pygame.event.get():
self.on_event(event)
self.on_render()
self.on_cleanup() |
def _get_main_pages(self):
main_pages = dict(
filter(
lambda item: self.__list_filter(item[1], PageKeyWords.MAIN_PAGE),
self.ordered_pages_data.items(),
)
)
self.related_pages = dict(
filter(
lambda item: item[0]... | The code processes main pages by extracting their attributes, identifies related pages, extracts additional attributes from these related pages, and combines both sets of attributes to add a comprehensive page entry. | def parse_pages(self):
main_pages = self._get_main_pages()
for main_page in main_pages:
page_main_attribs = self._extract_attribs(main_page)
related_page = self._find_related_page(main_page, page_main_attribs)
page_other_attribs = self._extract_attribs(related_page, o... |
def _buildForwardClosePacket(self):
"""
Assemble the forward close packet
"""
forwardClose = self._buildForwardClose()
rrDataHeader = self._buildEIPSendRRDataHeader(len(forwardClose))
return rrDataHeader + forwardClose
def recv_data(self):
"""
When receivi... | The main task of the code is to close a connection to a PLC by sending a forward close packet, unregistering the session, and closing the socket. It first disables the connected flag, sends a close packet if connected, receives a response, then sends an unregister packet if registered. Finally, it closes the socket, ha... | def _closeConnection(self):
"""
Close the connection to the PLC (forward close, unregister session)
"""
self.SocketConnected = False
try:
if self._connected:
close_packet = self._buildForwardClosePacket()
self.Socket.send(close_packet)
... |
def _getTagList(self, allTags):
"""
Requests the controller tag list and returns a list of Tag type
"""
conn = self.conn.connect()
if not conn[0]:
return Response(None, None, conn[1])
self.Offset = 0
status = 6
tags = []
while status ... | The code retrieves a PLC program's tag list, handling connection errors and program existence checks. It connects to the PLC, validates the program name, fetches tags if the program exists, processes UDT data, and returns a Response object with tags, status, or error messages. | def GetProgramTagList(self, programName):
"""
Retrieves a program tag list from the PLC
programName = "Program:ExampleProgram"
returns Response class (.TagName, .Value, .Status)
"""
conn = self.conn.connect()
if not conn[0]:
return Response(programNam... |
def parse_tag_name(tag):
"""
Parse the tag name into it's base tag (remove array index and/or
bit) and get the array index if it exists
ex: MyTag.Name[42] returns:
MyTag.Name[42], MyTag.Name, 42
"""
bit_end_pattern = r'\.\d+$'
array_pattern = r'\[([\d]|[,]|[\s])*\]$'
# get the arra... | This function processes a write request to a specified tag by formatting the value according to its data type, splitting data into packets if necessary, sending the write command via a connection, and returning a response with the operation status. It handles data conversion, packet construction, and error checking for... | def _write_tag(self, tag_name, value, data_type=None):
"""
Processes the write request
"""
self.Offset = 0
write_data = []
conn = self.conn.connect()
if not conn[0]:
return Response(tag_name, value, conn[1])
tag, base_tag, index = parse_tag_n... |
def parse_tag_name(tag):
"""
Parse the tag name into it's base tag (remove array index and/or
bit) and get the array index if it exists
ex: MyTag.Name[42] returns:
MyTag.Name[42], MyTag.Name, 42
"""
bit_end_pattern = r'\.\d+$'
array_pattern = r'\[([\d]|[,]|[\s])*\]$'
# get the arra... | This function processes a read request by parsing a tag name, constructing a read service request based on data type, handling bit/word arrays, and sending the request over a connection. It manages partial responses, adjusts for data padding, and returns parsed data in a Response object with the tag name, value, and st... | def _read_tag(self, tag_name, elements, data_type):
"""
Processes the read request
"""
self.Offset = 0
conn = self.conn.connect()
if not conn[0]:
return Response(tag_name, None, conn[1])
tag, base_tag, index = parse_tag_name(tag_name)
resp = ... |
def _buildMultiServiceHeader(self):
"""
Service header for making a multiple tag request
"""
MultiService = 0X0A
MultiPathSize = 0x02
MutliClassType = 0x20
MultiClassSegment = 0x02
MultiInstanceType = 0x24
MultiInstanceSegment = 0x01
retur... | This function processes multiple read requests for tags, constructing service segments while adhering to connection size limits. It calculates required response sizes, builds request headers, and assembles data segments. If the request exceeds size constraints, it stops adding tags. It sends the constructed request, ha... | def _multi_read(self, tags, first):
"""
Processes the multiple read request, but only the possible number of tags in a single request. The size
difference between tags and result must be check for a complete read
"""
service_segs = []
segments = b""
tag_count = 0
... |
def _closeConnection(self):
"""
Close the connection to the PLC (forward close, unregister session)
"""
self.SocketConnected = False
try:
if self._connected:
close_packet = self._buildForwardClosePacket()
self.Socket.send(close_packet)
... | The main task of the code is to establish a connection to a PLC by creating a socket, registering a session, and opening a connection with specified parameters. It handles connection type changes, socket management, error handling during connection, session registration validation, and attempts to open a connection wit... | def _connect(self, connected, conn_class):
"""
Open a connection to the PLC.
"""
if self.SocketConnected:
if connected and not self._connected:
# connection type changed, need to close so we can reconnect
self._closeConnection()
eli... |
def parse_tag_name(tag):
"""
Parse the tag name into it's base tag (remove array index and/or
bit) and get the array index if it exists
ex: MyTag.Name[42] returns:
MyTag.Name[42], MyTag.Name, 42
"""
bit_end_pattern = r'\.\d+$'
array_pattern = r'\[([\d]|[,]|[\s])*\]$'
# get the arra... | This function identifies and retrieves data types of unknown tags by checking against a known tags dictionary. It processes input tags, parses their structure, and collects those not in the known set. It then reads these unknown tags using either initial or multi-read methods to obtain their data types, returning the r... | def _get_unknown_types(self, tags):
"""
Retrieve the data types of tags we have not read yet
"""
unk_tags = []
for t in tags:
if isinstance(t, (list, tuple)):
tag_name, base_tag, index = parse_tag_name(t[0])
if len(t) == 3:
... |
def _get_unknown_types(self, tags):
"""
Retrieve the data types of tags we have not read yet
"""
unk_tags = []
for t in tags:
if isinstance(t, (list, tuple)):
tag_name, base_tag, index = parse_tag_name(t[0])
if len(t) == 3:
... | This function processes multiple read requests by splitting them into batches, handling connection establishment, and reassembling responses. It checks for Micro800 device specifics, retrieves unknown tag data types, and iteratively reads tags either individually (for the last remaining tag) or in bulk using _multi_rea... | def _batch_read(self, tags):
"""
Processes the multiple read request. Split into multiple requests and
reassemble responses when needed
"""
if self.Micro800 == True:
return Response(tags, None, 8)
conn = self.conn.connect()
if not conn[0]:
... |
def _get_unknown_types(self, tags):
"""
Retrieve the data types of tags we have not read yet
"""
unk_tags = []
for t in tags:
if isinstance(t, (list, tuple)):
tag_name, base_tag, index = parse_tag_name(t[0])
if len(t) == 3:
... | The main task of the code is to handle batch writing of tags by splitting requests when necessary, formatting tag data, processing unknown types, and reassembling responses. It checks for connection status, processes tags individually or in batches using `_multi_write`, and returns a list of results. Special handling o... | def _batch_write(self, tags):
"""
Processes the multiple write request. Split into multiple requests and
reassemble responses when needed
"""
if self.Micro800 == True:
return Response(tags, None, 8)
conn = self.conn.connect()
if not conn[0]:
... |
def load_table_L():
"""Table L: Electricity consumption"""
# 4 unnecessary rows at the top, column A is empty
df = pd.read_excel("Australian Energy Statistics 2022 Table L.xlsx",
sheet_name = "Aus",
skiprows = 4,
usecols = "B:J")
# Remove the row that just says "GWh"
df.drop(index = 0, inplace = True)
... | This function loads energy consumption and generation data from pandas DataFrames into a database. It first inserts region records, then iterates through regions and years to insert corresponding energy data, using region IDs and filtered DataFrame values for each year. The data includes electricity and gas usage, rene... | def load_data_into_db(connection):
elec_consumption_df = load_table_L()
elec_generation_df = load_table_O()
gas_consumption_df, gas_generation_df = load_table_Q()
region_to_id = {"Australia": 1, "Victoria": 2, "New South Wales": 3, "Queensland": 4, "South Australia": 5, "Northern Territory": 6, "Western Australia"... |
def _check_chunk_size(self, tolerance_ratio=0.1):
"""
Validates if the chunk size is within the model's maximum input size, considering metadata.
Args:
chunk_size (int): Size of each chunk in tokens.
tolerance_ratio (float): Ratio of (chunk + metadata) length to max inpu... | The main task of the code is to initialize a searchable index and associated DataFrame by building an FAISS index for embeddings and training an LDA model to extract document topic distributions. It orchestrates chunking documents, creating a similarity search index, and enriching document metadata with topics, alignin... | def initialize_components(self):
"""
The primary method to be used externally for activating the index building mechanism.
It orchestrates the creation of a searchable index and the associated DataFrame containing
embeddings, text, metadata, and topic distributions.
It follows t... |
def _prepare_batches_perplexity(self, test_data):
"""
Prepares batches of test data for perplexity evaluation.
Args:
test_data (DataFrame): DataFrame containing test data.
Returns:
List[List[Dict]]: List of batches, each batch being a list of query-response dict... | The main task of the code is to evaluate an RALM model using test data by processing queries in batches. It calculates perplexity (a measure of prediction quality) and generates responses for each query. The function combines these results with the original test data, producing a DataFrame that includes queries, expect... | def evaluate(self, test_data):
"""
Evaluates the RALM instance using the provided test data. It processes the data in batches, computing metrics
such as perplexity and generating responses.
Args:
test_data (DataFrame): DataFrame containing query and expected response pairs.
... |
def cache_key(dep):
# TODO sort keys
return json.dumps(remove_hashes(dep))
def flatten_repr(self):
return {
"fetcher": self.fetcher,
"hash": self.hash,
**self.args
}
def prefetch(self):
# TODO remove "hash" and "sha256" values from the cache key
... | The function `get_file` retrieves a file from a repository, handling both direct directory access and compressed archives. It checks if the file exists in a cached directory path; if not, it extracts the needed file from an archive using `bsdtar` with `--fast-read` for efficiency. The code identifies the archive's top-... | def get_file(self, filepath):
# TODO directory vs archive -> extract only needed files or zipmount
key = cache_key(self.flatten_repr())
if not "store_path" in cache_extra_data[key]:
print("Repo.get_file: calling Repo.prefetch to set store_path")
self.prefetch()
if... |
def check_win(self, player):
return self.check_col_win(player) or self.check_row_win(player) or self.check_diag_win(player)
def check_tie(self):
finished = True
for row in self.board:
for col in row:
if col == '-':
finished = False
... | The code implements the minimax algorithm to determine the optimal move for a player in a tic-tac-toe game. It recursively evaluates all possible moves, choosing the best outcome for the current player (maximizing their score) while assuming the opponent will also play optimally. The function returns the best score and... | def minimax(self, player):
if self.check_win(0):
return (-1, None, None)
if self.check_win(1):
return (1, None, None)
if self.check_tie():
return (0, None, None)
# person sim
if player == 0:
worst = 10
opt_row = -1
... |
def check_win(self, player):
return self.check_col_win(player) or self.check_row_win(player) or self.check_diag_win(player)
def check_tie(self):
finished = True
for row in self.board:
for col in row:
if col == '-':
finished = False
... | This code implements the Minimax algorithm for a Tic-Tac-Toe game. It recursively evaluates all possible moves for a given player (0 for human, 1 for AI), calculating scores based on win/tie conditions. The function returns the optimal move (row, column) and score for the current player at a specified depth, prioritizi... | def minimax_depth(self, player, depth):
if self.check_win(0):
return (-1, None, None)
if self.check_win(1):
return (1, None, None)
if self.check_tie():
return (0, None, None)
if depth == 0:
return (0, None, None)
# person sim
... |
def check_win(self, player):
return self.check_col_win(player) or self.check_row_win(player) or self.check_diag_win(player)
def check_tie(self):
finished = True
for row in self.board:
for col in row:
if col == '-':
finished = False
... | This function implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move for a player in a tic-tac-toe-like game. It recursively evaluates all possible moves, checks terminal states (win, tie), and selects the best move by maximizing/minimizing scores while pruning suboptimal branches. Playe... | def minimax_alpha_beta(self, player, depth, alpha, beta):
if self.check_win(0):
return (-1, None, None)
if self.check_win(1):
return (1, None, None)
if self.check_tie():
return (0, None, None)
if depth == 0:
return (0, None, None)
#... |
def print_instructions(self):
print("Welcome to TicTacToe!")
print("Player 0 is X and Player 1 is O")
print("Take turns placing your pieces — first to three in a row wins!")
def print_board(self):
print(" 0 1 2")
for i in range(3):
print(str(i), end=" ")
... | The code's main task is to facilitate a two-player game where players take turns marking the board (X or O) until a win condition is met or the game ties. It alternates turns, prints the board after each move, checks for a win or tie, and announces the result: "X wins!", "O wins!", or "It was a tie". | def play_game(self):
# TODO: Play game
self.print_instructions()
self.print_board()
player = 0
while not self.check_win((player + 1) % 2) and not self.check_tie():
print("X's Turn") if player == 0 else print("O's Turn")
self.take_turn(player)
... |
def _calculate_forward(self, rolls):
forward_data = self._init_forward_data(rolls)
for i in range(len(rolls) - 1):
for state in DiceTypes:
forward_data[state.value][i + 1] = Decimal(0)
for state_sum_element in DiceTypes:
transition_probab... | The code calculates the posterior probabilities of hidden states in a probabilistic model using forward and backward probabilities derived from observed data (rolls), combining them to determine the likelihood of each state sequence given the observations. | def _calculate_aposteriori(self, rolls):
fwd = self._calculate_forward(rolls)
bwd = self._calculate_backward(rolls)
return self._aposteriori_probability(fwd, bwd, rolls) |
def split_df(df, feature, split):
if isinstance(split, str):
return df[df[feature] == split], df[df[feature] != split]
# if not string must be numeric
return df[df[feature] <= split], df[df[feature] > split]
def create_node(self, data):
imp = leaf_gini_imp(data)
if imp != 0 and len(d... | This code recursively constructs a decision tree by splitting data at each node. It checks if the current node is a leaf or has reached the maximum height, then splits the dataset using the specified feature and threshold. It creates left and right child nodes with the split data and recursively processes them, increme... | def visit(self, dtree, height=1):
if height == self.max_height or dtree.is_leaf():
return
df, feature, split = astuple(dtree.value)
left_data, right_data = split_df(df, feature, split)
dtree.left = self.create_node(left_data)
dtree.right = self.create_node(right_dat... |
def get_paths_to_base_etl_outputs(path_to_read=None):
if not path_to_read:
path_to_read = os.path.join(os.getcwd(), "etl_outputs_xlsx")
else:
pass
paths = [
os.path.join(path_to_read, file)
for file in os.listdir(path_to_read)
if r".xlsx" in file and "combined" not... | The code's main task is to combine multiple ETL-processed dataframes into a unified dataset, validate column consistency, generate contextual metadata, and save the combined results to specified file paths. It retrieves input files, checks structural alignment, merges valid data, creates a context dataframe, and writes... | def run_pipeline(
paths_to_write_to: list,
base_file_name: str = r"CME Group Futures Price - Prior Settle (COMBINED).xlsx",
):
paths = get_paths_to_base_etl_outputs()
df_dict = get_dict_of_dfs(paths)
hash_dict = get_col_check_dtl(df_dict)
df_total = combine_valid_dfs(df_dict, hash_dict)
... |
def read_csv_from_path(full_path: str):
"""
Reads in combined csv from single scraping run output based on a
directory path and performs some basic cleanup.
:param full_path: Path where CSV is stored
:return: pd.DataFrame with slight modifications performed
"""
# full_path = r'C:\Users\GEM73... | The code processes a CSV file by parsing and splitting date/time fields, pivoting data by metrics, cleaning/normalizing values, reordering columns via an external template, and exporting to Excel. It transforms raw scraped data into structured, standardized output with contextual metadata, ensuring consistent formattin... | def run_pipeline(path_str):
print(f"Pipeline Started for:\n\t{path_str}")
# =========================================================================
# Importing and lightly cleaning up from scraping CSV output
# path_str = r'C:\Users\GEM7318\Documents\Github\Energy-Scraping' \
# r'\outp... |
def match(self, expected_token):
if self.current_token[0] == expected_token:
self.next_token()
elif self.current_token[1] == '$':
self.next_token()
elif self.current_token[1] == expected_token:
self.next_token()
else:
raise SyntaxError(f"Ex... | This function recursively parses a list of comma-separated identifiers. If the current token is a comma, it matches the separator, processes an identifier, and recursively continues parsing the remaining list. If no comma is found, it terminates the recursion by calling an empty method, effectively ending the list pars... | def IDs_prime(self):
if self.current_token[1] == ',':
self.match('separator')
self.identifier()
self.IDs_prime()
else:
self.empty() |
def match(self, expected_token):
if self.current_token[0] == expected_token:
self.next_token()
elif self.current_token[1] == '$':
self.next_token()
elif self.current_token[1] == expected_token:
self.next_token()
else:
raise SyntaxError(f"Ex... | This function recursively parses a list of parameters separated by commas. If the current token is a comma, it consumes the separator, parses a parameter, and continues parsing the list. If no comma is found, it signals an empty state. The method handles parameter list construction in a grammar parser, ensuring multipl... | def parameter_list_prime(self):
if self.current_token[1] == ',':
self.match('separator')
self.parameter()
self.parameter_list_prime()
else:
self.empty() |
def declaration(self):
self.qualifier()
self.IDs()
def match(self, expected_token):
if self.current_token[0] == expected_token:
self.next_token()
elif self.current_token[1] == '$':
self.next_token()
elif self.current_token[1] == expected_token:
... | This method recursively parses a list of variable declarations, checking if the current token is a valid type (integer, boolean, real). If true, it processes the declaration, matches a separator, and continues parsing the list. If not, it terminates the list by calling empty(). The function is part of a parser handling... | def declaration_list_prime(self):
if self.current_token[1] in ['integer', 'boolean', 'real']:
self.declaration()
self.match('separator')
self.declaration_list_prime()
else:
self.empty() |
def Initialize(self) :
layer_dims = self.NNSizes
L = len(layer_dims)
for i in range (1,L) :
self.NNParameters['W' + str(i)] = np.random.randn(layer_dims[i],layer_dims[i-1]) * 0.01
self.NNParameters['B' + str(i)] = np.random.randn(layer_dims[i],1)
def FeedForward (sel... | This code trains a neural network using gradient descent. It initializes the network structure, performs forward and backward passes iteratively, updates weights/biases with the given learning rate, and records the cost function value after each iteration to monitor training progress. | def Fit (self,input,output , learning_rate = 0.001 , iterations = 1000) :
self.NNInput = input
self.NNOutput = output
if self.NNSizes != [] :
self.NNSizes.insert(0, len(self.NNInput[0]))
self.NNActivationFunctions.insert(0, 'sigmoid')
self.... |
def _check_events_keydown(self, event):
# This is for checking if the key's have been pressed down and what whill happen if they are pressed
if event.key == pygame.K_q:
sys.exit()
elif event.key == pygame.K_ESCAPE:
sys.exit()
elif event.key == pygame.K_RIGHT:
... | This method handles user input events in a Pygame game. It checks for quitting the game, processes key presses/releases, and detects mouse clicks on the play button when the game is inactive. Events trigger corresponding methods to manage game state changes, input responses, and interaction with UI elements like the st... | def _check_events(self):
# This is the code for checking certain events occur (i.e. keys being pressed)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_events_keydown(event)
... |
def _check_events(self):
# This is the code for checking certain events occur (i.e. keys being pressed)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_events_keydown(event)
... | The main task of the code is to run a game loop that handles events, updates game objects (avatars, obstacles, coins), manages collisions, updates scores, and renders the game screen. It maintains the game state via `game_active`, updates visual elements, and ensures continuous gameplay with frame rate control using Py... | def run_game(self):
clock = pygame.time.Clock()
while True:
self._check_events()
self.car_hit()
self.score.prep_score(self)
self.score.prep_score_two(self)
if self.settings.game_active:
screen.blit(bg, (0, 20))
s... |
def setup_sidebar():
"""Set up the sidebar with selectable options."""
st.sidebar.title("Stuck on Leetcode?")
options = [None] + solutions["name"]
return st.sidebar.selectbox(
label="Choose an problem:", options=options, key="selection"
)
def handle_new_selection(selected_option):
"""Cle... | The main task of the code is to display a chat interface by handling sidebar selections, updating the interface based on user choices, rendering the chat title and messages, and processing user input for chat interactions. | def display_chat_interface():
"""Main function to display the chat interface"""
# Handle sidebar and check for new selections
selected_option = setup_sidebar()
selection_change = st.session_state.current_selection != selected_option
if selection_change and selected_option is not None:
hand... |
def check_previous_files():
#get all files and folders in /logs folder
for root, dirs,files in os.walk(os.getcwd() + '/logs'):
#loop through all files
for filename in files:
#removes ~ from file names
if filename.startswith('~'):
filenamelogs = os.getcwd() + '/logs/' + filename
os.rename(filenamelog... | The code sets up GPIO, I2C, and serial interfaces to log sensor data into files. It continuously writes data to a file until it reaches 25KB, then renames the file and starts a new one. The loop repeats until logging stops, ensuring data is stored in manageable file sizes while handling hardware interfaces and cleanup. | def main():
#set gpio settings
gpio.setmode(gpio.BCM)
gpio.setup(24,gpio.OUT)
gpio.setwarnings(False)
print("Checking previous files")
check_previous_files()
print("setting variables...")
#variables for i2c
#largest kb file size
largest_file_size_kb = 25
print("setting i2c interface...")
pi, handle = ... |
def _r_key(self, key):
if self._r_namespace:
return f"{RESQUE_NAMESPACE_PREFIX}:{self._r_namespace}:{key}"
return f"{RESQUE_NAMESPACE_PREFIX}:{key}"
def metric_failed_jobs(self):
failed_jobs_amount = self._r.get(self._r_key('stat:failed')) or 0
metric = self._failed_jobs_met... | The code collects metrics from a Redis broker by retrieving queue and worker data, then yields multiple metric methods to process and expose these metrics, logging the collection process. | def collect(self):
logging.info("Collecting metrics from redis broker")
self.queues = self._r.smembers(self._r_key('queues'))
self.workers = self._r.smembers(self._r_key('workers'))
yield self.metric_failed_jobs()
yield self.metric_processed_jobs()
yield self.metric_queu... |
def generate_progress_bar (count, no_segments, state, bar_length = 20, fill = '█', empty='-', prefix=' ... Adding segments: '):
"""
Prints a progress bar to the console.
:param count: current value
:param no_segments: maximum value
:param state: message printed next to the progress ba... | This code reads a JSON file containing TOMTOM network data, processes each segment to build a network, and simplifies it by removing degree-2 nodes. It optionally prints progress updates. | def build_from_file(self, filename, verbose):
"""
Builds network with TOMTOM data, downloaded in JSON format.
:param filename: JSON file path
:param verbose: Print network creation progress
"""
with open(filename) as json_file:
data = json.load(json_file)
... |
def list_databases(self):
description_arr = [('seq',
None,
None,
None,
None,
None,
None),
('name',
... | This code processes SQL commands by routing them to appropriate handler methods, initializing result variables, parsing specific commands like SHOW, KILL, DESCRIBE, and SET, executing queries, and converting responses into structured result tuples. | def execute(self, sql, arg=None, **kwargs):
self._result_set = tuple()
self._description = tuple()
self._rowcount = -1
self._arraysize = -1
self._json_result = {}
sql_string_array = sql.lower().split()
sql_string = " ".join(str(x) for x in sql_string_array)
... |
def _file_ext(f):
return f.split('.')[-1].lower()
def _make_file_index(files):
file_index = defaultdict(dict)
for f in files:
h = hashlib.new('md5')
with open(f, 'rb') as media:
h.update(media.read())
file_index[f]['created'] = _created_datetime_from_file(f)
file_... | The code searches for media files recursively, filters eligible files by extension, creates indexes for files, months, and duplicates, reports duplicate counts, sorts media files using indexes, and displays progress/status updates with a spinner. | def run(args):
sp = yaspin()
sp.color = 'blue'
sp.start()
sp.text = "searching for media files..."
files = glob.glob('**/*.*', recursive=True)
eligible_files = [f for f in files if _file_ext(f) in ALLOWED_EXTENSIONS]
sp.write(f"> found {len(eligible_files)} media files.")
sp.text = "crea... |
def handle_menu_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
elif self.current_menu.name == "Name":
name = self.player[2]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_B... | The code updates the game state by handling events and rendering elements based on the current playstate, transitioning between menu, map, battle, and stat menu states, with logic for player actions, battle outcomes, and stat adjustments. | def update(self):
if self.playstate == utilities.PlayState.MENU:
self.handle_menu_events()
self.current_menu.render_menu(self.screen)
elif self.playstate == utilities.PlayState.MAP:
self.player_moved = False
self.screen.fill(config.black)
self... |
def log_message(self, format, *args):
"""
Log an info message.
:param str format: Format string.
:param List[Any] args: % parameters of the format string.
"""
if is_server_running(self.server):
logging.info(("Request [%i]: " + format) % ((self._req_num,) + arg... | This code handles HTTP GET requests by relaying them to a target server, modifying headers to include the correct host and port, forwarding the request, capturing the response, and transmitting it back to the client while logging activity and managing connection state. It also manages error handling for socket issues a... | def do_GET(self):
"""
Do the relaying work.
"""
with self.relay.lock:
self.relay.num_open_requests += 1
try:
# Choose the right HTTP version
connection_class = HTTP11Connection if self.protocol_version == "HTTP/1.1" else HTTP10Connection
... |
def generate_prime():
yield 2 # 2 is the first prime number
sieve = {} # Using a dictionary to store multiples of primes
num = 3 # Start checking from 3
while True:
if num not in sieve:
yield num # Yield the prime number
sieve[num * num] = [num] # Mark the square of ... | The code generates a specified number of messages (`limit`) using prime and mix number generators, based on a given distribution. It loops, producing messages with `produce_message()` until the limit is reached, then sends an end message. The main task is to systematically create and distribute messages using prime and... | def run(distribution, limit):
counter = 0
prime_gen = generate_prime()
mix_gen = generate_mix()
while counter < int(limit): # while true
produce_message(distribution, prime_gen, mix_gen, limit)
counter += 1
produce_end_message() |
def getLinkedIssues(jira: JIRA, issue):
linkedIssues = []
for issue_link in issue.fields.issuelinks:
liKey = None
if hasattr(issue_link, "outwardIssue"):
outwardIssue = issue_link.outwardIssue
liKey = outwardIssue.key
if hasattr(issue_link, "inwardIssue"):
... | (The code analyzes a JIRA issue by creating a component-specific directory, retrieving linked issues, calculating size metrics from descriptions and links, proposing a size estimate, and generating a workbook to document the issue, its links, size analysis, and proposed size for the specified component.) | def analyzeIssue(jira: JIRA, component, issue):
# create component folder
if not os.path.isdir(f"generated/{component}"):
os.makedirs(f"generated/{component}")
linkedIssues = getLinkedIssues(jira, issue)
liSizes = linkedIssueSizes(issue.fields.description, linkedIssues)
proposedSize = propos... |
def __getArchResults(self) -> list:
req_conf = self.config["request"]
resp_conf = self.config["response"]
limit = req_conf["query"]["pagination"]["limit"]
all_results = []
seed_url = self.__buildSeedApiUrl()
url = seed_url
page = 1
total = 1
count ... | This function processes API response data to generate a list of structured ArchInfo objects. It extracts and transforms fields like title, summary, URL, and optional metadata (thumbnail, categories, products) from each item in the input JSON, applying nested path configurations if specified. Unique IDs are assigned, an... | def getArchInfos(self) -> List[ArchInfo]:
api_json = self.__getArchResults()
print("Need Processing:", len(api_json))
resp_conf = self.config["response"]
nested = resp_conf["identifiers"].get("nested")
item_fields = resp_conf["identifiers"]["item"]
arch_infos: List[ArchIn... |
def getPhidgetName(phidget: Phidget) -> str:
id = phidget.getChannel()
# This method identifies the phidget and returns its name
if phidget.getHubPort() != 2:
if phidget.getHubPort() == 0:
return 'Upstream'
elif phidget.getHubPort() == 1:
return 'Downstream'
... | The code processes voltage changes from upstream/downstream sensors to update pressure values, calculates tank pressure using correction constants, and controls solenoids/warning lights based on pressure thresholds. It ensures proper inflation/deflation states, logs exceptions, and writes pressure data to outputs if en... | def onVoltageChange(self: VoltageInput, voltage):
voltageInput = self
global upstreamVoltage
global upstreamPressure
global downstreamVoltage
global downstreamPressure
global tankPressure
global digitalOutputs
global inflationStateTime
global deflationStateTime
global allChannels... |
def getToken():
"""Will get authorization token from CSG."""
d = {
"grant_type": "client_credentials",
"client_id": f"{API_Client_ID}",
"client_secret": f"{API_Client_secret}",
}
r = requests.post("https://api.cybersixgill.com/auth/token", data=d)
r = r.text.split(":")
r ... | This function creates a new organization in the CSG system by sending a POST request to their API with organization details. If successful, it retrieves the organization ID and uses it to set up users and additional details like aliases, domains, IP addresses, and executives via helper functions. | def setNewCSGOrg(newOrgName, orgAliases, orgdomainNames, orgIP, orgExecs):
"""Set a new stakeholder name at CSG."""
newOrganization = json.dumps(
{
"name": f"{newOrgName}",
"organization_commercial_category": "customer",
"countries": ["worldwide"],
"indust... |
def cyhybastionConn():
"""Check for cyhyDB connection and if not connected, make the connection."""
myprocess = os.popen("w") # nosec
pro1 = myprocess.read()
if "bastion" in pro1:
logging.info("This application has a connection to the cyhy db...")
return True
else:
loggin... | The main task of the code is to process a form submission for customer stakeholder information, validate the input, store data in a database, and render a template with the form and relevant data. It handles customer domain details, checks for existing entries, and manages database operations for stakeholders, domains,... | def stakeholder():
"""Process form information, instantiate form and render page template."""
cust = False
custDomainAliases = False
custRootDomain = False
custExecutives = False
formExternal = InfoFormExternal()
# allCustIP = cyhyGet()[0]
cyhyconnected = cyhybastionConn()
# loggin... |
def human_game2(self, x, y):
self.UI.wn.onclick(None)
pos = self.get_position(x, y)
if pos is None or self.board[pos] is not None:
self.UI.wn.onclick(self.human_game2)
return
player = self.players[0]
self.take_turn2(player, pos)
if self.check_if... | This method initializes a game by determining player types, setting up UI interactions, and handling turn order. It checks if all players are human1, human2, or mixed. For all human1, it displays the first player's info and waits for a click to start; for all human2, it starts directly. For mixed types, it takes the fi... | def start_game(self):
self.players = self.turn_order.copy()
first = self.players[0]
if all(player.player_type == 'player1' for player in self.players):
self.UI.display(first.name, 'top', first.color)
self.UI.wn.onclick(self.human_game1)
elif all(player.player_type... |
def bot_take_turn(self, player):
self.minimax_calls = 0
pos, score = self.minimax_choose_pos(self.board, player.mark)
print(f"Minimax score: {score}, function calls: {self.minimax_calls}")
self.take_turn(player, pos)
def check_if_won(self, board, mark):
return any(all(board[p] ... | The code implements a game loop where a bot plays against another player, alternating turns until the board is full. After each bot move, it checks if the bot has won; if so, the game ends with the bot's victory. If the board fills without a winner, the game ends in a tie. | def bot_game(self):
while None in self.board:
self.bot_take_turn(self.players[0])
if self.check_if_won(self.board, self.players[0].mark):
self.end_game(self.players[0])
return
self.players.reverse()
self.end_game('tie') |
def get_position(self, x, y):
if x > -225 and x < -75 and y > 75 and y < 225:
position = 0
elif x > -75 and x < 75 and y > 75 and y < 225:
position = 1
elif x > 75 and x < 225 and y > 75 and y < 225:
position = 2
elif x > -225 and x < -75 and y > -75 ... | This function handles a turn in a human vs. bot game by processing a user's click, validating the move, taking turns for both players, checking win/tie conditions, and updating the game state. It removes the click handler temporarily, processes the human move if valid, triggers bot moves, checks for a win or tie, and r... | def human_bot_game(self, x, y):
self.UI.wn.onclick(None)
usr_pos = self.get_position(x, y)
if usr_pos is None or self.board[usr_pos] is not None:
self.UI.wn.onclick(self.human_bot_game)
return
for player in self.players:
if player.player_type == 'huma... |
def _slice_pic(self, pic):
padded_pic = pic
if self.v_padding < 0:
padded_pic = padded_pic[-self.v_padding:self.v_padding, :]
self.v_padding = 0
if self.h_padding < 0:
padded_pic = padded_pic[:, -self.h_padding:self.h_padding]
self.h_padding = 0
... | The code applies a convolution operation on an input image. It first checks padding values, slicing or padding the image accordingly. Then, it initializes an output array and performs convolution using a kernel, returning the processed image. | def apply(self, pic):
if self.h_padding < 0 or self.v_padding < 0:
padded_pic = self._slice_pic(pic)
else:
padded_pic = self._pad_input(pic)
output = np.zeros((self.v_size, self.h_size))
half_ker = (self.kernel.shape[0]-1)//2
self._convolve(half_ker, outpu... |
def processfirstjoincondition(dfjoincond,index,tbl_list,cond_list):
joincondjson = checkisjoincondition(dfjoincond.iloc[index].Condition)
if (joincondjson['isjoincondition'] == True):
vtuneprestmt = PRE_CNT_STMT + " " + dfjoincond.iloc[index].SchemaName + "." + joincondjson['table1'] + ',' + dfjoincond.... | The main task of the code is to process join conditions in a SQL query by iterating through each condition, handling new tables dynamically, and constructing an optimized query string (cons_tune_qry). It initializes variables, processes the first join condition, checks for new tables in subsequent conditions, updates q... | def checkjoincondition(dfjoincond):
#join condition logic
#print("##########Join Condition Started#########")
vtuneprestmt = ''
tbl_list = []
cond_list = []
cons_tune_qry = ''
for index,row in dfjoincond.iterrows():
if (index == 0):
#print("First Index: ",index)
... |
def getschemaname(phrase):
word_list = phrase.split('.')[0].split('(')
schema_nm = word_list[len(word_list)-1]
return schema_nm
def parsecondition(org_cond_str):
der_cond_str = org_cond_str
#remove the prefix brackets
if (org_cond_str[0] == '('):
der_cond_str = der_cond_str[1:]
... | The main task of the code is to parse SQL query conditions, identify schema/table references, validate data availability, and construct an optimized ADAT query by combining valid conditions while ensuring they return data, ultimately returning the tuned query in JSON format with success status. | def processquerytuning(self):
#to find the order or group clause exist in the sql statement.
fltsqlstmnt = self.fltsqlstmnt
sqlstmntsplt = fltsqlstmnt.upper().split(" ")
##Variable Declaration
dfconditions = pd.DataFrame(columns=["SchemaName", "TableName", "PreString", "Conditi... |
def sniffer(count=0):
global gameRegion
#upgrade button for game version
if pyautogui.locateOnScreen('images/sniffer/upgrade.jpg', confidence=.85, grayscale=True, region=gameRegion):
print("Upgrade game version button found.")
boxpress(671, 519, 806, 553) #presses upgrade
time.sleep(5)
pyautogui.click(633, 8... | The function `moveToCity` repeatedly searches for specific images on the screen (e.g., 'map.jpg', 'city.jpg', 'backbutton.jpg') using image recognition. It performs actions like clicking, sleeping, or navigating based on detected images, looping until the 'map.jpg' is found. If detected, it returns `True`; otherwise, i... | def moveToCity(screen='city', count=0):
sniffer()
counter = count + 1
print(f"Looking for city. Cycle # {counter}")
if counter % 5 == 0:
print("It's been ran 5 times")
sniffer()
if pyautogui.locateOnScreen('images/map.jpg', confidence=.8, grayscale=True):
print("Map found!")
time.sleep(random.uniform(1,... |
def testing(message='No Message Entered'):
'''If testing is marked as true, it will print the message'''
global testing
if testing:
print(f"{message}")
else:
pass
def circlepress(centerX, centerY, radius=10):
print("Pressing the circle.")
randomradius = random.randrange(0, radius)
angledegrees = random.randr... | The main task of the code is to ensure the game is on the "map" screen by locating a specific "city_button.jpg" image. If not found, it simulates a map press, waits, and retries up to 5 times. If still unsuccessful, it recursively retries with a cycle counter, exiting if failures exceed 4 attempts to avoid infinite loo... | def moveToMap(cycle=0):
global gameRegion
counter = 0
testing("Moving to Map")
if pyautogui.locateOnScreen('images/city_button.jpg', confidence=.8, grayscale=True, region=gameRegion) == None:
circlepress(628, 957, 32) #presses map
time.sleep(random.uniform(.8, 1.5))
while pyautogui.locateOnScreen('images/city... |
def moveToCity(screen='city', count=0):
sniffer()
counter = count + 1
print(f"Looking for city. Cycle # {counter}")
if counter % 5 == 0:
print("It's been ran 5 times")
sniffer()
if pyautogui.locateOnScreen('images/map.jpg', confidence=.8, grayscale=True):
print("Map found!")
time.sleep(random.uniform(1,... | The code automates using a "harvest" skill in a game by locating and clicking on-screen buttons, handling cooldowns via color checks, and navigating through menus. It moves to a city, identifies skill/harvest icons, presses them, waits for readiness (green button), and exits menus with predefined coordinates. Random de... | def daily_harvest():
print("Running Harvest Skills Check.")
moveToCity()
if pyautogui.locateCenterOnScreen('images/skills.jpg', grayscale=True, confidence=.8):
center = pyautogui.locateCenterOnScreen('images/skills.jpg', grayscale=True, confidence=.8)
circlepress(center[0], center[1]) #presses skills
time.slee... |
def moveToCity(screen='city', count=0):
sniffer()
counter = count + 1
print(f"Looking for city. Cycle # {counter}")
if counter % 5 == 0:
print("It's been ran 5 times")
sniffer()
if pyautogui.locateOnScreen('images/map.jpg', confidence=.8, grayscale=True):
print("Map found!")
time.sleep(random.uniform(1,... | The code automates interacting with virtual pinatas in a game by locating and pressing them using image recognition, handling outcomes like bombs or Fortune Teller events with specific actions and delays. It moves to a city location, checks for pinatas, presses them randomly, and responds to in-game visual cues with pr... | def daily_pinata():
print("Running Pinata.")
moveToCity()
if building_check('pinata'):
print("Pinata found!")
try:
center = building_check('pinata')
circlepress(center[0], center[1])
time.sleep(2)
except:
print("Pinata not found.")
time.sleep(2)
moveToCity()
return
listOfPinatas = pya... |
def _split_schemas_by_type(schemas):
"""
Sort schemas by type.
Parameters
----------
schemas: List[Dict]
Subschemas, specified as a list of dictionaries.
Returns
-------
Dict
A dictionary containing key-value pairs referring to each
schema type.
Examples
... | The function merges multiple subschemas into a unified list by separating them into objects and non-objects, merging object schemas, and adding unique non-object schemas. It returns the combined list of merged subschemas. | def _merge_schemas(schemas):
"""
Merge together subschemas.
Parameters
----------
node: Derek
Root node of tree.
strategy:
Schema extraction strategy.
Must be one of "permissive" (default), "restricted", or "inner_join".
Returns
-------
subschemas: List[Dic... |
def depth_first_numbering(T):
map = {} # map from positions to depth-first numbers
__depth_first_numbering(T.root, 0, map)
return map
def __tandem_repeats(root, depth, S, result, map, inv_map):
if not root.children:
return
large_leaf_list = None
for ch in root.children:
child = ... | The function `tandem_repeats` identifies tandem repeats in a tree structure. It first assigns depth-first indices to nodes, then uses a helper function to find branching tandem repeats. It then generates non-branching tandem repeats by left-rotating branching ones, adding valid results to `non_branching`. The output is... | def tandem_repeats(T):
map = depth_first_numbering(T)
inv_map = {v : k for k, v in map.items()}
branching = []
for node in T.root.children.values():
__tandem_repeats(node, string_depth(node.index), T.x, branching, map, inv_map)
non_branching = []
# claim: left-rotation of bran... |
def read_test_cases() -> Tuple[List[List[str]], List[str]]:
if test_cases_file.endswith(".gz"):
with gzip.open(test_cases_file, "rb") as g:
data = g.read()
try:
test_inp = json.loads(data)
except json.decoder.JSONDecodeError:
print(
f"Test ... | The main task of the code is to execute test cases for a solution, handling debug mode, selective test cases, speed testing, and other-language testing. It reads input/output test data, applies configurations like case limits, runs tests either one-by-one or all-at-once, and exits after debugging or external language t... | def main(path: str) -> None:
test_inp, test_out = read_test_cases()
if DEBUG_TEST:
case_number = (
DEBUG_TEST_NUMBER if 0 <= DEBUG_TEST_NUMBER - 1 < len(test_out) else 1
)
debug_solution(test_inp, test_out, case_number)
exit(0)
if 0 < NUMBER_OF_TEST_CASES < len(... |
def start_color_picking(self, combobox, checkbox):
self.selected_combo_color = combobox
self.selected_checkbox_color = checkbox
self.hide()
x_start, y_start, total_width, height, cropped_pixmap = self.color.capture_screen()
self.screen_capture = ScreenCapture(self, cropped_pixmap... | (The main task of the code is to initialize a GUI interface for a Shields.io image generator tool. It sets up UI elements like sliders, buttons, combo boxes, and color pickers for customizing logo, text, colors, and styles. The interface connects these controls to update a web browser preview and generate URLs/Markdown... | def init_ui(self):
link_style = '''
QLabel {
color: blue;
}
QLabel:hover {
color: green;
}
'''
self.setStyleSheet(link_style)
self.zoom_slider.setRange(100, 500)
self.zoom_slider.setValue(self.zoom_v... |
def get_run(self, id):
with self.run_cache_lock:
id = str(id)
if id in self.run_cache:
self.run_cache[id]['rtime'] = time.time()
return self.run_cache[id]['run']
run = self.runs.find_one({'_id': ObjectId(id)})
if not run:
run = self.old_runs.find_one({'_id': ObjectId(... | The function updates a task's statistics and status within a run, validating inputs and ensuring consistency. It checks if the task is active, verifies username and game counts, updates stats/nps, and triggers task completion or run termination based on SPRT/SPSA conditions. It also manages run state tracking and data ... | def sync_update_task(self, run_id, task_id, stats, nps, spsa, username):
run = self.get_run(run_id)
if task_id >= len(run['tasks']):
return {'task_alive': False}
task = run['tasks'][task_id]
if not task['active'] or not task['pending']:
return {'task_alive': False}
if task['worker_info... |
def format_results(run_results, run):
result = {'style': '', 'info': []}
# win/loss/draw count
WLD = [run_results['wins'], run_results['losses'], run_results['draws']]
if 'spsa' in run['args']:
result['info'].append('%d/%d iterations' % (run['args']['spsa']['iter'], run['args']['spsa']['num_iter']))
r... | The code retrieves and processes run data from a database, categorizing runs into states (pending, active, finished), calculates metrics like games per minute and pending hours, handles caching to optimize performance, and returns structured results with pagination for web display. | def tests(request):
username = request.matchdict.get('username', '')
success_only = len(request.params.get('success_only', '')) > 0
ltc_only = len(request.params.get('ltc_only', '')) > 0
do_cache = (len(username) == 0 and not success_only and not ltc_only
and request.params.get('page', 1) == 1)
... |
def y_or_n(s):
if s == "y" or s == "n" or s == "Y" or s == "N":
return True
else:
return False
def main():
auth = tweepy.OAuthHandler(API_key, API_secret)
auth.set_access_token(AT_token, AT_secret)
auth.secure = True
api = tweepy.API(auth)
names = api.trends_place(id=23424977... | The function `settings_acc` prompts the user to confirm posting a tweet (header + tweet) or generate a new one using a text model. If confirmed, it posts the tweet via API and restarts the main function. If declined, it asks to create a new short sentence, generates it via `text_model`, and recursively calls itself. In... | def settings_acc(tweet, header, text_model):
print("\n" + header + tweet)
print("\nDo you want to post this? (y/n)")
s = input()
# Check input parameter
while not y_or_n(s):
print("\nWrong parameter--\n")
print(header + tweet)
print("\nDo you... |
def y_or_n(s):
if s == "y" or s == "n" or s == "Y" or s == "N":
return True
else:
return False
def main():
auth = tweepy.OAuthHandler(API_key, API_secret)
auth.set_access_token(AT_token, AT_secret)
auth.secure = True
api = tweepy.API(auth)
names = api.trends_place(id=23424977... | This function allows users to edit a tweet by adding hashtags, confirm posting via Twitter API, generate a word cloud, or create a new tweet. It validates user inputs (y/n) for decisions on hashtag addition, posting, and word cloud generation, looping until valid input is received. If posting is skipped, it generates a... | def settings_topic(tweet):
print('________________\n')
print("\nDo you want to add #? (y/n)")
print(tweet)
s = input()
# Check input parameter
while not y_or_n(s):
print("\nWrong parameter--\n")
print(tweet)
print("\nDo you want to ad... |
def y_or_n(s):
if s == "y" or s == "n" or s == "Y" or s == "N":
return True
else:
return False
def main():
auth = tweepy.OAuthHandler(API_key, API_secret)
auth.set_access_token(AT_token, AT_secret)
auth.secure = True
api = tweepy.API(auth)
names = api.trends_place(id=23424977... | The code validates a Twitter username by checking its existence via an API. If invalid, it prompts the user to retry or exit, ensuring valid input through a loop. It recursively rechecks the username until valid or the user quits. | def check_acc(account):
try:
# q1q0q1q1q3 - Example of non-existent username
# Check if exist
api.get_user(account)
return account
except TweepError:
print("\nWrong username------\n")
print(account)
print("Want to try a... |
def load_files(N, Min, Max, wvls, path):
pix_scale = 0.0200549563786008 #number of arcseconds per pixel
tot_intensity = 7.16935519227643 #sum of all pixels, obtained from header
x = np.linspace(Max, Min, N) #arrays of all the x and y positions
y = np.linspace(Max, Min, N)
X,Y = np.meshgrid(x, y) #... | The code analyzes optical data across specified wavelengths by loading files, extracting parameters, and generating plots for FWHM, Strehl ratio, encircled energy, and ellipticity. It processes multiple wavelengths, visualizing key metrics for each, likely related to astronomical or optical system performance evaluatio... | def analysis(N, Min, Max, wvls, path, size):
psfs = load_files(N, Min, Max, wvls, path)
parameters = find_parameters(psfs, size)
for wvl in wvls:
grid(psfs, parameters, wvl, N)
plot_FWHM(parameters, wvl, N)
plot_strehl(parameters, wvl, N)
plot_ee50(parameters, wvl, N)
... |
def load_nirc2(nirc2_epoch):
"""
Loads NIRC2 data from a given observing night as a pandas dataframe
"""
nirc2_dir = f'{root_dir}{nirc2_epoch}/clean/kp/'
vprint("Message: NIRC2 file found: "+nirc2_dir)
### Check for Strehl file
if os.path.isfile(nirc2_dir + 'strehl_source.txt') == True:... | This function loads NIRC2 observational data, combines it with telemetry, seeing, and weather data from nearby timestamps, and returns a merged DataFrame for a master table. It handles data retrieval, date alignment, and NaN handling for incomplete matches. | def populate_df(nirc2_epoch, bad_data):
'''
This takes in a nirc2 epoch (two digit year, first three letters of month,
lgs, and a number if there were multiple days, ie. 04jullgs1), looks for and
downloads all associated cfht and seeing data, and returns the df to be
appended to a master table
'... |
def lik(omega,h):
if (h<=0 or omega<=0):
return -np.inf
elif (h>=1 or omega>=1):
return -np.inf
else:
l = 0
mu_theory = mu(z,omega,h)
for i in range(31):
for j in range(31):
diff1=(Mu[i]-mu_theory[i])
diff2=(Mu[j]... | The function computes the product of the exponential of a likelihood function `lik(omega, h)`, and two prior distributions `prior1(h)` and `prior2(omega)`, returning the unnormalized posterior probability `P` for parameters `omega` and `h` in a probabilistic model. | def target(omega,h):
P = np.exp(lik(omega,h))*prior1(h)*prior2(omega)
return P |
def get_location(raw_path):
if raw_path == '/':
return 'default'
else:
return raw_path.strip('/')
def get_location_data(location):
for stop_location_data in STOP_LOCATIONS_DATA:
if location == stop_location_data['location']:
return stop_location_data
def get_valid_service... | The code processes an incoming event to generate an HTML response containing ordered bus service data based on a location derived from the event's raw path. It retrieves location details, filters valid services, structures bus data, and returns the result as a text/html response with a 200 status code. | def handler(event, context):
print(event)
location = get_location(event['rawPath'])
stop_location_data = get_location_data(location)
valid_services = get_valid_services()
bus_services = order_bus_data(stop_location_data, valid_services)
html = gen_html(bus_services)
return {
'he... |
def _get_train_loader(self):
dataset = self._get_train_dataset()
dataloader = data_utils.DataLoader(dataset, batch_size=self.args.train_batch_size,
shuffle=True, pin_memory=True)
return dataloader
def _get_val_loader(self):
return self._get_eval... | The method `get_pytorch_dataloaders` creates and returns three PyTorch data loaders for training, validation, and testing by calling private methods `_get_train_loader`, `_get_val_loader`, and `_get_test_loader`. It encapsulates the process of preparing dataset splits and their corresponding DataLoader instances, enabl... | def get_pytorch_dataloaders(self):
train_loader = self._get_train_loader()
val_loader = self._get_val_loader()
test_loader = self._get_test_loader()
return train_loader, val_loader, test_loader |
def _get_preprocessed_dataset_path(self):
folder = self._get_preprocessed_folder_path()
return folder.joinpath('dataset.pkl')
def maybe_download_raw_dataset(self):
folder_path = self._get_rawdata_folder_path()
print(folder_path)
if folder_path.is_dir() and\
all(folder_... | This method preprocesses a dataset for a recommendation system by downloading raw data if necessary, converting ratings to implicit feedback, filtering items, mapping content to IDs, densifying indices, splitting into train/val/test sets, and saving the processed data as a pickle file. It skips processing if the datase... | def preprocess(self):
dataset_path = self._get_preprocessed_dataset_path()
if dataset_path.is_file():
print('Already preprocessed. Skip preprocessing')
return
if not dataset_path.parent.is_dir():
dataset_path.parent.mkdir(parents=True)
self.maybe_downl... |
def _get_preprocessed_dataset_path(self):
folder = self._get_preprocessed_folder_path()
return folder.joinpath('dataset.pkl')
def maybe_download_raw_dataset(self):
folder_path = self._get_rawdata_folder_path()
print(folder_path)
if folder_path.is_dir() and\
all(folder_... | The function retrieves a preprocessed dataset as a pandas DataFrame by ensuring the directory structure exists, downloading raw data if necessary, loading ratings, converting to implicit data, filtering triplets, and returning the processed DataFrame. | def get_preprocessed_dataset_as_pandas(self):
dataset_path = self._get_preprocessed_dataset_path()
if not dataset_path.parent.is_dir():
dataset_path.parent.mkdir(parents=True)
self.maybe_download_raw_dataset()
df = self.load_ratings_df()
df = self.make_implicit(df)
... |
def create_batches(self, data, labels, batch_size):
"""
Parameters
----------
data : np.array of input data
labels : np.array of input labels
batch_size : int size of batch
Returns
-------
list
list of tuples of (data batch of... | This code trains a neural network using Stochastic Gradient Descent (SGD) on provided training data. It iterates through epochs, splits data into mini-batches, performs forward and backward propagation, updates weights and biases with the learning rate, and optionally reports validation accuracy after each epoch if val... | def fit(self, training_data, validation_data=None):
"""Fit (train) the Neural Network on provided training data. Fitting is
carried out using Stochastic Gradient Descent Algorithm.
Parameters
----------
training_data : list of tuple
A list of tuples of numpy arrays, ... |
def compute_pseudo(self, bb_centre):
'''
Computes pseudo-coordinates from bounding box centre coordinates
'''
K = bb_centre.size(1)
# Compute cartesian coordinates (batch_size, K, K, 2)
pseudo_coord = bb_centre.view(-1, K, 1, 2) - \
bb_centre.view(-1, 1, K,... | The code computes image-text similarities by fusing contextual information from captions and images using positional and NTN relation weights. It processes each caption, expands it across image batches, and calculates pairwise similarity scores via Text2Image_fusion and Image2Text_score modules. Results are aggregated ... | def forward(self, images, captions, bbox, cap_lens, opt):
# bbox-->(batch_size, K, 4), k representations image regions or text words
similarities = []
n_block = opt.embed_size // opt.num_block
n_image, n_caption = images.size(0), captions.size(0)
bb_size = (bbox[:, :, 2:] - bbox... |
def nextStates(self, pos, vel, theta, ori, force):
# update positions, velocities
new_pos = pos + self.dt * vel
new_vel = vel + self.dt * (ori @ force).reshape(self.n_agent, 2)
# update orientations
def rotationMatrix(c, s):
return np.array([[c, -s], [s, c]])
... | The main task of the code is to process an action by applying forces to agents, compute next states, calculate rewards, update internal states, check if targets are reached, and return updated states, rewards, and completion flags. It involves physics simulation, reward calculation, and environment state management for... | def step(self, action):
# 1. apply forces
# start = time.perf_counter()
self.force = action.reshape(len(self.agents), 2, 1)
self.p_t1, self.v_t1, self.w_t1, self.o_t1 = self.nextStates(self.p_t, self.v_t, self.w_t, self.o_t, self.force)
self.updateStates()
# elapsed = tim... |
def get_profile(my_session,user_name):
profile = my_session.get_profile(username=user_name)
loaded_json = profile.json()
profile_did = str(loaded_json.get('did'))
profile_handle = str(loaded_json.get('handle'))
profile_displayName = str(loaded_json.get('displayName'))
profile_description = clea... | This code defines a command-line interface for interacting with the BlueSky social platform. It parses arguments for creating posts, deleting posts, replying to posts, fetching posts, following users, and retrieving profiles. The program reads authentication credentials from an INI file, establishes a session, and exec... | def main():
# Parse the passed arguments
parser = argparse.ArgumentParser(
prog='pBsky',
description='Comand line BlueSky client for Linux.')
parser.add_argument('-p', '--post', type=str,
help='create a post from the given string.')
parser.add_argument('-d', '--de... |
def in_board(pos, board):
"""returns True if pos (y, x) is within the board's Rect."""
return bool(board.rect.collidepoint(pos))
def drop_coin(self, mouse_pos):
"""Drop one coin from the top of the column closest to `mouse_pos`"""
board = self.board
board_xy = (self.settings.padding_lef... | The code runs a game loop for a turn-based game involving board rotation and coin placement, handling user/AI input, updating game state, checking for wins, and displaying a game-over screen with the winner. It manages UI interactions, music, and rendering, including rotating the board visually using blit_rotate, and r... | def run(self):
"""Run the game loop, then show game over screen after the game ends."""
clock = self.clock
music = self.music
screen = self.screen
settings = self.settings
ui_manager = self.ui_manager
board = self.board
angle = 0
target_angle = 0... |
def initPopulation(popSize, bounds):
population = []
for i in range(0,popSize):
indv = []
for j in range(len(bounds)):
indv.append(random.uniform(bounds[j][0],bounds[j][1]))
population.append(indv)
return population
def checkBounds(solutions, bounds):
updatedSolutions... | The code implements a Differential Evolution algorithm to optimize trading parameters. It iteratively evolves a population of parameter sets through mutation, recombination, and selection to maximize trade scores within specified bounds. The algorithm returns the best parameter solution, along with generation-wise aver... | def optimize(buyLimit, hyperparameters = [10,0.7,0.5,20]):
popSize = hyperparameters[0] # 10 Population size -> How many versions of parameters will be created in each generation
recombinationValue = hyperparameters[1] # 0.7 Recombination value -> Probability that an individual will take the mutated version of... |
def initialise_indicators(df):
bb_indicator = BollingerBands(df['close'],window=5)
#Adds upper band to dataframe
df['upper_band'] = bb_indicator.bollinger_hband()
#Adds lower band to dataframe
df['lower_band'] = bb_indicator.bollinger_lband()
#Adds smooth moving average to dataframe
df[... | The function `forward_test` evaluates trading strategies by applying optimized parameters to a test dataset, calculating success rates, and restoring the original data state. It updates a global dataframe with test data, initializes indicators, executes trades, assesses performance, then reverts the dataframe to its pr... | def forward_test(tradeParameters, buyLimit, test_data, df_previous):
# Refer to global df variable
global df
# Reassign df to test dataframe
df = test_data
# Initialise indicators for testing dataframe
initialise_indicators(df)
# Run the trade with optimised parameters
results = trad... |
def read_mltable_in_spark(mltable_path: str):
"""Read mltable in spark."""
spark = init_spark()
df = spark.read.mltable(mltable_path)
return df
def _compute_max_standard_deviation(df, std_deviation_threshold: float):
standard_deviations = df.agg(
*[stddev(column).alias(column) for column in ... | The code computes and saves signal metrics by calculating the maximum standard deviation from production data. It parses command-line arguments, reads data into a Spark DataFrame, processes it with a threshold value, displays results, and stores them as an ML table. | def run():
"""Compute metrics."""
# Parse argument
parser = argparse.ArgumentParser()
parser.add_argument("--production_data", type=str)
parser.add_argument("--std_deviation_threshold", type=str)
parser.add_argument("--signal_metrics", type=str)
args = parser.parse_args()
df = read_mlta... |
def _get_socket_addresses(self):
"""Get Socket address information.
:rtype: list
"""
family = socket.AF_UNSPEC
if not socket.has_ipv6:
family = socket.AF_INET
try:
addresses = socket.getaddrinfo(self._parameters['hostname'],
... | The code opens a socket connection by acquiring locks, initializing socket parameters, establishing a connection using retrieved addresses, setting up a poller for I/O monitoring, and launching an inbound thread for data handling, all while handling potential connection errors and ensuring thread safety through lock ma... | def open(self):
"""Open Socket and establish a connection.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:
"""
self._wr_lock.acquire()
self._rd_lock.acquire()
try:
self.data_in ... |
def transpose(array):#new function for transposing 2d array
l1=len(array)
l2=len(array[0])
NewArray=np.zeros((l2,l1))
for i in range(0,l1):
for j in range(0,l2):
NewArray[j][i]=array[i][j]
return NewArray
def rate(e,c,dis):# caculate the excitation rate
me=9.1e-31
e=np.ar... | The code calculates a ratio involving ACD (Atomic Collision Data) values and rate values derived from energy and cross-section data. It loads energy (E) and cross-section (C) data from a file, processes ACD data for multiple ionization stages, transposes energy and cross-section arrays, computes rates with smoothing, a... | def frac(fileacd,filec,z,dens,dis,disEgrid,te):
res = np.load(filec, allow_pickle=True)
E = res['energy']
C = res['sigma']
acd=[]
for i in range(0,z):
temp=adas.read_adf11(file=fileacd, adf11type='acd', is1=i+1, te=te, dens=dens, all=True)
acd.append(temp[0][0])
NewE=transpose(E)... |
def change_topology_add(route_topology, base_ip, base_port, new_ip, new_port):
# print("adding topology")
base_id = f"{base_ip},{base_port}"
new_id = f"{new_ip},{new_port}"
route_topology = link_nodes(route_topology, base_id, new_id)
return route_topology
def buildForwardTable(route_topology, ... | This function manages dynamic routing in a network by processing incoming packets (Hello, LinkState, Data), updating the route topology and forwarding table based on neighbor status and message sequences, sending periodic Hello messages, detecting node failures, and flooding LinkStateMessages to maintain consistent rou... | def createroutes(route_topology, forwarding_table, this_port):
# get the neighbors of the emulators we are currently on
neighs = route_topology[f"{this_ip_addr},{this_port}"]
latest_timestamps = {}
# latest timestamps set to current time
for neigh in neighs:
latest_timestamps[neigh] = time.... |
def readtopology(topology_file):
route_topology = {}
curr_line = topology_file.readline()
# show initial structure based on topology.txt
while len(curr_line) != 0:
neigh_parts = curr_line.split(" ")
route_topology[neigh_parts[0]] = []
for part in neigh_parts[1:]:
s_... | The code parses command-line arguments for a port and filename, binds a socket to the specified port, reads a network topology from the file, generates a forwarding table based on the topology, and creates routing configurations. It handles errors for socket binding and file access, then outputs the topology and forwar... | def main():
parser = argparse.ArgumentParser(description="gets emulator data")
parser.add_argument('-p', metavar='port')
parser.add_argument('-f', metavar='filename')
args = parser.parse_args()
try:
socket_obj.bind((this_ip_addr, int(args.p)))
except:
print("A socket error has... |
def read_train_data(pathSrc):
with open(pathSrc + '/train_pre_ntn.pickle', 'rb') as handle:
file = pickle.load(handle)
voc = np.load(pathSrc + "/voc.npy", allow_pickle=True).tolist()
return (file, voc)
def read_test_data(addr):
with open(addr + '/Data_from_before/ted_talks_pre_ntn.pickle', 'rb')... | The code performs hyperparameter tuning for a Naive Bayes classifier by systematically testing different Laplace smoothing values (from `laplace_smoothing_lower` to `laplace_smoothing_upper` in increments of `step`). It evaluates classifier accuracy for each smoothing parameter on test data, records results, and measur... | def bayesClassifier_hyper_par(laplace_smoothing_lower=0.2, laplace_smoothing_upper=2, step=0.1):
# path to read data from
pathSrc = str(pathlib.Path().absolute())
# read train data here
df_train, vocabulary = read_train_data(pathSrc)
print('read data.')
# read test data here
df_test = read_... |
def rotate_block(self) -> None:
self.block.cw_rotation()
if self.detect_collision():
self.block.undo_rotation()
def move_left(self) -> None:
if not self.detect_collision(-1):
self.block.move_left()
def move_right(self) -> None:
if not self.detect_collision(+1):
... | This method processes Pygame key events to control game actions: rotating the block (UP), moving left (LEFT), right (RIGHT), or down (DOWN), but only if the game is valid. It uses a match statement to dispatch events to corresponding methods, enabling player interaction with the game grid. | def event(self, event: Event) -> None:
if self.valid_game:
match event.key:
case pygame.K_UP:
self.rotate_block()
case pygame.K_LEFT:
self.move_left()
case pygame.K_RIGHT:
self.move_right()
... |
def move_down(self) -> bool:
if self.detect_collision(vertical_step=1):
if not self.block_is_inside_the_board():
self.game_over()
return False
else:
self.block.move_down()
return True
def incorporate_block_to_pile(self) -> None:
for... | This method processes a game frame by checking time intervals to move a block down, incorporating it into the pile if movement fails, processing completed rows, adding new blocks, and rendering the scene for a Tetris-like game. | def process_frame(self) -> None:
t = time.time()
if t - self.last_block_step >= self.step_interval and self.valid_game:
if not self.move_down():
self.incorporate_block_to_pile()
self.process_completed_rows()
self.add_new_block()
sel... |
def _conv_layer(self, net, num_filters, filter_size, strides, relu=True):
weights_init = self._conv_init_vars(net, num_filters, filter_size)
strides_shape = [1, strides, strides, 1]
net = tf.nn.conv2d(input=net, filters=weights_init, strides=strides_shape, padding='SAME')
net = self._ins... | The code defines a neural network model that processes an input image through a series of convolutional layers, residual blocks, and transposed convolutions to generate predictions. It upsamples features using transposed convolutions, applies a tanh activation, and scales output values for tasks like depth estimation o... | def build_model(self, image):
conv1 = self._conv_layer(image, 32, 9, 1)
conv2 = self._conv_layer(conv1, 64, 3, 2)
conv3 = self._conv_layer(conv2, 128, 3, 2)
resid1 = self._residual_block(conv3, 3)
resid2 = self._residual_block(resid1, 3)
resid3 = self._residual_block(resi... |
def kernel_density(x, h, nums, lb):
t = np.linspace(np.amin(x) - h, np.amax(x) + h, nums)
j_array = []
for item in t:
j_array.append(J(item, h, x) / (h * x.shape[0]))
plt.plot(t, j_array, label=lb)
return j_array
def plot_details(lesson):
plt.title("Distribution By School For : " + lesso... | The main task of the code is to generate two visualizations: first, a kernel density estimate (KDE) plot for a specified lesson across all schools using the `kernel_density` function, and second, an additional plot using the `Q1_d` function, which likely processes the data differently. The code labels the KDE plot as "... | def Q1_e(lesson):
plt.figure(2)
kernel_density(df[lesson].to_numpy(), 10, 50, "All Schools")
plot_details( "All Schools " + lesson)
plt.figure(3)
Q1_d(df, lesson) |
def test_inputs(fw_api, fw_project_id, yaml_file, rc_api, rc_url):
# Fail early, fail often
try:
fw = flywheel.Client(fw_api)
except Exception as e:
print('ERROR - invalid flywheel API, or site is unreachable')
print('Try copy/pasting these values to ensure accuracy')
print(... | The main task of the code is to translate and import records from a framework project to a RedCap project using a YAML configuration. It reads input data, processes records, maps fields via a YAML file, and imports transformed records into RedCap. The code handles data initialization, field mapping, and record translat... | def main(fwapi, projectID, yamlFile, rcAPI, rcURL):
fw, fw_project, rc_project = test_inputs(fwapi, projectID, yamlFile, rcAPI, rcURL)
with open(yamlFile) as file:
dict_in = yaml.full_load(file)
file.close()
record_field = get_record_field(dict_in)
calls = initialize_level_ma... |
def sign_in():
st.header('User Login')
email_login = st.text_input('Enter your email:', placeholder="ehzwh@example.com")
password_login = st.text_input('Enter your Password:', placeholder="Password", type="password")
forgot_password = st.checkbox("Forgot Password")
if forgot_password:
emai... | The code implements a login system with options for user sign-in, sign-up, and admin sign-in. It directs users to respective dashboards based on authentication, allowing non-admin users to upload CSV files (max 10MB) for data processing. Admins access a different dashboard. | def login():
user_input = st.radio('Please select an option:', options=['Sign In', 'Sign Up', 'Admin Sign In'], horizontal=True)
if user_input == 'Sign In':
sign_in()
if get_session_state().user:
if get_session_state().user[4] == 'bjymw@example.com': # Check if the user is admi... |
def get_search_meta_data(self):
return parse_search_meta_data(self._identity_order_field, self._order_fields,
self._search_fields, self._page_size_limit)
def _listing_key_set_actions(self, search_meta_data: SearchMetaData):
key_set_actions = []
if search_me... | This function fetches movie listings from MongoDB using an aggregation pipeline, applying filters, sorting, and limits based on search metadata. It constructs a pipeline with dynamic stages, executes the query, enhances results, and handles pagination by generating cursor tokens for subsequent requests when reaching th... | def fetch_listing(self, mongo: MongoClient, search_meta_data: SearchMetaData = None):
if search_meta_data is None:
search_meta_data = self.get_search_meta_data()
pipeline = [
*search_meta_data.digest(self._resource_fields),
*self._listing_key_set_actions(search_meta_... |
def clean_persons_name(self, entity_id):
"""
clean the name, de-plualize it in case this is a phone and we
don't have a person.
"""
name = self.friendly_name(entity_id)
name = name.split(' ')[0]
if name.endswith("'s"):
name = name[:-2]
retu... | This function tracks a person's presence by checking if their new state is in the home states. If true, it adds the person to the list using their cleaned name; otherwise, it removes them. The task involves conditional addition/removal of individuals based on state changes, ensuring consistent tracking with cleaned nam... | def track_person(self, entity, attribute, old, new, kwargs):
name = self.clean_persons_name(entity)
if new in STATES_HOME:
self.add_person(name)
else:
self.remove_person(name) |
def find_people(self):
for entity_id in self.entities:
if self.get_state(entity_id) in [ 'home' ]:
name = self.clean_persons_name(entity_id)
self.add_person(name)
if self.guest_entity_id:
if self.get_state(self.guest_entity_id) in ['on','enabled','... | This code initializes a sensor to track people based on entity states, setting up listeners for state changes, configuring logging, and populating initial data. It processes configuration arguments, creates a sensor entity, and dynamically updates the sensor state as tracked entities change, combining results using spe... | def initialize(self):
args = APP_SCHEMA(self.args)
# Set Lazy Logging (to not have to restart appdaemon)
self._level = args.get(CONF_LOG_LEVEL)
self.entities = args.get(CONF_ENTITIES, [])
self.guest_entity_id = args.get(CONF_GUESTS_ENTITY)
self._guest_name = args.get(CO... |
def start_encounter(self, user):
player_id = str(user.id)
encounter = self.encounters.get(player_id)
if encounter is None:
player = self.get_player(user)
if player.is_alive():
encounter = Encounter(player)
self.encounters.update({player_id:... | This function manages a player's encounter in a game. It checks for an existing encounter, starts a new one if none exists, processes the battle result, ends the encounter if the battle concludes, saves the player's state, and returns the battle outcome message. | def encounter_action(self, user):
player_id = str(user.id)
encounter = self.encounters.get(player_id)
if encounter is None:
new_encounter = self.start_encounter(user)
encounter = self.encounters.get(player_id)
if encounter is None:
return new_e... |
def _flush_changes(self) -> None:
statements = []
for i, row in enumerate(self._local_data):
if self._changed_row[i] & ChangedState.CREATED and self._changed_row[i] & ChangedState.DELETED:
continue
if self._changed_row[i] & ChangedState.DELETED:
statements.append(self._delete_stateme... | The main task of the code is to save the model's state by flushing changes, executing a query, resetting change flags, and clearing errors, while ensuring proper model reset handling through beginResetModel() and endResetModel(), with error handling via onError(). | def save(self) -> None:
self.beginResetModel()
try:
self._flush_changes()
self._make_query()
self._resetChanged()
self.clearError()
except Exception as e:
self.onError(e)
finally:
self.endResetModel() |
def import_data(filename):
data2 = pd.read_csv(filename)
data = data2[["full_text"]].copy()
edited_response = data['full_text'].copy()
data['Edited_Response'] = edited_response
return data
def preprocess(data):
preprocess_Reviews_data(data,'Edited_Response')
rem_stopwords_tokenize(data,'Edited_Response')
make_s... | The main task of the code is to process data by importing a cleaned dataset, preprocessing it, analyzing sentiment (e.g., labeling text polarity), and writing the sentiment-labeled results back to a file. The workflow includes data loading, transformation, sentiment analysis, and output storage for downstream use. | def main():
data = import_data(clean_file)
data = preprocess(data)
data = make_sentiment(data)
write_sent(clean_file, data) |
def generate_descriptions_for_blocks(self, show=False):
print('------ Generate Block Descriptions ------')
# short, long_blocks: list of block vh
leaves, blocks = self.partition_element_to_leaves_and_blocks(self.gui.element_tree)
# for leaves, use vh directly
self.block_descripti... | The main task of the code is to identify and interact with GUI elements based on a given task. It analyzes block descriptions to locate target elements, prioritizing direct matches, then checks scrollable blocks for navigation, and finally identifies indirectly related blocks. The function returns 'click' with an eleme... | def ai_chain(self, task=None, load_block_desc=False):
self.task = task
# Block description
if not load_block_desc:
self.generate_descriptions_for_blocks()
else:
self.load_block_descriptions()
# 0. Identify elements through leaves node vh
ele_id = s... |
def get_rules(root):
rules = []
if len(root.children) > 0:
rules, tokens = get_rule(root)
# for i, _ in enumerate(rules):
# print("rule lhs:\n{}".format(rules[i].lhs.token))
return rules
def rules_as_dict(rules):
rules_dict = defaultdict(list)
for rule in rules:
rules_di... | The code processes a list of UASTs by extracting rules and nodes, counts their occurrences, calculates statistical metrics (mean, standard deviation) of rule lengths, and returns sorted lists of rules and nodes by frequency. It aggregates rules, analyzes their structure, and outputs summary statistics for further analy... | def process_uasts(uasts):
rules_dict = defaultdict(int)
rules = []
antecedents_length = []
for uast in uasts:
rule = get_rules(uast)
rules.extend(rule)
for rule in rules_dict.keys():
antecedents_length.append(len(rule.rhs))
rules_dict = rules_as_dict(rules)
nodes ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.