dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_fonts(self):
self.label_font = QtGui.QFont()
self.label_font.setPointSize(22)
def setup_ui(self):
# setup grid layout
grid = QtGui.QGridLayout()
grid.setSpacing(15)
# add manga chooser
grid.addWidget(QtGui.QLabel('Load manga: '), 0, 0)
grid.addW... | The code initializes a LoaderWindow by setting up its GUI components, connecting to a parent window, initializing a manga plugin, configuring fonts, and establishing signal-slot connections for functionality. It prepares the window's structure, loads necessary resources, and prepares event handling for user interaction... | def __init__(self, parent):
super(LoaderWindow, self).__init__(parent)
self.main_gui = parent
self.manga_store_path = os.getcwd()
self.plugin = MangaFoxPlugin.MangaFoxPlugin()
self.manga_list = []
self.create_fonts()
self.setup_ui()
self.set_signals_and_sl... |
def recalc_height(self, node):
if node == None:
return
node.height = max(self.height(node.left), self.height(node.right)) + 1
def bfactor(self, node):
if node == None:
return 0
return self.height(node.right) - self.height(node.left)
def right_rotation(self, q):
... | This code balances an AVL tree node by checking its balance factor. If the factor is ±2, it performs left or right rotations to restore balance, with additional rotations on child nodes if needed. The function ensures the tree maintains height balance for efficient operations. | def balance(self, node):
self.recalc_height(node)
if self.bfactor(node) == 2:
if self.bfactor(node.right) == -1:
node.right = self.right_rotation(node.right)
return self.left_rotation(node)
if self.bfactor(node) == -2:
if self.bfactor(node.left... |
def find_biggest_element_from_left(self, node):
if node.right == None:
return node
else:
return self.find_biggest_element_from_left(node.right)
def unlink_biggest_element_from_left(self, node):
if node.right == None:
return node.left
else:
... | This function recursively deletes a node with value x from a binary tree. If the node is found, it replaces it with the largest element from its left subtree, reconnects remaining children, and rebalances the tree to maintain structural integrity. | def del_helper(self, node, x):
if node == None:
return
elif node.value > x:
node.left = self.del_helper(node.left, x)
elif node.value < x:
node.right = self.del_helper(node.right, x)
elif node.value == x:
if node.left == None:
... |
def mode_qlt(data_list):
count_dict = Counter(data_list)
top_mode = count_dict.most_common(2)
if len(top_mode) < 2:
return top_mode[0][0]
if top_mode[0][1] == top_mode[1][1]:
return "There's no unique mode"
else:
mode = top_mode[0][0]
return mode
def chooseSplit(self, x)... | This code implements a decision tree learning algorithm (DTL) that recursively splits data into subsets based on attribute values. It stops splitting when data size is below a threshold or all values in a column are identical, assigning labels based on the mode of the target column. If splitting continues, it selects t... | def DTL(self, data, min_leaf):
if len(data) == 0:
n = TreeNode(data)
return n
data_T = [[row[i] for row in data] for i in range(len(data[0]))]
stop_split = False
if len(data) <= min_leaf:
stop_split = True
for i ... |
def find_images_and_labels(self, imageDir, labelFile):
# find image
self.images = []
for file in os.listdir(imageDir):
if os.path.isdir(os.path.join(imageDir,file)):
continue
else:
imgFile = os.path.join(imageDir,file)
self.... | The code initializes a GUI application for image navigation and labeling. It binds left/right arrow keys to handle image traversal, loads images and labels, sets up a canvas for display, and prepares YOLO output. The class manages image indexing, user input, and visualization, enabling interactive image annotation or a... | def __init__(self, parent, image, label, output):
self.root = parent
self.root.bind('<Left>',self.left_pressed)
self.root.bind('<Right>',self.right_pressed)
self.find_images_and_labels(image, label)
self.max_count = len(self.images)-1
self.counter = 0
self.create_... |
def _validate_elements_sequence(self, elements):
# exclude strings to not detect them below as sequence
valid_string_types = (str, bytes)
if isinstance(elements, valid_string_types):
raise TypeError(f'Passed value has type "{type(elements)}" but a sequence is expected')
sequ... | The code's main task is to send a sequence of elements by validating them, establishing a connection, preparing a compressed payload with an adjusted window size, transmitting the payload, and waiting for an acknowledgment. It ensures proper data transmission through validation, compression, and acknowledgment handling... | def send(self, elements):
self._validate_elements_sequence(elements)
self.connect() # lazy init
self._reinit_last_ack()
self._window_size = self._factor_window_size(elements)
payload = self._factor_payload(elements)
compressed_payload = self._compress_payload(payload)... |
def interval_to_seconds(interval, default = 60):
# Convert the scheduler_interval from the config into seconds
interval_seconds = default
if interval.endswith('s'):
interval_seconds = int(interval[:-1])
elif interval.endswith('m'):
interval_seconds = int(interval[:-1]) * 60
elif inte... | The main task of this code is to monitor specified files for changes, read new content, and send it to a Lumberjack server or log it, with configurable behaviors for file handling (e.g., deletion, flushing). It tracks file positions, persists them periodically, and adapts to dynamic configurations, ensuring continuous ... | def monitor_files_background_job():
# Get the globs from the configuration
filenameGlobs = config.get('scriptablebeat', {}).get('data_stream', {}).get('files', {}).get('paths', [])
data_stream__monitor_sources = config.get('scriptablebeat', {}).get('data_stream', {}).get('moniror_sources', [])
filemonit... |
def searchID(id):
books = allBooksStripped()
for line in books:
bookId = line[0]
if (int(bookId) == int(id)):
return line
return (False)
def showLikedBook(bookId):
datas = logFileRead()
amountCheckedOut = 0
for entry in datas:
if (str(entry[0]) == str(bookId)... | The main task of the code is to display detailed information about a book, including its ID, genre, title, author, price, purchase date, and check-out count. If `showStatus` is True, it also shows the book's status. The function retrieves data using `searchID` and `showLikedBook`, then prints the results in a formatted... | def displayBookInfo(bookId, showStatus):
book = searchID(bookId)
print("Book ID: " + book[0])
print("Genre: " + book[1])
print("Title: " + book[2])
print("Author: " + book[3])
print("Price: " + book[4])
print("Date Purchased: " + book[5])
amountCheckedOut = showLikedBook(book[0])[1]
... |
def _get_parameters(path, **kwargs):
""" Sets the parameters, adding defaults if not set """
# Read json file if path contains a json file
if path.lower().endswith('.json'):
with open(path, encoding='utf-8') as file:
parameters = json.load(file)
for key, val in parameters.items... | (The code presents a fullscreen photo slideshow using Tkinter, displaying images from a specified directory. It initializes a window, binds stop/skip controls (Escape, Double-Click, Space), loads images sequentially with delays, and updates the display dynamically. Parameters manage slideshow behavior, including pausin... | def present(path: str, **kwargs: dict):
"""
Present the photo slideshow. AKA "Run It"
:param path: the path to the root directory for the photos
:param kwargs: The parameters, see the tutorial and how to guide for options
"""
parameters = _get_parameters(path, **kwargs)
win = tk.Tk()
w... |
def get_royal_flush(self):
self.get_straight_flush()
if self.get_straight_flush()[0] and set(['A', 'K', 'Q', 'J', '10']).issubset([s[1] for s in self.straight_flush]):
return True, self.straight_flush
else:
return False, []
def get_straight_flush(self):
suits = []... | This function determines the ranking of a poker hand by checking for specific combinations in descending order of strength, returning an integer value (0-9) corresponding to the hand's priority, where 0 is the highest (royal flush) and 9 is the lowest (high card). | def recognize_hand_ranking(self):
if self.get_royal_flush()[0]:
return 0
elif self.get_straight_flush()[0]:
return 1
elif self.get_four_of_a_kind()[0]:
return 2
elif self.get_full_house()[0]:
return 3
elif self.get_flush()[0]:
... |
def populate_graph_joint_links(self):
"""Populate directed links between bodies with joints"""
if self.assembly_data["joints"] == None:
return
for joint_uuid, joint in self.assembly_data["joints"].items(): # TODO: Question - no "joints" in dataset?
# TODO: Consider links... | The main task of the code is to generate graph links between mechanical bodies using joints and contact data. It checks for "joints," "as_built_joints," and "contacts" in the assembly data, then calls corresponding methods to create graph connections. This builds a structural relationship map for the assembly, enabling... | def populate_graph_links(self):
"""Create links in the graph between bodies with joints and contacts"""
if "joints" in self.assembly_data:
self.populate_graph_joint_links()
if "as_built_joints" in self.assembly_data:
self.populate_graph_as_built_joint_links()
if "... |
def populate_graph_nodes(self):
"""
Recursively traverse the assembly tree
and generate a flat set of graph nodes from bodies
"""
# First get the root and add it's bodies
root_component_uuid = self.assembly_data["root"]["component"] # root > component
root_comp... | The main task of the code is to retrieve graph data by populating nodes, links, and edges through helper methods, processing links further, and returning the structured graph components as lists. | def get_graph_data(self):
"""Get the graph data as a list of nodes and links"""
self.graph_nodes = []
self.graph_links = []
self.graph_edges = []
self.graph_node_ids = set()
self.populate_graph_nodes() # Populate "nodes" list
# print(self.graph_nodes)
s... |
def getAllPossibleMoves(self):
moves = []
for row in range(8):
for col in range(8):
turn = self.board[row][col][0]
if(turn == 'w' and self.whiteToMove) or (turn == 'b' and not self.whiteToMove):
piece = self.board[row][col][1]
... | The code filters valid moves by checking if each move leaves the king in check. It iterates through possible moves, simulates each, and removes invalid ones. It also determines checkmate or stalemate if no valid moves remain, then returns the filtered list of valid moves. | def getValidMoves(self):
#1 get all possible moves
moves = self.getAllPossibleMoves()
#2 make move
for x in range(len(moves)-1, -1, -1):
self.makeMove(moves[x])
#3 generate all opponents moves, see if king is attacked
#4 if attacked, not vali... |
def is_corner_curve(corner):
""" is the corner curved? """
is_curve = "wallIsCurved" in corner and corner["wallIsCurved"]
safe_curve = "wallCurve" in corner and abs(corner["wallCurve"]) < 180
return is_curve and safe_curve
def parse_corner(corner):
""" Parse a single corner """
return [ corner[... | The function `add_floor` processes architectural floor data by iterating through `corner_array` to parse walls and arches. For each corner, it checks if it's a curve, generating curved wall segments using `curve.main()` if true. Otherwise, it processes arches via `parse_arch()`. Corners are parsed and added to the outp... | def add_floor(corner_array, arch_array):
""" parse the entire floor """
global floor_array
out = []
corner_prev = corner_array[-1]
i = 0
for corner in corner_array:
if is_corner_curve(corner):
radians = corner["wallCurve"] / 180.0 * np.pi
corner_prev_pt = parse_c... |
def remove_duplicates(wall):
"""" remove dupicates from an array of 2D points """
if len(wall) != 0:
# remove duplicates
corner_prev = wall[0]
i = 1
while i < len(wall):
corner = wall[i]
if corner[0] == corner_prev[0] and corner[1] == corner_prev[1]:
... | This function triangulates a polygon by recursively dividing it into non-overlapping triangles. It removes duplicate points, checks the polygon's orientation, and iteratively selects triangles using a modified ear-clipping approach. The process continues until all vertices are processed, with indices tracking triangle ... | def triangulate(points):
""" converts a polygon into triangles """
global indices
points = remove_duplicates(points) # This must happen!
indices = []
n = len(points)
if n < 3:
return points
v_array = list(range(n))
if get_area(points) < 0:
v_array.reverse()
nv = ... |
def reset():
""" reset all arrays """
global floor_array
global window_array
global door_array
floor_array = []
window_array = []
door_array = []
def parse_json_room(room_array):
""" Parse a single room """
for room in room_array:
try:
arch_array = []
... | The function `parse_json` parses a JSON input from Ensemble by checking its version compatibility, processing room data if valid, and returning parsed elements like floor, window, and door information. | def parse_json(data):
""" Parse an entire JSON from Ensemble """
global arch_array
reset()
if "rooms" in data:
version_array = data["rooms"]
supported = ["1.0.4", "1.0.7", "1.0.8" ]
if version_array["version"] in supported and "rooms" in version_array:
room_array... |
def update_style(self):
# color
target_color = self.compute_color()
if self.cur_color is None:
self.cur_color = target_color
self.cur_color = lerp_vec(self.cur_color, target_color, 0.5)
# width
target_width = self.compute_width()
if self.cur_width is ... | This code updates an object's visual state by drawing lines between positions, rotating a player sprite along a path using interpolation, and incrementing the animation tick with delta time, while checking if the animation is finished or in progress. | def update(self):
if self.is_finished:
return
self.update_style()
num_positions = min(len(self.positions), math.ceil(self.tick))
num_positions_2 = min(len(self.positions), math.floor(self.tick))
if num_positions_2 > 2:
pygame.draw.lines(layers[0], self.... |
def parse_version(self) -> int:
return self.parse_bits(3)
def parse_type(self) -> Type:
return Type(self.parse_bits(3))
def parse_literal(self) -> int:
literal = ""
while True:
has_next, section = self.parse_literal_section()
literal += bin(section)[2:].zfill(4)
... | The main task of the code is to parse a packet by reading its version and type, then recursively extracting either a literal value or a list of sub-packets based on the length type. It returns a structured `Packet` object containing the parsed data, version, type, value, and the byte span of the packet. | def parse_packet(self):
start = self.pointer
version = self.parse_version()
type = self.parse_type()
if type == Type.LITERAL:
value = self.parse_literal()
else:
value = []
length_type_id = self.parse_length_type_id()
if length_ty... |
def get_auth_user(self, username, email, password):
"""
Retrieve the auth user from given POST payload by using
either `allauth` auth scheme or bare Django auth scheme.
Returns the authenticated user instance if credentials are correct,
else `None` will be returned
"""
... | The code validates user credentials by checking the existence of a user via username, email, and password. It verifies the user's active status and, if applicable, confirms email verification. If invalid, it raises an error; otherwise, it attaches the validated user to the attributes and returns them. | def validate(self, attrs):
username = attrs.get("username")
email = attrs.get("email")
password = attrs.get("password")
user = self.get_auth_user(username, email, password)
if not user:
msg = _("Unable to log in with provided credentials.")
raise exceptio... |
def _prepare_data(self, values_real, values_pred):
assert len(values_real) == len(values_pred)
# assert np.allclose(np.unique(values_real), np.array([0, 1]))
# assert np.allclose(np.unique(values_pred), np.array([0, 1]))
if self.metric_option == "classic":
real_anomalies = ... | This function calculates precision, recall, and Fβ score for anomaly detection by comparing real and predicted anomalies. It validates input arrays, prepares data, computes metrics, and returns them. Fβ uses a weighted harmonic mean with β², defaulting to 0 if precision+recall=0. | def score(self, values_real, values_predicted):
assert isinstance(values_real, np.ndarray)
assert isinstance(values_predicted, np.ndarray)
real_anomalies, predicted_anomalies = self._prepare_data(
values_real, values_predicted)
precision = self._update_precision(real_anomalie... |
def _prepare_data(self, values_real, values_pred):
assert len(values_real) == len(values_pred)
# assert np.allclose(np.unique(values_real), np.array([0, 1]))
# assert np.allclose(np.unique(values_pred), np.array([0, 1]))
if self.metric_option == "classic":
real_anomalies = ... | This function calculates the F-beta score for evaluating anomaly detection performance, combining precision and recall using a weighted harmonic mean adjusted by the beta parameter. It prepares real and predicted anomaly data, computes precision and recall, then applies the F-beta formula, returning 0 if precision and ... | def f_beta(self, values_real, values_predicted):
# if np.sum(values_real) == 0 or np.sum(values_predicted) == 0:
# return 0
real_anomalies, predicted_anomalies = self._prepare_data(
values_real, values_predicted)
precision = self._update_precision(real_anomalies, predicte... |
def make_grid(rows, width, generate_grid=False):
grid = []
visited = []
gap = math.ceil(width / rows)
for i in range(rows):
grid.append([])
for j in range(rows):
spot = Spot(i, j, gap, rows)
grid[i].append(spot)
for i in range(rows ):
visited.append([]... | This code implements a pathfinding visualization tool using Pygame. It allows users to set start/end points, create barriers, and execute DFS, BFS, or A* algorithms to find paths on a grid. The main task is to handle user interactions for grid modification, algorithm selection, and real-time pathfinding visualization w... | def main(win, width):
ROWS = 75
grid = make_grid(ROWS, width)
start = None
end = None
run = True
started = False
while run:
draw(win, grid, ROWS, width)
for event in pygame.event.get():
if(event.type == pygame.QUIT):
run = False
... |
def __boxes_neighbors(self,state):
near_box = self.__neighbors(state,self.box)
return near_box
def __reachable_locations(self,state):
state = np.copy(state)
open_floor_and_player = ((state==self.player)|
(state==self.empty)|
... | The code identifies valid actions to move boxes by finding the intersection of positions adjacent to boxes and reachable locations, then determining feasible moves from those positions. | def get_possible_actions(self, state):
next_to_boxes = self.__boxes_neighbors(state)
reachable_locations = self.__reachable_locations(state)
reachable_next_to_box = self.__get_intersected_indexes(
next_to_boxes,reachable_locations)
valid_actions = self.__find_locations_action... |
def clear():
if platform.system() == "Windows":
os.system("cls")
else:
os.system("clear")
def attack(attacker, defenser, magicial, damage=None):
if attacker.human and magicial == "0":
print("You attacked!")
if magicial == "0" or magicial == "2":
if hasattr(defenser, 'shines') and defenser.shines... | The code simulates a turn-based battle between a main character (mainc) and an attacker. It displays HP/TP stats, allows color-specific actions (attack, heal, TP gain, magic), processes user input to execute chosen actions, and alternates turns until one character dies. The outcome is declared based on who remains aliv... | def fight(mainc, attacker):
print(f"{attacker.name} appeard!")
while mainc.alive and attacker.alive:
clear()
print(f"Enemy HP:{attacker.health}")
print(f"Your HP:{mainc.health}, Your TP: {mainc.tp}")
if mainc.color == "red":
userinput2 = input("1 for attack, 2 for health, 3 for TP, 4 for magic... |
def imageContours(self,
thresh, minMarkerPerimeterRate = 0.05, maxMarkerPerimeterRate = 4,
polygonalApproxAccuracyRate = 0.05, minCornerDistanceRate = 0.05,
minMarkerDistanceRate = 0.05):
#Find contours
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPL... | The main task of the code is to detect AruCo markers in an input image by converting it to grayscale, applying adaptive thresholding, extracting contours, isolating potential markers, identifying their AruCo IDs, and drawing these IDs on the original image for visualization. | def detect(self, img):
# Create a copy of original image to prevent overwriting
image = img.copy()
# Convert to Grayscale and apply adaptive thresholding
imgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(imgray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, ... |
def game_init(self, tick):
print(tick.map.topology)
print(tick.map.tideLevels)
for y in range(len(tick.map.topology)):
for x in range(len(tick.map.topology[y])):
if tick.map.topology[y][x] >= (tick.map.tideLevels.min + tick.map.tideLevels.max) // 2:
... | This function determines the next action for an agent navigating a map with tide levels and ports. It initializes the game, tracks position and movement, calculates blocked tiles, finds the nearest unvisited port via pathfinding, and returns actions like Sail, Dock, or Anchor based on movement status, path availability... | def get_next_move(self, tick: Tick) -> Action:
print()
print()
if tick.currentLocation is None:
self.game_init(tick)
return self.return_move(Spawn(tick.map.ports[0]))
self.current_tide = tick.tideSchedule[
0] # min(tick.tideSchedule[2], (tick.map.t... |
def parse_func_call_node(root, node, is_if_node = False):
assert node['_nodetype'] == 'FuncCall'
print("Function Call Node Found")
func_call = node['name']['name']
temp_node = SimplifiedAstNode('FuncCall', func_call)
if is_if_node:
root.calls.append(temp_node)
print("Function call in... | This function parses a function definition node into a simplified AST by creating a function node, iterating through its body items, and delegating parsing of statements (function calls, assignments, if-else) to specialized handlers, returning the structured AST node. | def parse_function_definition(node):
assert node["_nodetype"] == 'FuncDef'
items_in_function_block = node["body"]["block_items"]
function_name = node["decl"]["name"]
function_root_node = SimplifiedAstNode('FuncDef', function_name)
num_block_items = len(items_in_function_block)
for item in items... |
def StartNextSong( self):
# Clear item colors
for i in range( self.MediaList.GetItemCount()):
if self.MediaList.GetItemTextColour(i) != wx.TheColourDatabase.Find("BLACK"):
self.MediaList.SetItemTextColour(i, wx.TheColourDatabase.Find("BLACK"))
# First find the fi... | The code updates a time slider and related UI elements based on media playback status. It checks for a blanking timer, triggers next song transitions, adjusts slider ranges dynamically, and updates time labels (current time and remaining time) while playback is active. If playback ends, it resets the slider and labels. | def OnTimer(self, evt):
"""Update the time slider according to the current movie time.
"""
# Check for blanking after starting to play
if self.TimerBlank:
self.TimerBlank -= 1
return
# See if we need to start the next song
time_until_start... |
def OnStop(self, evt=None):
"""Stop the player.
"""
self.IsPlayingToEndTime = False
self.player.stop()
self.timer.Stop()
self.StatusBar.SetStatusText("")
self.timeslider.SetValue(0)
self.timeText.SetLabel("")
self.timeToEndText.SetLabel("")
... | The code handles right-click menu selections to play media, update playback timing, or delete items. For 'Play This', it stops current playback, loads the selected media, and starts playback. For 'Play From Here', it sets start times for subsequent items, updates the playlist, and initiates playback. 'Delete' removes t... | def OnRightMenuSelect(self, event):
"""
Handle a right-click event.
"""
if (self.menuItems[event.GetId()] == 'Play This'):
self.OnStop()
self.player.set_media(self.MediaList.GetItemCollectionData( self.ItemIndexRightClicked, "media"))
if self.player.pl... |
def go_left(self):
"""Move player left."""
self.shape("player_left.gif")
self.handle_event(self.xcor() - BLOCK_PIXEL_SIZE, self.ycor())
def go_right(self):
"""Move player right."""
self.shape("player_right.gif")
self.handle_event(self.xcor() + BLOCK_PIXEL_SIZE, self.ycor(... | The main task of the code is to execute a sequence of directional moves by iterating through the input list and calling corresponding methods (go_left, go_right, go_down, go_up) based on each move's value ('L', 'R', 'D', 'U'). | def vizualize(self, moves):
"""
Make sequence of moves.
moves -- list of moves
"""
for move in moves:
if move == 'L':
self.go_left()
elif move == 'R':
self.go_right()
elif move == 'D':
self.go_do... |
def get_formula_sheet(gc, spreadsheet_key):
sh = gc.open_by_key(spreadsheet_key)
worksheet = sh.sheet1
formula_sheet = worksheet.get_values(value_render_option='FORMULA')
return formula_sheet
def get_elements(formula_sheet):
edges = find_edges(formula_sheet)
cell_names = list(set([edge[0] for... | This function generates a Cytoscape graph visualization component using data from a spreadsheet. It retrieves formula sheet data, extracts graph elements and layout, then constructs a styled Cytoscape instance with customized node/edge appearance, responsive sizing, and dark theme styling. The component displays molecu... | def build_cytoscape_component(gc, spreadsheet_key, id):
formula_sheet = get_formula_sheet(gc, spreadsheet_key)
elements = get_elements(formula_sheet)
layout = get_layout(formula_sheet)
return cyto.Cytoscape(
id=id,
layout=layout,
stylesheet=[
{
'sele... |
def log(text):
print(text)
logFile.write(text + "\n")
def showIntro(win):
win.setBackground("light blue")
titleText = Text(Point(500, 200), introTitle)
titleText.setSize(20)
titleText.setStyle('bold')
descText = Text(Point(500, 250), introDesc)
descText.setSize(15)
startText = Te... | The main task of the code is to create a graphical window for a game titled "Escape Castle," log the start of a new session, display an introduction and menu screens, and then close the window and log file. The code initializes a graphics window, records session data, and executes game setup functions before terminatin... | def main():
win = GraphWin("Escape Castle", 1000, 500)
# log = open(logFileName, "a")
log("\n## New game session")
showIntro(win)
showMenu(win)
win.close()
log.close() |
def get_frequent_headers(n_frequent):
"Parses the MIMIC csv, grabbing only the `n_frequent` most frequent headers"
lab_headers = get_headers('labevents')
r_headers = get_realvalue_headers()
vs_headers = list(set(r_headers)-set(lab_headers))
count_headers, _ = number_non_missing()
count_headers.... | The code processes ICU patient data by extracting time series features, static data, and labels. It groups data by ICU stays, filters invalid entries, and compiles time series, timestamps, static features, mortality labels, and predicted survival times into structured lists for modeling. | def get_data(n_frequent):
ts_headers = get_frequent_headers(n_frequent=n_frequent)
sta_data, la, la_time = get_static_data()
mimic = parse_csv(['icustay_id', 'hour'] + ts_headers + ['F pred hours_until_death'], dtype=None)
mimic['F pred hours_until_death'] = mimic['F pred hours_until_death'].apply(... |
def get_offline(self, domain):
return self.dns_offline().get(domain)
def get_cache(self, domain):
return self.cache.get(domain)
def add_cache(self, domain, addr):
ping_time = self.check_work_ip(addr)
if ping_time:
self.cache[domain] = {"addr": addr, "ping": ping_time}
def gen... | This code resolves a domain's IP address by checking cached results (if available) based on priority settings, then fallback to offline data or DNS lookup if needed. It prioritizes cached or offline IPs when enabled, otherwise uses DNS resolution as a last resort. | def query(self, domain):
ip_offline = self.get_offline(domain)
ip_cache = self.get_cache(domain)
if ip_cache != None:
ip_cache =ip_cache.get("addr")
if self.conf.get_priority() == True:
if ip_offline:
self.add_cache(domain, ip_offline)
... |
def get_sni(self, data):
data = TLS(data)
tls_ext = data[TLS].msg[0][TLS_Ext_ServerName][0]
return tls_ext[ServerName].servername.decode()
def clflr_range_ping(self, domain):
try:
clflr_range = self.conf.clflr_range()
for clflr_ip in clflr_range:
c... | This function checks if a host is in the 'clflr' list, retrieves its IP address via DNS or range ping, and returns the host with port 443. It first checks existing records, queries DNS if needed, validates the IP, and falls back to range ping if validation fails. | def check_clflr(self, data):
host = self.get_sni(data)
if host in self.clflr:
if host in self.clflr_ip:
clflr_ip = self.clflr_ip.get(host)
else:
clflr_ip = self.clflr_range_ping(host)
else:
is_clflr = self.exists_header_clflr(ho... |
def PhaseA1(storm:list, outputfile:str)->print(list):
'''
This function is for PhaseA1: calculating some stats data, which includes [ID, name,
date_min,data_max, MSW, dt3,tm3, landfall_count]
:param storm: is the storm in the format of list that just read from original text file.
:param outputfile: ... | The main task of the code is to analyze hurricane data from the HURDAT2 file (e.g., Atlantic or Pacific storms) by processing each storm record, counting annual storms/hurricanes (PhaseA2), and performing additional analyses (PhaseB1–B3). It writes summaries to an output file, including yearly storm/hurricane counts an... | def Main(filestr:str):
"""
This is the main program for this assignment.
:param filestr: the file name for different filenames. eg: Main('hurdat2-1851-2016-041117.txt') # AL
:return: no need to return, the output has been written in the target file.
"""
# get ready for the output
outputfile... |
def init_argparse() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
usage="%(prog)s --db-host [OPTION] --db-user [OPTION] --db-password [OPTION] --db-database [OPTION] ...",
description="Export OPML based on definitions."
)
parser.add_argument(
"--db-host", action='store', dest='db_hos... | The main task of the code is to process domains from a MySQL database by filtering excluded domains, generating a master list of domains with more than two links, handling missed URLs, enriching the domain list with additional data, and saving results to YAML files. It also connects/disconnects from the database using ... | def main() -> None:
parser = init_argparse()
args = parser.parse_args()
if(
(args.db_host) and
(args.db_user) and
(args.db_password) and
(args.db_database)
):
print(f"host : {args.db_host}")
print(f"user : {args.db_user}")
print(f"password : {args.db_password}")
print(f... |
def bounding_ellipsoid(points, pointvol=0.):
"""
Calculate the bounding ellipsoid containing a collection of points.
Parameters
----------
points : `~numpy.ndarray` with shape (npoints, ndim)
A set of coordinates.
pointvol : float, optional
The minimum volume occupied by a sing... | The code updates a set of ellipsoids to tightly bound a collection of points, recursively splitting ellipsoids until volume reductions meet a threshold. It calculates bounding ellipsoids, adjusts their sizes, and optionally expands them using bootstrapping. Monte Carlo integration may estimate the total volume and over... | def update(self, points, pointvol=0., vol_dec=0.5, vol_check=2.,
rstate=None, bootstrap=0, pool=None, mc_integrate=False):
"""
Update the set of ellipsoids to bound the collection of points.
Parameters
----------
points : `~numpy.ndarray` with shape (npoints, ndim... |
def _get_covariance_from_clusters(self, points):
"""Compute covariance from re-centered clusters."""
# Compute pairwise distances.
distances = spatial.distance.pdist(points, metric='mahalanobis',
VI=self.am)
# Identify conglomerates of points ... | This code updates the radii and volume of balls to bound input points, using clustering or full-point covariance estimation. It calculates radii via leave-one-out or bootstrap methods, scales them to ensure minimum volume, and optionally computes Monte Carlo-integrated volumes and overlaps with the unit cube. | def update(self, points, pointvol=0., rstate=None, bootstrap=0,
pool=None, mc_integrate=False, use_clustering=True):
"""
Update the radii of our balls.
Parameters
----------
points : `~numpy.ndarray` with shape (npoints, ndim)
The set of points to boun... |
def _get_covariance_from_clusters(self, points):
"""Compute covariance from re-centered clusters."""
# Compute pairwise distances.
distances = spatial.distance.pdist(points, metric='mahalanobis',
VI=self.am)
# Identify conglomerates of points ... | The code updates the half-side-lengths of cubes to bound given points, using covariance estimation (via clustering or all points), bootstrapping for robustness, and Monte Carlo integration for volume estimation. It adjusts cube sizes to ensure minimum volume per point and scales axes accordingly. Key tasks include deco... | def update(self, points, pointvol=0., rstate=None, bootstrap=0,
pool=None, mc_integrate=False, use_clustering=True):
"""
Update the half-side-lengths of our cubes.
Parameters
----------
points : `~numpy.ndarray` with shape (npoints, ndim)
The set of po... |
def bounding_ellipsoid(points, pointvol=0.):
"""
Calculate the bounding ellipsoid containing a collection of points.
Parameters
----------
points : `~numpy.ndarray` with shape (npoints, ndim)
A set of coordinates.
pointvol : float, optional
The minimum volume occupied by a sing... | The function updates an ellipsoid to bound a set of points, adjusting its parameters (center, covariance, volume, etc.). It optionally expands the ellipsoid using bootstrapping to account for uncertainty, and computes the overlap with the unit cube via Monte Carlo integration if enabled. The core task is to compute and... | def update(self, points, pointvol=0., rstate=None, bootstrap=0,
pool=None, mc_integrate=False):
"""
Update the ellipsoid to bound the collection of points.
Parameters
----------
points : `~numpy.ndarray` with shape (npoints, ndim)
The set of points to ... |
def player(board):
countO=0
countX=0
for y in[0,1,2]:
for x in board[y]:
if x=="O":
countO=countO+1
elif x=="X":
countX=countX+1
if countO>=countX:
return X
elif countX>countO:
return O
def actions(board):
freeboxes=... | The code implements the minimax algorithm to determine the optimal move for a player in a turn-based game. It alternates between maximizing and minimizing players, recursively evaluating all possible moves. For each move, it simulates the action, calculates the resulting score via `minimax_helper`, reverts the board st... | def minimax(board):
isMaxTurn=True if player(board)==X else False
bestMove = None
if isMaxTurn==True:
bestScore = -math.inf
for move in actions(board):
result(board,move)
score = minimax_helper(board)
board[move[0]] [move[1]]= EMPTY
if (sc... |
def construct_sinogram_frame(self, do_cache=False):
if not hasattr(self, "data"):
raise ValueError("You need to load image for processing first, with load_image.")
frame = []
beams = self.get_beams(self.radius, self.width / 2, self.height / 2)
translated_beams = []
... | The code constructs a sinogram by generating multiple frames through iterative scanning, applying a filtering operation if enabled, normalizing the resulting image data, and returning the processed sinogram array. It manages scan progression, caching, and output formatting. | def construct_sinogram(self, enable_filter=True, do_cache=False):
i = 0
frames = []
fil = filtering.get_filter(10)
if not do_cache:
self.start_angle = self.rotation
while i < self.scans_no:
row = self.construct_sinogram_frame(do_cache)
if ena... |
def setAngle(self, angle):
self.rotation = angle % 360
def __construct_image_frame_no_cache(self, frame, scanset):
beams = self.get_beams(self.radius, self.width / 2, self.height / 2)
for (beam_val, beam) in zip(scanset, beams):
(beams_xx, beams_yy) = self.filter_beam(beam, self.wid... | The code reconstructs an image from a sinogram using backprojection, either with or without precomputed cached beams. It optionally generates a GIF of intermediate frames and calculates the Mean Squared Error (MSE) between the reconstructed image and the original input. The function returns the final image, MSE, and GI... | def construct_image(self, do_gif=True, gif_step=10):
if not hasattr(self, "sinogram"):
raise ValueError("You need to process input image first, by calling construct_sinogram.")
frame = np.zeros((self.height, self.width))
gif = []
i = 1
if not self.cached_beams:
... |
def _loadSurveyData(self):
try:
print(f"Loading data from {self.csv_path}...")
with open(self.csv_path, newline='') as csvFile:
reader = csv.reader(csvFile)
next(reader)
self.questions_items = [SurveyItem(*row) for row in reader]
ex... | This code initializes a survey application by loading data from a CSV file, generating question widgets, and setting up UI components for questions, navigation, and a footer using PyQt/PySide. It prepares the interface structure by calling methods to load survey data, generate questions, and format layout elements for ... | def __init__(self, csv_path:str, questions_container:qt.QLayout, navigations_container:qt.QLayout, footer_container:qt.QLayout):
self.csv_path = csv_path
self.questions_container = questions_container
self.navigations_container = navigations_container
self.footer_container = footer_conta... |
def _checkCurrentQuestionUnanswered(self):
self.current_question = self.question_widgets[self.current_num]
if isinstance(self.current_question, SurveyUI.SliderQuestion):
# Check if the slider has been moved
if self.current_question.slid is False:
dialog = CustomDi... | This method switches to a specified question by updating the current question index, ensuring the previous question is unanswered, adjusting navigation buttons, and synchronizing the dropdown selection while maintaining signal states. It also triggers formatting for the new question. | def toQuestion(self, num:int):
self._checkCurrentQuestionUnanswered()
self.current_num = num
self.current_question = self.question_widgets[num]
self._setNavigationButtonStatus()
state = self.questions_dropdown.blockSignals(True)
self.questions_dropdown.setCurrentIndex(n... |
def _initList(self):
global bits
bits = [16, 12, 25, 24, 23, 26, 19, 13]
def _initGPIO(self):
for pin in bits:
GPIO.setup(pin, GPIO.OUT, initial=GPIO.LOW)
GPIO.output(self.E, GPIO.HIGH)
global length
length = 0
def _init_LCD(self):
self.send_instructio... | The code initializes hardware components (GPIO, LCD) and displays the provided message on the LCD's first row, setting up the device for subsequent operations. | def setup(self, first_message):
self._initList()
self._initGPIO()
self._init_LCD()
self.first_row()
self.write_message(f"{first_message}") |
def hex2bin(ch):
n = int(ch, 16)
result = ""
while n > 0:
result = str(n % 2) + result
n = n >> 1
return result
def fillupbyte(ch, padn=8, padchar="0", mode="l"):
n = len(ch)
l = n
while l % padn != 0:
l += 1
result = ""
j = 0
for i in range(l):
if... | The function `hex_xor` performs a bitwise XOR operation on two hexadecimal strings. It converts each hex string to binary, pads the shorter with leading zeros to match lengths, XORs corresponding bits, converts the result back to hex, and pads leading zeros to maintain the original maximum input length. The output is a... | def hex_xor(ch1, ch2):
"""
>>> hex_xor('0aabbf11','12345678')
'189fe969'
>>> hex_xor('12cc','12cc')
'0000'
>>> hex_xor('1234','2345')
'3171'
>>> hex_xor('111','248')
'359'
>>> hex_xor('8888888','1234567')
'9abcdef'
"""
maxlen = -1
if len(ch1) > len(ch2):
m... |
def get_step_flag():
step = [2,2]
while (len(step) != 1):
step = input('Enter 0 to display only the final results - 1 for single-stepping option: ').split()
step = [int(x) for x in step]
if (step[0]):
print()
print('>> get_step_flag function takes input to decide Single-stepping option')
p... | The main task of the code is to execute and demonstrate topological sorting (top_sort) on three distinct input datasets (A, B, C), with the process controlled by a 'step' flag that determines whether execution occurs step-by-step. The code retrieves input configurations based on the step flag, then prints sorted result... | def main():
# get single stepping input
step = get_step_flag()
# get the homework inputs
input_A, input_B, input_C = create_inputs(step)
print('\nTHE FIRST EXAMPLE')
top_sort(step, input_A)
print('\nTHE SECOND EXAMPLE')
top_sort(step, input_B)
print('\nTHE THIRD EXAMPLE')
top... |
def get_step_flag():
step = [2,2]
while (len(step) != 1):
step = input('Enter 0 to display only the final results - 1 for single-stepping option: ').split()
step = [int(x) for x in step]
if (step[0]):
print()
print('>> get_step_flag function takes input to decide Single-stepping option')
p... | The main task of the code is to build a KDTree from given 2D points with associated colors, then query the tree to determine the color of a specific box at user-provided (width, height) coordinates. It optionally displays the tree structure step-by-step and returns the matching box's color and position. | def main():
# get single stepping input
step = get_step_flag()
# Entering points in the figure 19.2 of winston book
points = [(1, 2, "Red"), (2, 1, "Violet"), (2, 5, "Orange"),
(2, 6, "Red"), (4, 2, "Blue"), (5, 6, "Yellow"),
(6, 5, "Purple"), (6, 1, "Green")]
# Establi... |
def create_collection():
return Collection.objects.create()
def get_all_people():
return get_all_from_swapi("people")
def get_all_planets():
return get_all_from_swapi("planets")
def write_csv(filename, people, planets):
planets_map = {p['url']: p for p in planets}
data = petl.fromdicts(people)
n... | The main task of the code is to generate a new collection by gathering data on people and planets, writing this data to a CSV file, updating the collection's item count based on the CSV rows, and saving the collection. It returns the updated collection object. | def fetch_new_collection():
collection = create_collection()
people = get_all_people()
planets = get_all_planets()
data = write_csv(filename=collection.full_filename, people=people, planets=planets)
collection.items_count = data.nrows()
collection.save()
return collection |
def augmented_laplacian(self, q_agents):
L = self.laplacian(q_agents)
self.save_laplacians.append(L)
return torch.kron(L, torch.eye(2))
def grad_V(self, L, q_agents):
grad_V = torch.zeros(2 * self.na)
for i in range(self.na):
r_sigma = self.sigma_norm(self.r, self.e)... | The main task of the code is to compute the dynamics of a flocking system by calculating the velocity changes (dp) based on the gradient of a potential function (ΔV), the augmented Laplacian matrix (L), and a control input. It splits inputs into position/velocity states, computes interactions via L and ΔV, and applies ... | def flocking_dynamics(self, t, inputs):
L = self.augmented_laplacian(inputs[:2 * self.na])
DeltaV = self.grad_V(L, inputs[:2 * self.na])
dq = inputs[2 * self.na:4 * self.na]
dp = -DeltaV - L @ inputs[2 * self.na:4 * self.na] + self.f_control(inputs[:2 * self.na], inputs[2 * self.na:4 * ... |
def get_initial_node_queue(initial_state):
"""Queue that only contains root node with initial state"""
return [node_set_state(new_node(), initial_state)]
def node_get_state(node):
return node[2][1]
def node_get_path(node):
return node[2][0]
def node_get_parent(node):
return node[0]
def print_action_... | This code performs a search algorithm using the specified strategy to find a path from an initial state to a goal state in a problem. It iteratively explores nodes, expands them to generate child nodes, and checks if the goal is reached. If a solution is found, it returns the action path; otherwise, it returns False af... | def search(problem, strategy, max_nodes=20000):
initial_state = problem[0]
poss_act_func = problem[1]
successor_func = problem[2]
goal_test_func = problem[3]
node_queue = get_initial_node_queue(initial_state)
initial_node = node_queue[0]
if len(node_queue) == 0:
return False
f... |
def validate_model_path(model_name, model_save_path):
"""Checks if the model already exists and is so, asks the user if they want to overwrite."""
name_validated = False
while not name_validated:
model_path = os.path.join(model_save_path, model_name)
model_exists = os.path.exists(model_path)... | The main task of the code is to either train a new model or evaluate an existing one based on the --mode argument. In train mode, it checks for existing model names, trains using parameters from train_config.json, and saves the model and training history. In eval mode, it loads a pre-trained model and evaluates it on a... | def main():
"""Either train a new model or evaluates an existing model depending on the --mode argument.
If in train mode:
First verifies that the provided model name han not already been used.
If a model with the name exists, the user is asked if the want to overwrite or provide a new name.
... |
def getSkeletonParse(self, parse):
parse_tree = Tree.fromstring(parse)
parsed_sentence = getPOSs(parse_tree)
# get the sentence's syntax
parsed_pos = []
for parse in parsed_sentence:
if type(parse) is str:
parsed_pos += [parse]
else:
... | This code identifies a verb class from a syntactic parse by matching parsed sentence structures with VerbNet frames. It simplifies syntax (replacing PPs with NPs, reducing complexity) and checks POS tag alignment and prepositional matches. If a frame matches the parsed sentence's structure without preposition mismatche... | def findVerbFromSyntax(self, classIDs, parse):
# get the dependency parse, the parsed sentence (NPs, PPs, etc.), and the list of the parts of speech
parsed_sentence, parsed_pos = self.getSkeletonParse(parse)
bareIDs = list(set(["-".join([cla.split("-")[0], cla.split("-")[1]]) for cla in classID... |
def callStanfordNER(self, sentence):
encoding = "utf8"
default_options = ' '.join(_java_options)
with tempfile.NamedTemporaryFile(mode='wb', delete=False) as input_file:
# Write the actual sentences to the temporary input file
if encoding:
input_ = sentenc... | The main task of the code is to extract events from a sentence by analyzing syntactic dependencies, identifying subjects, verbs, objects, and modifiers, generalizing terms, and structuring event data. It uses Stanford NER and dependency parsing to build events, handling prepositions and named entities, then stores and ... | def getEvent(self):
# given a parse of a sentence, extract the event(s)
sentence = self.sentence
words = sentence.split()
original_sent = sentence.strip()
ner = self.callStanfordNER(original_sent).split()
ner_dict = {} # json sentence index should match up with sentence ... |
def __needs_auth(self) -> bool:
if EpRequestHandler.KEY is None or EpRequestHandler.KEY == b'':
return False
auth = self.headers.get('Authorization')
expected = 'Basic '.encode('utf-8') + EpRequestHandler.KEY
if auth is None or auth.encode('utf-8') != expected:
... | This method processes HTTP requests by routing them to appropriate handlers. It checks for authentication, resets POST data, parses the URL path, and directs GET/POST requests under '/api' to specific API handlers or defaults to web handling. It then sends the generated response. | def _handle_request(self, method: str):
if self.__needs_auth():
return
# reset post body content
self.post_body = None
path_tokens: ParseResult = urlparse(self.path)
response: bytes = b''
if self.config is not None and path_tokens.path.startswith('/api'):
... |
def adv_RK3(adv_func, u0, x, c, CFL, T):
dx = np.mean(x[1:]-x[:-1])
dt = CFL*dx/c
u = np.array(u0)
t = 0
iteration = 0
while(t < T):
if dt > T-t:
dt = T-t
dfdx = adv_dfdx(adv_func, u, c, dx)
u1 = u + dfdx*dt
dfdx = adv_dfdx(adv_func, u1, c, dx)
... | The code simulates the advection equation using a specified numerical method (`adv_func`) and compares the result to an exact solution (`wave_func`). It initializes spatial grids, runs the simulation with a Runge-Kutta 3rd-order method, computes the root-mean-square error (RMSE) and total variation (TV) of the numerica... | def test_adv(adv_func, wave_func):
# physics
L = 1 # periodic boundary f(x+L) = f(x)
c = 1
# simulation parameter
nI = 100
CFL = 0.5
T = 10
# initialization
x = np.linspace(0, L, nI+1)[:-1]
u0 = wave_func(x, 0, c, L)
# simulation
u_sim = adv_RK3(adv_func, u0, x, c, CFL... |
def adv_RK3(adv_func, u0, x, c, CFL, T):
dx = np.mean(x[1:]-x[:-1])
dt = CFL*dx/c
u = np.array(u0)
t = 0
iteration = 0
while(t < T):
if dt > T-t:
dt = T-t
dfdx = adv_dfdx(adv_func, u, c, dx)
u1 = u + dfdx*dt
dfdx = adv_dfdx(adv_func, u1, c, dx)
... | The code simulates a periodic wave equation using the WENO5-JS scheme with RK3 time integration over time T. It initializes a wave profile, evolves it numerically, computes the RMSE error against the exact solution, and evaluates the total variation (TV) of the result. The function returns the spatial grid and simulate... | def cal_WENO5_JS(T, wave_func):
# physics
L = 1 # periodic boundary f(x+L) = f(x)
c = 1
# simulation parameter
nI = 100
CFL = 0.5
# initialization
x = np.linspace(0, L, nI+1)[:-1]
u0 = wave_func(x, 0, c, L)
# simulation
u_sim = adv_RK3(WENO5_getf, u0, x, c, CFL, T)
# ... |
def adv_RK3_NN(model_info, u0, x, c, CFL, T, u_max=1e10):
dx = np.mean(x[1:]-x[:-1])
dt = CFL*dx/c
u = np.array(u0)
t = 0
iteration = 0
while(t < T):
if dt > T-t:
dt = T-t
dfdx = adv_dfdx_NN(model_info, u, c, dx)
u1 = u + dfdx*dt
dfdx = adv_dfdx_NN... | The code evaluates a neural network model's performance in solving an advection equation by comparing its numerical solution (obtained via adv_RK3_NN) to an exact wave function solution. It computes the root mean square error (RMSE) and total variation (TV) to quantify accuracy and smoothness of the neural network's ou... | def test_adv_NN(model_info, wave_func):
# physics
L = 1 # periodic boundary f(x+L) = f(x)
c = 1
# simulation parameter
nI = 100
CFL = 0.5
T = 10
# initialization
x = np.linspace(0, L, nI+1)[:-1]
u0 = wave_func(x, 0, c, L)
# simulation
u_NN = adv_RK3_NN(model_info, u0, ... |
def adv_RK3_NN(model_info, u0, x, c, CFL, T, u_max=1e10):
dx = np.mean(x[1:]-x[:-1])
dt = CFL*dx/c
u = np.array(u0)
t = 0
iteration = 0
while(t < T):
if dt > T-t:
dt = T-t
dfdx = adv_dfdx_NN(model_info, u, c, dx)
u1 = u + dfdx*dt
dfdx = adv_dfdx_NN... | The function `view_adv_NN` compares a neural network (NN) model and the WENO5-JS scheme for solving an advection equation. It initializes parameters, simulates solutions using both methods, computes the RMSE error and total variation (TV) of the NN solution, and visualizes results alongside the exact solution. The task... | def view_adv_NN(model_info, wave_func, T):
# physics
L = 1 # periodic boundary f(x+L) = f(x)
c = 1
# simulation parameter
nI = 100
CFL = 0.5
# initialization
x = np.linspace(0, L, nI+1)[:-1]
u0 = wave_func(x, 0, c, L)
# simulation
u_NN = adv_RK3_NN(model_info, u0, x, c, CF... |
def adv_RK3_NN(model_info, u0, x, c, CFL, T, u_max=1e10):
dx = np.mean(x[1:]-x[:-1])
dt = CFL*dx/c
u = np.array(u0)
t = 0
iteration = 0
while(t < T):
if dt > T-t:
dt = T-t
dfdx = adv_dfdx_NN(model_info, u, c, dx)
u1 = u + dfdx*dt
dfdx = adv_dfdx_NN... | The function `cal_WENO_NN` simulates a wave equation using a neural network (NN) model, compares the result with an exact solution, and evaluates accuracy and smoothness. It initializes a spatial grid and initial condition via a wave function, evolves the solution using a Runge-Kutta 3rd-order method with the NN model,... | def cal_WENO_NN(model_path, T, wave_func):
model_info = read_model(model_path)
# physics
L = 1 # periodic boundary f(x+L) = f(x)
c = 1
# simulation parameter
nI = 100
CFL = 0.5
# initialization
x = np.linspace(0, L, nI+1)[:-1]
u0 = wave_func(x, 0, c, L)
# simulation
... |
def init_data_U(r, r_min):
func = gen_data.f_sin
n_data = 100 # data per shift
x = np.linspace(0, 1, n_data+2*r)
exp_max = 3
exp_min = -1
exp_k = (exp_max-exp_min)*np.random.random_sample() + exp_min
k = np.exp(exp_k)
omega = 2*np.pi*k
delta = np.random.random_sample()/k
args = ... | The code generates synthetic data using various mathematical functions (sine, sawtooth, step, tanh, etc.) with WENO5 parameters, combines them into a dataset, and saves the aggregated data array to a file. It initializes parameters, processes each data type, compiles results, and outputs the final dataset with a comple... | def data_SC(path):
r = 3 # WENO5 based
r_min = 3e-3 # data minimum distance
dataU = init_data_U(r, r_min)
data_SC_sin(dataU, r) # ~11,000 sin (11,000)
data_SC_sw(dataU, r) # ~8,000 sawtooth (19,000)
data_SC_step(dataU, r) # ~1,000 step (20,000)
data_SC_tanh(dat... |
def request_host(self):
return self.headers.get('Host')
def send_mocks_information(self):
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.end_headers()
self.wfile.write(json.dumps(self.request_paths).encode('utf-8'))
def send_stubbed_response(self):
self.... | The code handles HTTP GET requests by sending a 200 OK response. It checks if the request host matches a predefined mock DNS host; if true, it sends mock DNS information, otherwise, it sends a stubbed response. The primary task is to conditionally route requests to mock or stubbed DNS data based on the host domain. | def do_GET(self):
self.send_response(200)
if self.request_host() == dns_mocks_host:
self.send_mocks_information()
else:
self.send_stubbed_response() |
def _update_state(self, state, u1, u2):
x, y, theta, v = state
dx = v * np.cos(theta)
dy = v * np.sin(theta)
dtheta = v * u1
dv = u2 - self.friction * v
new_v = max(min(v + dv * self.dt, self.vmax), -self.vmax)
return [x + dx * self.dt, y + dy * self.dt, theta + d... | This code processes an action by updating the environment state, advancing car behaviors, tracking time, checking termination conditions, calculating reward, and returning the new state, reward, done flag, and metadata for reinforcement learning training. | def step(self, action):
action = np.array(action)
u1, u2 = action
self.state = self._update_state(self.state, u1, u2)
for car in self.cars:
car.update(self._update_state)
self.time += 1
done = bool(self.time >= self.episode_length)
reward = self._get... |
def reset(self):
self.state = self.initial_state
self.time = 0
for car in self.cars:
car.reset()
self.history = []
self._update_history()
return np.array(self.state + [self.time])
def get_reward_features(self, state=None):
return self._get_features(sta... | The function simulates an environment using a given flat policy, repeating actions as needed to match the episode length. It accumulates reward and constraint features over the episode by iterating through steps, extracting features after each action, and returning aggregated reward and constraint feature vectors. | def _get_features_from_flat_policy(self, policy):
a_dim = self.action_d
n_policy_steps = len(policy) // a_dim
n_repeat = self.episode_length // n_policy_steps
self.reset()
r_features = np.zeros_like(self.get_reward_features())
c_features = np.zeros_like(self.get_constrai... |
def reset(self):
self.state = self.initial_state
self.time = 0
for car in self.cars:
car.reset()
self.history = []
self._update_history()
return np.array(self.state + [self.time])
def get_reward_features(self, state=None):
return self._get_features(sta... | The code generates reward and constraint features by repeatedly applying a given policy over an episode. It initializes feature arrays, executes the policy, and accumulates reward and constraint features across all steps. The policy is repeated to match the episode length, and the final summed features are returned. | def get_features_from_policy(self, policy):
a_dim = self.action_d
n_policy_steps = len(policy)
n_repeat = self.episode_length // n_policy_steps
self.reset()
r_features = np.zeros_like(self.get_reward_features())
c_features = np.zeros_like(self.get_constraint_features())
... |
def move(self, direction):
moved = False
if direction == "up":
for j in range(4):
new_col = [0] * 4
new_col_idx = 0
for i in range(4):
if self.board[i][j] != 0:
if new_col[new_col_idx] == 0:
... | The code handles keyboard arrow key events to control game direction. It converts the key to lowercase, triggers movement in that direction, checks if the game is over, and either displays a game-over message or adds a new tile if the game continues. | def handle_key_event(self, event):
if event.keysym in ("Up", "Down", "Left", "Right"):
direction = event.keysym.lower()
self.move(direction)
if self.is_game_over():
self.display_game_over()
else:
self.add_new_tile() |
def _read_data():
with open(config.SCHEDULE_FILE, 'rb') as schedule:
data = pickle.load(schedule)
return (data['events'], data['timestamp'])
def _diff_now(event_datetime):
"""Seconds between now and input (positive means input in past)."""
return int((datetime.datetime.now(config.TIMEZONE_UTC) -... | The code executes scheduled tasks whose designated runtime has passed, marks them as completed, and checks if a reset interval has elapsed to trigger a rescheduling process. | def execute():
"""Run task(s) if in time window after event runtime."""
# get events from schedule, filter out already ran
(events, timestamp) = _read_data()
events = [x for x in events if not x['ran']]
# examine event datetimes
for event in events:
# execute task if schedule time was ... |
def get_bias(path,save_path=None):
"""Creates a master bias frame.
Collects bias frames from a specified path. Check exposure time of each file
to ensure that it is a bias frame then factors for overscan. Outliers past five
standard deviations of the mean are removed before all bias frames are aver... | The function generates a master flat image by processing flat frames from a specified path. It corrects for bias and dark current, removes outliers via sigma clipping, normalizes each frame, and averages them. If provided, it uses or creates master bias/dark frames. The result is a normalized, averaged master flat save... | def get_flat(path,master_bias,master_dark,save_path=None):
"""Creates a master flat image.
Takes master bias and master dark frames, or creates them using the paths given. Collects
flat frames from a specified path. Corrects frames for bias, then converts pixel values
to units of counts/secon... |
def get_bias(path,save_path=None):
"""Creates a master bias frame.
Collects bias frames from a specified path. Check exposure time of each file
to ensure that it is a bias frame then factors for overscan. Outliers past five
standard deviations of the mean are removed before all bias frames are aver... | The main task of the code is to collect science frames from a specified directory, calibrate them using master bias, dark, and flat frames (either provided or generated from paths), correct for CCD artifacts, and return the calibrated frames as a list of numpy arrays. If a save path is specified, the calibrated frames ... | def get_science(path,master_bias,master_dark,master_flat,save_path=None):
"""Collects and calibrates science frames.
Takes master bias, master dark, and master flate frames, or creates them using the paths
given. Collects science frames from a specified path then corrects frames using master
bi... |
def initial_checks(self):
self.serial_number = self.lineEdit_cardserialno.text()
self.associate_name = self.lineEdit_associatename.text()
if self.associate_name != "":
if self.serial_number != "":
if "-" in self.serial_number and len(self.serial_number) < 30:
... | The main task of the code is to execute a series of tests on a device under test (DUT), handle user prompts for test failures, and update the UI to reflect test outcomes (PASS/FAIL) with corresponding status messages, timestamps, and visual indicators. It disables the start button during testing, logs test details, and... | def start_function(self):
self.pushButton_start.setDisabled(True)
testing_flag = True
global final_output
self.is_topcard = True
if not self.initial_checks():
self.reset()
self.final_status.setText("TESTING...")
font = QtGui.QFont()
... |
def for_loop():
print("=" * 25)
print("For loop")
print("-" * 25)
for n in range(len(InfoDb)):
print_data(n)
def while_loop(n):
print("=" * 25)
print("While loop")
print("-" * 25)
while n < len(InfoDb):
print_data(n)
n += 1
return
def recursive_loop_run():
... | The main task of the code is to execute and test different loop mechanisms (for, while, recursion) and a list search function, starting with initial index values, to demonstrate iterative and recursive traversal of data structures like lists. | def tester():
for_loop()
while_loop(0) # requires initial index to start while
recursive_loop_run(0) # requires initial index to start recursion
list_finder() |
def h_balance(self, grid):
if(sum(1 for row in grid for value in row if (value != -1 and value != 0)) == 1):
return 0
num_left_col = int(len(grid)/2)
left_sum = sum(grid[i][j] for i in range(num_left_col) for j in range(len(grid[0]))if grid[i][j] != -1)
right_sum = sum(grid[i... | This code implements a search algorithm to find a balanced grid configuration. It uses an open list (priority queue sorted by f-value) and a closed list to track explored nodes. Starting from 'start', it iteratively explores nodes, checking if a node's balance score meets a threshold (≥0.9). If so, it returns the confi... | def process(self, start):
self.open.append(start)
while self.open:
cur = self.open.pop(0)
self.closed.append(cur)
h_cur = self.h_balance(cur.grid)
if self.balance_score(cur.grid) >= 0.9:
print("Found a Balanced Configuration with a balance ... |
def login():
username = input("Enter your name for login: ")
timestamp = datetime.now().strftime("%b %d %Y %H:%M")
log_entry = f"{timestamp} : \"{username}\" logged in\n"
with open(LOG_FILE, 'a') as file:
file.write(log_entry)
print(f"Welcome {username}!")
def upload_manifest():
print("P... | The main task of the code is to present a menu-driven interface for Wavefront Solutions, allowing users to choose between logging in, uploading a manifest, accessing a menu, or exiting. It continuously loops until the user selects "Exit," handling invalid inputs by prompting retries. | def main():
while True:
print("\nWavefront Solutions\n")
print("1. Login")
print("2. Upload Manifest")
print("3. Menu")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
login()
elif choice == '... |
def login():
username = input("Enter your name for login: ")
timestamp = datetime.now().strftime("%b %d %Y %H:%M")
log_entry = f"{timestamp} : \"{username}\" logged in\n"
with open(LOG_FILE, 'a') as file:
file.write(log_entry)
print(f"Welcome {username}!")
def upload_manifest():
print("P... | The main task of the code is to present a menu-driven interface allowing users to log in, upload a manifest file, access a menu, or exit the program. It continuously prompts the user for input, executes corresponding functions based on their choice, and maintains a loop until the exit option is selected, ensuring inter... | def main():
manifest_path = None
while True:
print("\nWavefront Solutions\n")
print("1. Login")
print("2. Upload Manifest")
print("3. Menu")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
login()... |
def load_data(self):
self.loader = Loader(args)
# self.loader.build_dataset(file="train_expanded_data.json")
# self.loader.build_dataset(file="train_augmented_data.json")
self.loader.build_dataset(file="train_data.json")
# self.loader.build_dataset(file="train_debug_data.json")
... | The code's main task is to load data and execute either training or evaluation based on command-line arguments. If the 'train' flag is set, it initiates the training process; if the 'evaluate' flag is set, it runs the evaluation. This structure allows the program to flexibly switch between training and testing modes de... | def run(self):
self.load_data()
if self.args.train:
self.run_train()
elif self.args.evaluate:
self.run_test() |
def reply_msg(msg, current_ts, node1, node2):
if msg["msg_type"] == MESSAGE_FRIENDSHIP_INIT:
mm = []
if node1["owner"] == node2["owner"]:
mm.append( "owner" )
if node1["batch"] == node2["batch"]:
mm.append( "batch" )
if distance(node1,node2) < node1["locality"]:
mm... | The code simulates one step in a network of agents by processing inter-node messages, updating friendships, and facilitating service consumption. It retrieves all nodes, checks for prior messages to trigger replies, adjusts friendship levels, and searches for unmet service needs. Nodes prioritize fulfilling services th... | def simulate_one_step(current_ts):
db = get_conn()
nodes = list( db.agents.find())
nodes_dic = {node1["name"]:node1 for node1 in nodes}
# reply message
for node1 in nodes:
for node2 in nodes:
if node1 == node2:
continue
# if there is a message j->i at t-1 then respond
... |
def buildService(Creds):
"""
returns gmail `Service`
"""
return build('gmail', 'v1', credentials=Creds)
def getMessagesInThread(Creds, Service, threadId):
try:
threadData = getThreadData(Creds=Creds, Service=Service, threadId=threadId)
messages = threadData.get('messages', [])
... | The main task of the code is to read an unread email thread, extract its content (plain text or multipart), check if it matches a specified query, and trigger a custom task if it doesn't. If the content matches, it downloads attachments and returns True; otherwise, it returns False or an error. It uses Gmail API creden... | def readMail(Creds, Service, threadId, query = '', task_if_not_match_query = None, work_w_plain_text_mail = True, resultPath = None):
"""
query: [str], format "query_true|query_false"
task_if_not_match_query: a function to do if mail content does not match
"""
try:
if not Service:
... |
def load_data_from_file(file_path):
global mtg_data
try:
mtg_data = pd.read_csv(file_path)
# Repeat the same cleaning and processing as for the general file
# Clean percentage columns
for col in percentage_columns:
mtg_data[col] = (
mtg_data[col]
... | The main task of the code is to handle selection of a color combination, load corresponding CSV data, update the UI title with the combination's win rate, and refresh the table display with Magic: The Gathering data. It retrieves the selected code/name, constructs a file path, loads data if found, and updates interface... | def on_color_combo_selected(event):
selected_combo_code = color_combo_var.get()
selected_combo_name = color_code_to_name.get(selected_combo_code, None)
if selected_combo_name:
combo_file_path = os.path.join(
data_dir, f"card-ratings-2023-11-20({selected_combo_code}).csv"
)
... |
def update_title(selected_color_code=None):
selected_color_name = color_code_to_name.get(selected_color_code, None)
if selected_color_name and selected_color_name in color_win_rates:
win_rate = color_win_rates[selected_color_name]
title_text = f"{selected_color_name} - Avg. Win Rate: {win_rate}"... | The main task of the code is to handle color selection in a GUI application. It updates a combobox's options, enables/disables it based on the selected color, loads data from a CSV file, and refreshes the table display. It also updates the UI title with the selected color's win rate, ensuring dynamic filtering of data ... | def on_color_selected(event):
selected_color = color_selection_var.get()
if selected_color != "All Colors":
combo_values = color_combinations.get(selected_color, [])
color_combo_combobox["values"] = combo_values
color_combo_combobox.set("") # Clear the default selection
color_co... |
def read_file(filename):
file = check_file()
list = []
for line in file.readlines():
if line.strip() == "":
continue
if line[0] != "v" and line[0] != " ":
print_msg(f'Invalid line: "{line}". First character should be " " or "v"')
list.append(ToDoI... | The code toggles the checkbox status of an item in a list stored in a file. It reads the file, validates the index, switches the checkbox value between "v" and " ", then writes the updated list back to the file. Error messages are displayed for invalid indices. | def check_item(index: int):
list = read_file(FILE_NAME)
if index < 0:
print_msg(f"The index is too small. You may use indexes from 0 to {len(list) - 1}")
return
if index >= len(list):
print_msg(f"The index is too big. Max index is {len(list) - 1}")
return
el = l... |
def check_args(args, cmd):
if len(args) < 3:
print_msg("You have to enter the second argument")
return False
map = {'--add': False, '--del': True, '--check': True}
if not cmd in map:
print_msg("Invalid command")
return False
if map[cmd] and not args[2]... | The code parses command-line arguments to perform actions on items: adding, deleting, or checking based on the '--add', '--del', or '--check' flags. It validates arguments using `check_args`, then executes the corresponding operation with parameters from `args[2]`, converting the second argument to an integer for delet... | def parse_args(args):
if not check_args(args, args[1]):
return
if args[1] == '--add':
add_item(args[2])
elif args[1] == '--del':
del_item(int(args[2]))
elif args[1] == '--check':
check_item(int(args[2])) |
def show_list(list):
if len(list) < 1:
return
y = 0
scr.clear()
for el in list:
scr.addstr(y, 0, el.__str__())
y += 1
scr.refresh()
def read_file(filename):
file = check_file()
list = []
for line in file.readlines():
if line.strip() == "... | The code defines a `main` function handling screen operations via `curses`. It checks command-line arguments: if none are provided, it reads a file, displays its content, and waits for a key press. If arguments exist, it parses them and waits for another key press. The global `scr` variable stores the screen object for... | def main(stdscr):
global scr
scr = stdscr
if len(sys.argv) < 2:
show_list(read_file(FILE_NAME))
scr.getkey()
return
parse_args(sys.argv)
scr.getkey() |
def db_check():
global new_host #ENCODES THE HOST NAME AFTER STRING SORT
new_host = ROT_encode(BASE_encode(host()))
global mb_id #IMP MOTHERBOARD ID
if os.name == 'nt':
if 'db.db' not in os.listdir(os.path.expanduser("~") + "\\"):
#f = open(os.path.expanduser("~") + '... | The code generates a secure password backup by combining random strings, encoded passwords, and keys into a file stored in OS-specific locations (Windows: ~\creds.txt, Linux/macOS: ~/Documents/creds.txt). It outputs a backup key message for user storage and confirms registration completion. | def register_cont(confirm_password):
db_check()
if os.name == 'nt':
first = last = ''
for i in range(500):
first += random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-+|')
last += random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM... |
def get_cache_key(self) -> str:
return self._get_cache_key(self.cache_key)
def _get_cache_key_with_suffix(self, suffix: str):
cache_key = f"{self.get_cache_key()}_{suffix}"
return cache_key
def get_all_queryset(
self,
queryset: Optional[QuerySet[ModelType]],
key: str,
... | This method retrieves or caches a queryset based on a cache key, optionally modified by a suffix or filters. It warns if filtering is applied without a suffix to avoid cache conflicts. The queryset is fetched from the cache if available, otherwise generated and stored. | def all(
self,
suffix: Optional[str] = None,
filter_kwargs: Optional[Dict[str, Any]] = None,
) -> QuerySet[ModelType]:
"""all
Gets querysets from cache if queryset was in the cache otherwise sets queryset to the cache.
Parameters:
suffix: Optional[str]
... |
def setup_menubar(self) -> None:
"""inits menubar
Returns:
None"""
self.menu_Bar = self.menuBar()
menu_file = self.menu_Bar.addMenu("file")
self.action_open = QAction("open")
self.action_save = QAction("save")
self.action_new = QAction("new")
... | Your return This code initializes a `MainWindow` class, configuring GUI parameters, loading a `.ui` file, setting up file/directory paths, and initializing click events for menu bars, combo boxes, and buttons. It creates a `QStackedWidget` as the central widget, sets window properties, and prepares multiple UI pages (v... | def __init__(self) -> None:
"""inits MainWindow class
configuring parameters of MainWindow class and inherits from QtWidget.QMainWindow
loads .ui file sets up file and directory path vars, inits click events(menuebar, coboboxes, btns) and
shows gui the first time
Returns:
... |
def _calculate_teleport_heuristic(self, board):
start_time = time.time()
front_heuristic = 0
back_heuristic = 0
for x in range(len(board)):
for y in range(len(board[x])):
current = board[x][y]
if current == 0:
continue
... | This function calculates a heuristic value for a given board state based on the specified heuristic type (teleport, slide, or learned). It calls the corresponding private method to compute front and back heuristics, then returns the minimum of the two along with the calculation time. If no specific type is provided, it... | def _calculate_heuristic(self, board):
if self.heuristic_type == HEURISTIC_TELEPORT:
front_heuristic, back_heuristic, calc_time = self._calculate_teleport_heuristic(board)
return min(front_heuristic, back_heuristic), calc_time
elif self.heuristic_type == HEURISTIC_SLIDE:
... |
def is_maximising(self) -> bool:
return bool(self.depth % 2)
def prune(self) -> None:
if len(self.moves) < 2:
return
self.vocabulary = prune(
words=self.vocabulary,
guesses=self.moves[-2:-1],
scores=self.moves[-1:],
final_only=True,
... | This function generates child nodes for a Wordle game tree. If in maximizing mode, it prunes and creates nodes with guesses from the vocabulary. If in evaluation mode, it computes outcomes of guesses, logs results, and generates nodes with evaluations instead of guesses, advancing the game state for tree exploration. | def children(self) -> Iterator[Self]:
if self.is_maximising():
self.prune()
for guess in self.vocabulary:
yield WordleNode(
moves=self.moves + [guess],
vocabulary=[w for w in self.vocabulary],
depth=self.depth + ... |
def _reset(self):
self.state = self.env.reset()
self.last_obtained_return = 0
def _play_step(self):
action = self._select_action()
next_state, reward, done, _ = self.env.step(action)
self.last_obtained_return+=reward
exp = Experience(self.state, action, reward, done, next... | The code trains a reinforcement learning agent using a DQN-like approach. It initializes an optimizer, runs episodes in the environment, and uses experience replay to sample batches for policy updates. Gradient clipping and target network synchronization are applied periodically. Metrics like speed, memory usage, and r... | def train_agent(self):
"""
Train the Agent
"""
writer = SummaryWriter(comment="_"+self.env_name+"_"+self.config['name'])
optimizer = optim.Adam(self.policy_net.parameters(),
lr=self.config['hp_learning_rate'])
print("Start Training on %s... |
def _load_token(self) -> Token:
config_path = os.path.expanduser(TOKEN_PATH)
config = configparser.ConfigParser()
token = Token()
if os.path.exists(config_path):
config.read(config_path)
if config.has_section(self._hostname):
token.id = config.get(self._hostname, 'id')
token.... | This code initializes a connection to a robotic system by setting up authentication credentials, disabling SSL verification, logging in, detecting the robot's platform type (Panda or FR3), and handling legacy system compatibility. It establishes a session, manages error handling for connection issues, and prepares the ... | def __init__(self,
hostname: str,
username: str,
password: str,
platform: str = 'panda') -> None:
urllib3.disable_warnings()
self._session = requests.Session()
self._session.verify = False
self._hostname = hostname
self._username = username... |
def delete_table(dbname):
# db = pymysql.connect(host='eu-cdbr-azure-west-d.cloudapp.net',
if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
con = pymysql.connect(
host='192.168.127.12',
unix_socket='testflask-1315:fairydb',
... | The main task of the code is to reset a database by dropping the "FAIRY_TBL" table, recreating it, and populating it with x randomly generated fairies (alternating between male and female genders using a 50/50 random choice). | def resetDB(x):
# drops Fairy table and creates a new table with x number of random fairies
delete_table("FAIRY_TBL")
create_fairy_table("FAIRY_TBL")
for c in range(0, x):
if (random.randint(0, 1) == 0):
createfairy('m')
else:
createfairy('f')
return |
def createfairy(sex):
if sex == "f":
bodyx = random.randint(0, 2) # pick a random row
bodyy = random.randint(0, 2) # pick a random column
wingx = random.randint(0, 9)
wingy = random.randint(0, 2)
eyesx = random.randint(0, 4)
eyesy = random.randint(0, 8)
mou... | The main task of the code is to process command-line arguments for managing fairy data in a database. It handles operations like creating a fairy (-f), listing entries (-l), retrieving specific fairies (-s), resetting the database (-r), and displaying random fairy images (-x). The script uses getopt to parse flags, int... | def main(argv):
# for argv in sys.argv: 1
# print (argv)
command = ''
argument = ''
try:
opts, args = getopt.getopt(argv, "hf:g:c:d:ls:r:x")
except getopt.GetoptError:
print ('test.py -f <m/f> -g <DBref> -c <DB_Table_Name> -d <DB_TableName> -l -s <DBref> -r -x')
... |
def jsonify(js):
'''
make sure $metaver_json is a json (dict), must not pass in json as a string
'''
if isinstance(js, str) and js:
js = json.loads(js)
return js
def is_valid_metavarset(metavar_json, verbose = False):
'''
validates that $metavar_json is the correct format for metavar json
'''
invalidities = ... | This function validates a JSON object as a metavarset, uploads it to DynamoDB if valid, and returns a confirmation response. It first converts the input to JSON, checks validity, inserts into DynamoDB, and confirms the operation with the dataset ID. | def insert_metavarset_dynamodb(metavar_json):
'''
takes in a json, $metavar_json, and uploads it to the dynamodb
'''
metavar_json = jsonify(metavar_json)
if is_valid_metavarset(metavar_json):
response = table.put_item(Item = metavar_json)
else:
raise kobaza_error.MetavarsetIsInvalid(metavar_json)
return co... |
def jsonify(js):
'''
make sure $metaver_json is a json (dict), must not pass in json as a string
'''
if isinstance(js, str) and js:
js = json.loads(js)
return js
def is_valid_metavarset(metavar_json, verbose = False):
'''
validates that $metavar_json is the correct format for metavar json
'''
invalidities = ... | This function inserts a metavar JSON dataset into an Elasticsearch endpoint. It converts the input JSON, validates its structure, and sends it via a PUT request to a specified ES index. If invalid, it raises an error. Finally, it confirms the insertion's success based on the Elasticsearch response. | def insert_metavarset_elasticsearch(endpoint:str, username:str, password:str, metavar_json):
'''
insert $metavar_json into es $endpoint
'''
metavar_json = jsonify(metavar_json)
if is_valid_metavarset(metavar_json):
response = elasticsearch_curl(f"{endpoint}metavars/_doc/{metavar_json['ds_id']}?pretty", username... |
def scp_data_storage_file_exists(file_name:str, storage_path:str, server_host:str = '') -> bool:
'''check for file existance at path. leave server blank to check local'''
ls = custom_cmd(['ls', storage_path], server_host = server_host, action = 'check file existance')
return file_name in ls.stdout
def scp_data_stora... | The main task of the code is to read a file from a remote server storage to a local storage, ensuring the file does not already exist locally or, if it does, verifying it is not identical via checksum before copying. It raises errors for missing files or existing duplicates, using SCP for transfer. | def scp_data_storage_read(file_name:str, server_host:str, server_storage_path:str, local_storage_path:str) -> bool:
'''storage read'''
if not scp_data_storage_file_exists(file_name, server_storage_path, server_host):
raise kobaza_error.DatasetFileNotFoundError(file_name, f'{server_host}:{server_storage_path}')
if... |
def scp_data_storage_file_exists(file_name:str, storage_path:str, server_host:str = '') -> bool:
'''check for file existance at path. leave server blank to check local'''
ls = custom_cmd(['ls', storage_path], server_host = server_host, action = 'check file existance')
return file_name in ls.stdout
def scp_data_stora... | This function securely transfers a local file to a remote server storage via SCP, ensuring no unintended overwrites. It checks if the local file exists, verifies if the server already has a file with the same name, compares checksums to detect duplicates, and only proceeds with transfer if the file differs or overwrite... | def scp_data_storage_write(file_name:str, server_host:str, server_storage_path:str, local_storage_path:str, overwrite:bool = False) -> bool:
'''
storage create and update, must specify overwrite to replace existing file
'''
if not scp_data_storage_file_exists(file_name, local_storage_path):
raise kobaza_error.Da... |
def jsonify(js):
'''
make sure $metaver_json is a json (dict), must not pass in json as a string
'''
if isinstance(js, str) and js:
js = json.loads(js)
return js
def is_valid_metavarset(metavar_json, verbose = False):
'''
validates that $metavar_json is the correct format for metavar json
'''
invalidities = ... | The main task of the code is to insert a metavarset JSON into both Elasticsearch and a database while ensuring data consistency. It validates the input, checks for existing entries, and performs insertions. If one store fails, it rolls back the other and raises specific errors (e.g., inconsistency, duplication) to aler... | def insert_metavarset(endpoint:str, username:str, password:str, metavar_json) -> bool:
'''
insert $metavar_json into both es and db, keep all data stores consistant, notify if they arent, may raise following errors on failure (MetavarsetIsInvalid, DataStoreInconsistantError, MetavarsetAlreadyPresentError, DatastoreOp... |
def is_metavarset_present(endpoint:str, username:str, password:str, ds):
'''
checks if metavarset ($ds) is present in the datastores and raises appropriate errors on inconsistancy
params:
$ds can be either full metavarset (type dict) or ds_id (type str)
return:
tuple with 2 bools for db and es being present in ... | The function deletes a metavarset identified by `ds_id` from both Elasticsearch (ES) and a database (DB), ensuring consistency between the two. It first verifies the dataset's existence, retrieves its data, and attempts deletion from the DB and ES. If ES deletion fails but DB deletion succeeds, it reinserts the data in... | def delete_metavarset(endpoint:str, username:str, password:str, ds_id) -> bool:
'''
delete metavarset with $ds_id from both es and db, may raise following errors on failure (kobaza_error.DataStoreInconsistantError, kobaza_error.MetavarsetNotFoundError, kobaza_error.MetavarsetDatastoreOperationFailedError)
'''
#che... |
def insert_metavarset(endpoint:str, username:str, password:str, metavar_json) -> bool:
'''
insert $metavar_json into both es and db, keep all data stores consistant, notify if they arent, may raise following errors on failure (MetavarsetIsInvalid, DataStoreInconsistantError, MetavarsetAlreadyPresentError, DatastoreOp... | This function inserts a dataset and its associated metadata (metavarset) into a system. It transfers the dataset via SCP to a server, then inserts the metadata. If either step fails, it ensures consistency by rolling back the other step. Error handling addresses invalid metadata, existing entries, or storage failures, ... | def insert_dataset_and_metavars(endpoint:str, username:str, password:str, server_host:str, server_storage_path:str, local_storage_path:str, uploaded_metavars_json:dict):
'''
this is the create in the crud for the dataset-metavarset pair
'''
dataset_filename = uploaded_metavars_json['cleaned data file']
ds_id = upl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.