dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def most_common_label(self, y):
counter = Counter(y)
most_common = counter.most_common(1)[0][0]
return most_common
def best_criteria(self, X, y, feat_idxs):
best_gain = -1
split_idx, split_thresh = None, None
for feat_idx in feat_idxs:
X_column = X[:, feat_idx... | This function recursively constructs a decision tree node by selecting the optimal feature and threshold to split the data, then building left and right subtrees. It terminates when reaching maximum depth, encountering pure labels, or insufficient samples, returning a leaf node with the most common label. | def grow_tree(self, X, y, depth=0):
n_samples, n_feautres = X.shape
n_labels = len(np.unique(y))
# stop
if (depth >= self.max_depth
or n_labels == 1
or n_samples < self.min_samples_split):
leaf_value = self.most_common_label(y)
ret... |
def addcourse(self, course_window):
coursename_entry = StringVar()
coursecode_entry = StringVar()
addcourse_Toplevel = Toplevel(self, bg="#243447")
addcourse_Toplevel.geometry("400x200")
addcourse_Toplevel.pack_propagate(False)
rowa = Frame(addcourse_Toplevel, bg = "#... | The code initializes a GUI window for managing courses, creating a Toplevel window with a Treeview to display course data (code and name), scrollbars for navigation, and buttons (Add, Edit, Delete) to manipulate course records. It configures layout, styling, and event bindings for user interaction with course data. | def course_window_init(self):
course_window = Toplevel(self, bg="#D2649A")
course_window.geometry("500x500")
course_window.grid_propagate(0)
course_window.grid_columnconfigure(0, weight=1)
course_window.grid_rowconfigure(0, weight=1)
self.cinput = StringVar()
... |
def get_text_features(self, batched_inputs: List[Dict[str, torch.Tensor]], index: int = 0) -> torch.Tensor:
if 'text_descriptions' in batched_inputs[index]:
for batch in batched_inputs:
batch.update(self._text_features(batch.pop('text_descriptions')))
return [inp['text_featur... | The code performs post-processing on detected instances by calculating their top probabilities and corresponding labels using text features. It uses either patch-wise similarity for VisionTransformer models or ROI feature similarity, then attaches these results to the instance data for output. | def inference(self, batched_inputs: List[Dict[str, torch.Tensor]]) -> List[Dict[str, torch.Tensor]]:
index = 0
instances = super().inference(batched_inputs)[index]
if len(instances['instances']) == 0:
return
text_features = self.get_text_features(batched_inputs, index)
... |
def inference(
self,
batched_inputs: List[Dict[str, torch.Tensor]],
detected_instances: Optional[List[Instances]] = None,
do_postprocess: bool = True,
):
assert not self.training, 'Running inference in training mode'
images = self.preprocess_image(batched_inputs)
... | This code computes multimodal losses by processing image-text pairs through a transformer. It calculates image and text features, aligns them via cosine similarity (scaled by logit_scale), normalizes features, and aggregates symmetric losses along with individual image/text losses for training. | def forward(self, batched_inputs: List[Dict[str, torch.Tensor]]) -> Dict[str, torch.Tensor]:
if not self.training:
return self.inference(batched_inputs)
if self.transformer.logit_scale.requires_grad:
# clamp to ln(100), as in the paper
with torch.no_grad():
... |
def bait_potion_counter():
global bait_counter,potion_round,TIME,potion_round_refill
if ((bait_counter % 10) == 0) and ((get_value("Use Bait")) == True):
log_info(f'Using bait...', logger="Information")
pyautogui.press("1")
time.sleep(1)
if ((int(TIME / 30)) > potion_round) and ((g... | This code automates a fishing rod casting process in a game. It continuously checks the state, casts the rod when in "CASTING" or "STARTED" mode, scans for a bobber, and triggers minigame actions if detected. It handles errors like missing bobbers by rescaning or recasting, logs status updates, and manages state transi... | def cast_hook():
global STATE,stop_button,mouse_pos,bobber_loc_array_initial,recognition_state,stuck_allert
while 1:
if (stop_button == False):
if STATE == "CASTING" or STATE == "STARTED":
time.sleep(1.6)
bait_potion_counter()
pyautogui.mouseUp... |
def compile_box(self,line_type):
points = {}
box_points = []
circle_points = []
points,out_points,circle_points = point_collection(line_type,self.center,self.inner_width,self.inner_height,self.inner_length,self.t,self.inset_flap,self.flap_width)
box_points = multi_mirror_points(s... | The main task of the code is to draw wrapped lines and incisions on an image. It compiles an outer box, converts its boundaries to pixel coordinates, and renders dashed lines for the wrap. The incision is mirrored, converted to pixels, and drawn as solid black lines with greater thickness, creating a visual representat... | def draw_wrap(self):
wrap,incision = self.compile_box("outer")
dashes = line_to_pixel(wrap,self.dpi)
# Draw the lines
for line in dashes:
draw_dashed(self.draw,line)
# self.draw.line(line, fill="black", width=2)
incision = double_mirror(self.center,[incision])
... |
def getFile(self, fileName):
folder = os.path.dirname(os.path.abspath(__file__))
file = os.path.join(folder, fileName)
return file
def createTable(self, cursor):
cursor.execute("""
CREATE TABLE IF NOT EXISTS employees(
id INTEGER PRIMARY KEY,
first_name TEXT (30... | The main task of the code is to retrieve employee data from an SQLite database. It connects to "biker.db," creates the necessary table, checks if the database exists, inserts data into the "Employees" table, and populates a list of employee objects if successful. The function returns this list after committing changes ... | def getFromDb(self):
connection = sqlite3.connect(self.getFile("biker.db")) # opens connection at each button press
cursor = connection.cursor()
self.createTable(cursor)
list = [] # returns an empty list if the following checks fail:
if self.databaseExists(cursor):
... |
def lists(self, employees): # makes lists from given employees for use in text widgets, id's not used in interface
firstNames, lastNames, roles, loginNames = [], [], [], []
for employee in employees:
firstNames.append(employee.firstName)
lastNames.append(employee.lastNam... | The code filters stored employee data based on search input, updates text widgets with matching results, displays a message if no results are found, and resets the interface, while handling empty employee lists with a warning. | def search(self, event = None): # show only data that matches search results
if self.storedEmployees != []:
results = []
for employee in self.storedEmployees:
if self.searchEntry.get().lower() in employee.firstName.lower() or self.searchEntry.get().lower() in employee.la... |
def fetch(self): # fetch all data and fill in text widgets / applies to the first two notebook tabs
self.storedEmployees = self.employees.getFromDb()
self.getTexts()
self.button.config(text = "Haal opnieuw op")
if self.storedEmployees != []:
self.dateLabel.config(text = date... | This code initializes a GUI application for "Biker Haaglanden," creating a tabbed interface with sections for employees, customers, bikes, and accessories. It sets up the main menu with an image, buttons to fetch data, and navigation between tabs. The employee tab includes search functionality and displays employee det... | def __init__(self, root):
root.title("Biker Haaglanden")
root.geometry("1090x600+100+75")
root.minsize(width = 1085, height = 600)
self.notebook = ttk.Notebook(root)
self.notebook.pack()
self.mainFrame = ttk.Frame(self.notebook, relief = RAISED)
self.notebook.ad... |
def eat(self):
value = self.lexer.get_token_value()
self.tokenType = self.lexer.next_token()
self.tokenLoc = self.lexer.tokenLoc()
return value
def expect(self, tokenType):
if self.tokenType != tokenType:
self.error('%s expected, found %s' % (tokenType, self.tokenType... | This method parses primary justification constructs from input tokens, returning structured tuples based on token types. It handles 'Herschrijven' (with fact spec and number), 'Z' (with optional fact spec), and identifiers (direct fact spec parsing), raising errors for unsupported tokens. | def parsePrimaryJustification(self):
if self.tokenType == 'Herschrijven':
self.eat()
self.expect('met')
i = self.parseFactSpec()
self.expect('in')
j = int(self.expect('number'))
return ('Herschrijven', i, j)
elif self.tokenType == '... |
def normalize_eq(e):
"""Rewrites an equation to a form not involving not or <, i.e. involving only ==, <=, or !="""
if e[0] == 'not':
e1 = normalize_eq(e[1])
if e1[0] == 'not':
e = e1[1]
elif e1[0] == '==':
e = ('!=', e1[1], e1[2])
elif e1[0] == '!=':
... | The function `follows_in_Z_from` checks if a logical consequent follows from an antecedent under integer arithmetic (ℤ). It normalizes both expressions, validates their operators (==, !=, <=), and compares their polynomial coefficients and constants. It verifies entailment by ensuring the consequent's structure (operat... | def follows_in_Z_from(consequent, antecedent):
antecedent = normalize_eq(antecedent)
consequent = normalize_eq(consequent)
if not {consequent[0], antecedent[0]} <= {'==', '<=', '!='}:
return False
if consequent[0] == '==' and antecedent[0] != '==':
return False
if consequent[0] == '<... |
def parsePrimaryJustification(self):
if self.tokenType == 'Herschrijven':
self.eat()
self.expect('met')
i = self.parseFactSpec()
self.expect('in')
j = int(self.expect('number'))
return ('Herschrijven', i, j)
elif self.tokenType == '... | The main task of the code is to parse a justification, which may include a primary justification or a recursive structure starting with the 'of' token. If the current token is 'of', it consumes the token and returns a tuple containing 'of', the parsed primary justification, and a recursively parsed justification. Other... | def parseJustification(self):
justification = self.parsePrimaryJustification()
if self.tokenType == 'of':
self.eat()
return ('of', justification, self.parseJustification())
return justification |
def pawn_moves_filtered(sudo_moves):
legal_moves = []
for sudo_move in sudo_moves:
if len(sudo_move.direction) == 3 and 'k' in sudo_move.type:
legal_moves.append(sudo_move)
elif len(sudo_move.direction) == 1 and sudo_move.type == 'x ':
legal_moves.append(sudo_move)
re... | This function generates legal moves for a chess piece on a board, considering pawn-specific rules (double move, en passant, end-of-file adjustments), castling for the king, and filtering out moves that leave the king in check. It returns a list of valid moves based on the piece's type, position, and game state. | def legal_moves(board, location_index):
moves = moves_piece_bounded(board, location_index)
piece = board[location_index[0]][location_index[1]]
team = piece.team
if piece.type == 'p':
moves = pawn_moves_filtered(moves)
doubled_move = double_first_pawn_move(piece, board, loca... |
def guiReviewActive(self):
return self.reviewer().card is not None and self.window().state == 'review'
def reviewer(self):
reviewer = self.window().reviewer
if reviewer is None:
raise Exception('reviewer is not available')
else:
return reviewer
def api(*versions):... | This method initiates a card's timer if review mode is active and the card exists. It checks if `guiReviewActive()` is true, retrieves the current card from the reviewer, and calls `startTimer()` on the card if valid. Returns `True` if successful, otherwise `False` | def guiStartCardTimer(self):
if not self.guiReviewActive():
return False
card = self.reviewer().card
if card is not None:
card.startTimer()
return True
else:
return False |
def guiReviewActive(self):
return self.reviewer().card is not None and self.window().state == 'review'
def reviewer(self):
reviewer = self.window().reviewer
if reviewer is None:
raise Exception('reviewer is not available')
else:
return reviewer
def api(*versions):... | This method checks if a review is active; if so, it delegates to the reviewer's _showQuestion() method and returns True, otherwise returns False. Its primary task is to conditionally display a question via the reviewer based on the current review status. | def guiShowQuestion(self):
if self.guiReviewActive():
self.reviewer()._showQuestion()
return True
else:
return False |
def guiReviewActive(self):
return self.reviewer().card is not None and self.window().state == 'review'
def window(self):
return aqt.mw
def api(*versions):
def decorator(func):
method = lambda *args, **kwargs: func(*args, **kwargs)
setattr(method, 'versions', versions)
setattr... | This method checks if a review is active; if true, it triggers the reviewer's interface to display an answer and returns True, otherwise returns False. | def guiShowAnswer(self):
if self.guiReviewActive():
self.window().reviewer._showAnswer()
return True
else:
return False |
def guiReviewActive(self):
return self.reviewer().card is not None and self.window().state == 'review'
def reviewer(self):
reviewer = self.window().reviewer
if reviewer is None:
raise Exception('reviewer is not available')
else:
return reviewer
def scheduler(self)... | This function handles GUI-based card answering in a spaced repetition system. It validates if the review is active, the reviewer is in 'answer' state, and the ease value is within allowed bounds. If valid, it triggers the card answer process and returns True; otherwise, it returns False. | def guiAnswerCard(self, ease):
if not self.guiReviewActive():
return False
reviewer = self.reviewer()
if reviewer.state != 'answer':
return False
if ease <= 0 or ease > self.scheduler().answerButtons(reviewer.card):
return False
reviewer._ans... |
def database(self):
database = self.collection().db
if database is None:
raise Exception('database is not available')
else:
return database
def decks(self):
decks = self.collection().decks
if decks is None:
raise Exception('decks are not availa... | This function groups a list of card IDs into dictionaries keyed by deck names. It queries the database to find the deck ID (did) for each card, retrieves the corresponding deck name, and appends the card to the deck's list in the output dictionary. The result maps deck names to lists of card IDs belonging to those deck... | def getDecks(self, cards):
decks = {}
for card in cards:
did = self.database().scalar('select did from cards where id=?', card)
deck = self.decks().get(did)['name']
if deck in decks:
decks[deck].append(card)
else:
decks[deck... |
def startEditing(self):
self.window().requireReset()
def decks(self):
decks = self.collection().decks
if decks is None:
raise Exception('decks are not available')
else:
return decks
def stopEditing(self):
if self.collection() is not None:
self.... | This method retrieves the ID of a specified deck while ensuring the editing session is properly initiated and terminated, returning the deck's ID (did) after processing. | def createDeck(self, deck):
try:
self.startEditing()
did = self.decks().id(deck)
finally:
self.stopEditing()
return did |
def startEditing(self):
self.window().requireReset()
def collection(self):
collection = self.window().col
if collection is None:
raise Exception('collection is not available')
else:
return collection
def stopEditing(self):
if self.collection() is not None:... | This function moves specified cards to a new deck by updating their deck ID, modification time, and user sequence number in the database. It first removes cards from their current dynamic deck, then updates their metadata in the 'cards' table. The process is wrapped in startEditing() and stopEditing() to manage databas... | def changeDeck(self, cards, deck):
self.startEditing()
did = self.collection().decks.id(deck)
mod = anki.utils.intTime()
usn = self.collection().usn()
# normal cards
scids = anki.utils.ids2str(cards)
# remove any cards from filtered deck first
self.colle... |
def startEditing(self):
self.window().requireReset()
def collection(self):
collection = self.window().col
if collection is None:
raise Exception('collection is not available')
else:
return collection
def stopEditing(self):
if self.collection() is not None:... | This code adds specified tags to given notes in a collection using a bulk operation. It initiates an editing session, applies the tag additions, then finalizes the changes. The 'add' parameter determines if tags are added (True) or removed (False), with True as the default. | def addTags(self, notes, tags, add=True):
self.startEditing()
self.collection().tags.bulkAdd(notes, tags, add)
self.stopEditing() |
def createNote(self, note):
collection = self.collection()
model = collection.models.byName(note['modelName'])
if model is None:
raise Exception('model was not found: {}'.format(note['modelName']))
deck = collection.decks.byName(note['deckName'])
if deck is None:
... | The main task of the code is to add a note to an Anki collection, handling audio attachments by downloading files, verifying them via MD5 hash to avoid duplicates, embedding sound tags in relevant fields, and managing errors. It creates a note, processes audio data, writes media files, and saves the note to the collect... | def addNote(self, note):
ankiNote = self.createNote(note)
audio = note.get('audio')
if audio is not None and len(audio['fields']) > 0:
try:
data = self.download(audio['url'])
skipHash = audio.get('skipHash')
if skipHash is None:
... |
def suspended(self, card):
card = self.collection().getCard(card)
return card.queue == -1
def scheduler(self):
scheduler = self.collection().sched
if scheduler is None:
raise Exception('scheduler is not available')
else:
return scheduler
def startEditing(s... | This function suspends or unsuspends specified cards based on their current status. It filters cards that already match the target suspension state, then uses the scheduler to apply the suspension/unsuspension. Returns True if cards were processed, False if none remained after filtering. | def suspend(self, cards, suspend=True):
for card in cards:
if self.suspended(card) == suspend:
cards.remove(card)
if len(cards) == 0:
return False
scheduler = self.scheduler()
self.startEditing()
if suspend:
scheduler.suspendC... |
def modelNames(self):
return self.collection().models.allNames()
def collection(self):
collection = self.window().col
if collection is None:
raise Exception('collection is not available')
else:
return collection
def api(*versions):
def decorator(func):
... | The code retrieves model names and their corresponding IDs from a collection, creating a dictionary that maps each model name to its integer ID, then returns this dictionary. | def modelNamesAndIds(self):
models = {}
for model in self.modelNames():
models[model] = int(self.collection().models.byName(model)['id'])
return models |
def collection(self):
collection = self.window().col
if collection is None:
raise Exception('collection is not available')
else:
return collection
def deckNameFromId(self, deckId):
deck = self.collection().decks.get(deckId)
if deck is None:
rai... | This function retrieves detailed information for each card in the input list, including fields, question/answer, model, deck, and metadata. It constructs a structured list of dictionaries, handling missing card IDs by adding empty entries to maintain input-output correspondence. | def cardsInfo(self, cards):
result = []
for cid in cards:
try:
card = self.collection().getCard(cid)
model = card.model()
note = card.note()
fields = {}
for info in model['flds']:
order = info... |
def guiReviewActive(self):
return self.reviewer().card is not None and self.window().state == 'review'
def reviewer(self):
reviewer = self.window().reviewer
if reviewer is None:
raise Exception('reviewer is not available')
else:
return reviewer
def deckNameFromId(... | The function retrieves and structures current card data for GUI display, checking if review is active, then compiling card details like fields, question/answer, model info, and UI elements into a dictionary for presentation. | def guiCurrentCard(self):
if not self.guiReviewActive():
raise Exception('Gui review is not currently active.')
reviewer = self.reviewer()
card = reviewer.card
model = card.model()
note = card.note()
fields = {}
for info in model['flds']:
... |
def findCards(self, query=None):
if query is None:
return []
else:
return self.collection().findCards(query)
def collection(self):
collection = self.window().col
if collection is None:
raise Exception('collection is not available')
else:
... | The code determines if each card in the input list is due for review. It checks if a card is new, queries its review log for the latest interval and date, and evaluates due status based on interval thresholds or time comparisons, returning a list of booleans indicating each card's due status. | def areDue(self, cards):
due = []
for card in cards:
if self.findCards('cid:{} is:new'.format(card)):
due.append(True)
else:
date, ivl = self.collection().db.all('select id/1000.0, ivl from revlog where cid = ?', card)[-1]
if ivl >=... |
def findCards(self, query=None):
if query is None:
return []
else:
return self.collection().findCards(query)
def collection(self):
collection = self.window().col
if collection is None:
raise Exception('collection is not available')
else:
... | The main task of the code is to retrieve interval values (ivl) for each card from the revlog database. For new cards, it returns 0; for existing cards, it fetches the latest interval value (or the last entry if `complete=False`). The result is a list of intervals corresponding to the input cards. | def getIntervals(self, cards, complete=False):
intervals = []
for card in cards:
if self.findCards('cid:{} is:new'.format(card)):
intervals.append(0)
else:
interval = self.collection().db.list('select ivl from revlog where cid = ?', card)
... |
def guiDeckOverview(self, name):
collection = self.collection()
if collection is not None:
deck = collection.decks.byName(name)
if deck is not None:
collection.decks.select(deck['id'])
self.window().onOverview()
return True
... | The main task of the code is to determine if a deck overview can be displayed; if successful, it transitions the application window to the 'review' state and returns True, otherwise returns False. This function acts as a conditional gatekeeper for initiating the review process based on the outcome of the deck overview ... | def guiDeckReview(self, name):
if self.guiDeckOverview(name):
self.window().moveToState('review')
return True
else:
return False |
def deckNames(self):
return self.decks().allNames()
def decks(self):
decks = self.collection().decks
if decks is None:
raise Exception('decks are not available')
else:
return decks
def api(*versions):
def decorator(func):
method = lambda *args, **kwarg... | This method generates a dictionary mapping deck names to their corresponding IDs by iterating over each deck name from `self.deckNames()`, retrieving the ID using `self.decks().id(deck)`, and returning the resulting dictionary. | def deckNamesAndIds(self):
decks = {}
for deck in self.deckNames():
decks[deck] = self.decks().id(deck)
return decks |
def startEditing(self):
self.window().requireReset()
def deckNames(self):
return self.decks().allNames()
def decks(self):
decks = self.collection().decks
if decks is None:
raise Exception('decks are not available')
else:
return decks
def stopEditing(self):... | This method deletes specified decks from a collection, optionally including their associated cards. It first ensures an editing session is active, filters input decks to only those existing in the collection, retrieves each deck's ID, and deletes them (and cards if specified). Finally, it stops the editing session to f... | def deleteDecks(self, decks, cardsToo=False):
try:
self.startEditing()
decks = filter(lambda d: d in self.deckNames(), decks)
for deck in decks:
did = self.decks().id(deck)
self.decks().rem(did, cardsToo)
finally:
self.stopE... |
def deckNames(self):
return self.decks().allNames()
def collection(self):
collection = self.window().col
if collection is None:
raise Exception('collection is not available')
else:
return collection
def api(*versions):
def decorator(func):
method = lam... | The function retrieves the configuration of a specified deck by first verifying its existence, then obtaining its ID from the collection, and finally returning the corresponding deck configuration. | def getDeckConfig(self, deck):
if not deck in self.deckNames():
return False
collection = self.collection()
did = collection.decks.id(deck)
return collection.decks.confForDid(did) |
def deckNames(self):
return self.decks().allNames()
def collection(self):
collection = self.window().col
if collection is None:
raise Exception('collection is not available')
else:
return collection
def api(*versions):
def decorator(func):
method = lam... | This function assigns a specified configuration ID to multiple decks in an Anki collection. It validates that all input decks exist and the config ID is valid, then updates each deck's configuration ID in the collection's data structure. Returns True if successful, False if any validation fails. | def setDeckConfigId(self, decks, configId):
configId = str(configId)
for deck in decks:
if not deck in self.deckNames():
return False
collection = self.collection()
if not configId in collection.decks.dconf:
return False
for deck in decks... |
def deleteMediaFile(self, filename):
self.media().syncDelete(filename)
def media(self):
media = self.collection().media
if media is None:
raise Exception('media is not available')
else:
return media
def api(*versions):
def decorator(func):
method = lam... | This function stores a media file by first deleting any existing file with the given filename, then writing the decoded base64 data to the specified media file. | def storeMediaFile(self, filename, data):
self.deleteMediaFile(filename)
self.media().writeData(filename, base64.b64decode(data)) |
def get_aug_config():
scale_factor = 0.25
rot_factor = 30
color_factor = 0.2
scale = np.clip(np.random.randn(), -1.0, 1.0) * scale_factor + 1.0
rot = np.clip(np.random.randn(), -2.0,
2.0) * rot_factor if random.random() <= 0.6 else 0
do_flip = random.random() <= 0.5
... | This code processes a dataset entry by loading an image, applying data augmentation (flip, rotation, color scaling), transforming joint coordinates with affine transformations, normalizing depth values, and preparing training data. It returns the augmented image patch, joint coordinates, visibility flags, and depth inf... | def __getitem__(self, index):
joint_num = self.joint_num
skeleton = self.skeleton
flip_pairs = self.flip_pairs
joints_have_depth = self.joints_have_depth
data = copy.deepcopy(self.db[index])
bbox = data['bbox']
joint_img = data['joint_img']
join... |
def getKeyNames(self, sectionName):
"""
section is the name of the section from which to get the key names.
section exists? is TRUE if the VI found the specified section.
"""
break_section=self.getSectionNames()
keyNames=[]
self.__goToBegin()
if (section... | This code removes a specified section from a configuration file by first deleting all its keys, then using a temporary file to exclude the section's lines during rewrite. It returns True if the section was removed, False otherwise. | def removeSection(self, sectionName):
"""
section is the name of the section to remove.
section exists? is TRUE if the VI found the specified section.
"""
try:
#start by removing each key
keys=self.getKeyNames(sectionName)
names=self.getSectio... |
def parse_command_line():
"""Runs Command line argument parser for pipeline. Exit program on bad arguments. Returns struct of arguments"""
from typing import List
def parse_directory(path : str) -> str:
"""Command line argument parser for directory path arguments. Raises argument error if the path d... | (The main task of the code is to execute a pipeline with logging, hardware checks, directory management, and mode-specific operations. It parses command-line arguments, initializes logging, logs system parameters, displays GPU details, creates output directories, deletes old validation files, and runs either AMQP or lo... | def main():
main_time = time()
args = parse_command_line()
# Start logger
if args.verbose:
global FILE_LOG_LEVEL, STREAM_LOG_LEVEL
FILE_LOG_LEVEL = logging.DEBUG
STREAM_LOG_LEVEL = logging.DEBUG
global log
log = start_logger(LOGGER_NAME, args.log, log_level=FILE_LOG_LEVE... |
def check_events(self,manual):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
print(self.score)
if event.type == pygame.QUIT:
sys.exit()
if manual:
if event.type == pygame.KEYDOWN:
... | The main task of the code is to execute the game's main loop, handling either manual player input or Q-learning-based AI behavior depending on settings. It processes events, updates the screen, moves the agent, and maintains a target frame rate using pygame's clock, while optionally detecting collisions and applying re... | def run_game(self):
""""Main loop of the game."""
while True:
if self.settings.manual:
self.check_events(self.settings.manual)
self.update_screen()
self.agent.move_agent(self.settings.manual)
#self.detect_collision()
... |
def manhattan_distance(xStart, yStart, xDest, yDest):
return abs(xStart - xDest) + abs(yStart - yDest)
def get_path(x, y, xDest, yDest, grid, dynamic_paths_collection=None):
start = (x, y)
end = (xDest, yDest)
if dynamic_paths_collection is not None:
if (x, y, xDest, yDest) in dynamic_paths_col... | This function identifies cars that can reach a passenger within a specified "patience" range. It filters cars by checking if their Manhattan distance to the passenger is within the patience limit and if the actual path length (using a grid and dynamic paths) is also within the limit. Valid cars are collected and return... | def get_cars_in_patience_range(cars, passenger, grid, patience, dynamic_paths_collection):
cars_in_range = []
(x, y) = passenger.x, passenger.y
for car in cars:
approx_dist = manhattan_distance(car.x, car.y, x, y)
if approx_dist > patience:
continue
path = get_path(car.x... |
def car_pooling_update(cache):
cars = cache["cars"]
available_cars = [car for car in cars if len(car.passengers_list) < CAR_CAPACITY]
if len(available_cars) > 0:
for passenger in cache["passengers"].values():
if passenger.car_id is not None:
pass # cruisin in da hood
... | This function simulates passenger and car movement in a transportation system, updating passenger states (travel time, waiting time), managing car movements, spawning new passengers randomly and in hotspots, and incrementing simulation ticks. It returns True when maximum ticks are reached, otherwise False. | def update(cache):
cars = cache["cars"]
taxi_cars = cache["taxi_cars"]
passengers = cache["passengers"]
taxi_passengers = cache["taxi_passengers"]
if cache["ticks"] >= cache["maxTicks"]:
return True
for passenger in cache["passengers"].values():
if passenger.is_in_car:
... |
def input_validation_static_dict(self,
external_dict,
previous_menu=None,
location=None,
function_pointer=None,
argument=None,
... | The code adds a new project to a dictionary, validating client and manager selections. It ensures the project name is unique, creates entries for active/inactive tickets, and updates the UI. | def add_project(self):
client_name = self.input_validation_static_dict(self.client_list,
self.project_menu,
'Choose a Client',
None,
... |
def input_validation_static_dict(self,
external_dict,
previous_menu=None,
location=None,
function_pointer=None,
argument=None,
... | The code's main task is to close a selected project by validating input, checking for active tickets, and moving the project to an inactive state if no active tickets exist. If active tickets are present, it alerts the user and returns to the project menu. Upon successful closure, it updates the project dictionary, con... | def close_project(self):
project_name = self.input_validation_static_dict(self.active_project_dict,
self.project_menu,
'Choose a project',
No... |
def input_validation_static_dict(self,
external_dict,
previous_menu=None,
location=None,
function_pointer=None,
argument=None,
... | This code adds a new ticket to a specified project by validating user input for an employee, retrieving project details, ensuring the ticket name is unique, and then linking the ticket to the project with associated metadata. It handles input validation, checks for duplicates, and updates project and ticket dictionarie... | def add_ticket(self, project_name):
employee_name = self.input_validation_static_dict(self.employee_list,
self.project_menu,
'Choose an employee',
... |
def face_normals(mesh):
"""
Args:
mesh: tensor(float), shape (num_faces, 3, 3)
Returns:
normals: tensor(float), shape (num_faces, 3)
"""
vec_a = mesh[:, 0] - mesh[:, 1]
vec_b = mesh[:, 1] - mesh[:, 2]
normals = torch.cross(vec_a, vec_b)
return normals
def area_weighted_di... | This function generates 3D sample points on a mesh surface using specified methods. It computes face normals if not provided, applies area-weighted distribution by default, and samples points uniformly, on the surface, or near the surface based on input parameters. Results from multiple methods are concatenated into a ... | def sample_points(mesh, num_samples_and_method, normals=None, distrib=None):
"""
Args:
mesh: tensor(float), shape (num_faces, 3, 3)
num_samples_and_method: [tuple(int, str)]
normals: tensor(float), shape (num_faces, 3)
distrib: distribution
Returns:
samples: tensor(fl... |
def get(self):
return self.matrix
def is_solvable(self):
self.matrix_colored = deepcopy(self.matrix)
# Mask all the filled pieces
for i in range(8):
for j in range(7):
if isinstance(self.matrix_colored[i][j], int) or \
self.matrix_colo... | The main task of the code is to overlay a piece `p` onto a matrix at specified coordinates `(row, col)`, ensuring no conflicts with existing elements like "X", "D", or integers. If valid, it updates the matrix and checks if the resulting state is solvable, returning `True` if so; otherwise, it returns `False` on confli... | def overlay_piece(self, row: int, col: int, p):
matrix = deepcopy(self.get())
for i in range(len(p)):
for j in range(len(p[0])):
try:
if p[i][j] == "-":
continue
else:
if matrix[row + i][... |
def find_remaining(self):
self.remaining_locations = []
for i in range(8):
for j in range(7):
self.remaining_locations.append([i, j])
def next_location(self):
return self.remaining_locations.pop(0)
def overlay_piece(self, row: int, col: int, p):
matrix = deepc... | This method attempts to place a given piece in the next available location by repeatedly calling `next_location()` and `overlay_piece()`, continuing until the piece is successfully placed or no valid locations remain. It returns a boolean indicating whether placement was successful. | def place_piece(self, piece):
self.find_remaining()
placed = False
while not placed:
try:
loc = self.next_location()
except BaseException:
break
placed = self.overlay_piece(loc[0], loc[1], piece)
return placed |
def chanceOfLoss(hand):
deck = ["2","2", "2", "2", "3", "3", "3", "3", "4", "4", "4", "4", "5", "5", "5", "5", "6", "6", "6", "6",
"7", "7", "7", "7", "8", "8", "8", "8", "9", "9", "9", "9", "10", "10", "10", "10",
"J", "J", "J", "J", "Q", "Q", "Q", "Q", "K", "K", "K", "K", "A", "A... | This function simulates a card game decision-making process where a player chooses to 'hit' or 'stand'. It calculates probabilities of game outcomes based on the current state (player and dealer hands), recursively evaluating possible actions. When 'hit' is chosen, it appends a card ("R") and computes continuation chan... | def placeOfBattle(stateArr, action):
if action == "hit":
chanceOfContinuing = 1 - chanceOfLoss(stateArr[0])
stateArr[0].append("R")
return_value = placeOfBattle(stateArr, "stand")
return return_value[0] * chanceOfContinuing, ["hit"] + return_value[1]
else:
if calculateTo... |
def install_signal_handlers():
if os.name == 'posix':
signal.signal(signal.SIGUSR1, signal_handler)
signal.signal(signal.SIGUSR2, signal_handler)
def download_song(self, song: song_metadata.SongMetadata) -> bool:
if self.exit_requested:
return False
if song is not None:
... | The code retrieves songs based on artist/album, manages a playlist directory, selects platform-specific audio players, optionally shuffles songs, downloads and plays them sequentially, handles pausing, and manages exit signals with PID tracking. | def play_songs(self, shuffle: bool = False, artist: str = "", album: str = ""):
self.song_list = self.jukebox_db.retrieve_songs(artist, album)
if self.song_list is not None:
self.number_songs = len(self.song_list)
if self.number_songs == 0:
print("no songs in juk... |
def get_encryptor(self):
# key_block_size = 16 # AES-128
# key_block_size = 24 # AES-192
key_block_size = 32 # AES-256
return aes.AESBlockEncryption(key_block_size,
self.jukebox_options.encryption_key,
self.ju... | The main task of the code is to import song files by processing metadata, handling compression/encryption, uploading to storage, and updating the local database. It iterates through files in a directory, extracts metadata, prepares data for storage, uploads to a storage system, tracks progress, and reports upload stati... | def import_songs(self):
if self.jukebox_db is not None and self.jukebox_db.is_open():
dir_listing = os.listdir(self.song_import_dir)
num_entries = float(len(dir_listing))
progressbar_chars = 0.0
progressbar_width = 40
progress_chars_per_iteration = pro... |
def get_main_content(self, row):
return self.strip_spaces(str(row[self.MAIN_CONTENT_COLUMN]))
def get_next(self):
self.current_row, row = next(self.iter)
return row
def parse_contract_data(self):
self.get_next()
department_info = self.get_main_content(self.get_next())
... | This method collects contract data by iterating through items, appending parsed contracts to a list when a specific trigger is detected, and returns the list upon reaching the end of iteration. | def get_contracts(self):
contracts = []
add_contract = contracts.append
try:
while True:
if self.get_main_content(
self.get_next()
) == CONTRACT_START_TRIGGER:
add_contract(self.parse_contract_data())
... |
def __setError(self, status):
"""Internal function that sets different error at different program execution step
Args:
status (int): Denotes the error code
"""
self.err.setError(status)
def showError(self):
"""Function to return the set error
"""
self... | The main task of the code is to retrieve column names from a DataFrame, handling nested structures like structs and arrays by recursively exploring them. It returns column names directly for simple types, drills into struct fields (with `.*` notation), and processes array elements by exploding arrays and recursively ca... | def getColumnNames(self, colname = None, df = None):
"""Function to get all the column names of the provided df
Args:
colname (string, optional): If supplied searches the dataframe for this column and returns all the column names inside this column. Defaults to None.
df (_type_,... |
def __searchTrueDF(self, colname, df):
"""Internal recursion function which is used to return the dataframe which contains the colname as column. The column can be in any level of the dataframe
Args:
colname (string): The column to search in the dataframe
df (spark.df): The dataf... | This function displays rows of a DataFrame with options to specify the number of rows, vertical formatting, truncation, specific columns, and source DataFrame. It handles cases where the column might exist in a different DataFrame, showing data or setting errors if the column is not found. | def showRows(self, no = 20, vertical = False, truncate = True, colname = None, df = None, all = False):
"""Function to display the rows
Args:
no (int, optional): How many rows to display?. Defaults to 20.
vertical (bool, optional): Should the rows be displayed vertically, one at... |
def getColumnNames(self, colname = None, df = None):
"""Function to get all the column names of the provided df
Args:
colname (string, optional): If supplied searches the dataframe for this column and returns all the column names inside this column. Defaults to None.
df (_type_,... | The function recursively flattens nested DataFrame columns by traversing hierarchical structures, appending parent-child relationships with dots (e.g., "parent.child") to populate `self.flatCols` for search functionality. It uses `getColumnNames` to identify subcolumns, processes lists recursively, and constructs hiera... | def flatten(self, df = None, parentColumn = None):
"""Recursive function to populate the internal flatfields with the column name required for search function
Args:
df (spark.df, optional): The dataframe to use the flatten on. Defaults to None.
parentColumn (string, optional): J... |
def __searchTrueDF(self, colname, df):
"""Internal recursion function which is used to return the dataframe which contains the colname as column. The column can be in any level of the dataframe
Args:
colname (string): The column to search in the dataframe
df (spark.df): The dataf... | The function displays unique values in a specified column of a DataFrame along with their recurrence counts, sorted by frequency (descending by default). It handles nested columns, resolves data types, and optionally returns the resulting DataFrame instead of displaying it. | def showUniqueData(self, colname, df = None, desc = True, returnDf = False):
"""Function to display only unique data from a particular column with the number of times this data is recurrent in the dataset
Args:
colname (_type_): The column to collect data on
df (_type_, optional... |
def __getFiletype(self, fileName):
"""Internal Function that is used to get the file extension of the supplied file
Args:
fileName (string): Filename in the same directory as example.py
Returns:
string: Extension of the file
"""
if fileName in os.listdir... | This function reads a dataset from a file into a Spark DataFrame, handling JSON, CSV, and XLSX formats. It converts XLSX to CSV using xlsx2csv, applies error checks, fixes columns, and returns the DataFrame if the 'default' flag is True; otherwise, it stores it in self.df. | def readFile(self, fileName, default = False):
"""Function that reads the dataset into spark dataframe
Args:
fileName (string): The name of the dataset
default (bool, optional): Flag which denotes whether to return the dataframe(True) or not(False). Defaults to False.
R... |
def flatten(self, df = None, parentColumn = None):
"""Recursive function to populate the internal flatfields with the column name required for search function
Args:
df (spark.df, optional): The dataframe to use the flatten on. Defaults to None.
parentColumn (string, optional): J... | This function identifies and returns either the count of duplicate rows or the actual duplicate rows in a Spark DataFrame. It checks duplicates based on specified columns, handling nested fields, and computes results using SQL queries. If `count=True`, it returns the duplicate count; otherwise, it returns the distinct ... | def getDuplicates(self,count = True , columns = None , df = None):
"""Function to get the duplicates, either count or the actual duplicates encountered in the dataset
Args:
count (bool, optional): Should only the number of duplicates be returned?. Defaults to True.
columns (stri... |
def getColumnNames(self, colname = None, df = None):
"""Function to get all the column names of the provided df
Args:
colname (string, optional): If supplied searches the dataframe for this column and returns all the column names inside this column. Defaults to None.
df (_type_,... | This code generates a summary of a file's data, including column names, row count, and optional null statistics. If 'stat=True', it calculates null counts per column using SQL queries, creates a detailed stats DataFrame, and displays it. It also prints the schema tree. | def summary(self, stat = False):
"""As the name specifies summary
"""
print("File selected = {}".format(self.fileName))
print("="*(20+len(self.fileName)))
print("Column Names: {}".format(", ".join(self.getColumnNames())))
print("Column Count: {}".format(len(self.getColumn... |
def __searchTrueDF(self, colname, df):
"""Internal recursion function which is used to return the dataframe which contains the colname as column. The column can be in any level of the dataframe
Args:
colname (string): The column to search in the dataframe
df (spark.df): The dataf... | The function `search` queries a dataset (Spark DataFrame) for records matching a specified search term in a given field, supporting flexible field paths and display configurations. It constructs SQL queries based on the data type of the search field (using `rlike` for strings, `array_contains` for others), executes the... | def search(self, searchquery=None, searchfield=None, displayfields = None, show = True, df = None):
"""A powerful function which can search the dataset for any data in any field supplied
Args:
searchquery (string, optional): What to search?. Defaults to None.
searchfield (string... |
def flatten(self, df = None, parentColumn = None):
"""Recursive function to populate the internal flatfields with the column name required for search function
Args:
df (spark.df, optional): The dataframe to use the flatten on. Defaults to None.
parentColumn (string, optional): J... | This function removes duplicates from a dataset based on specified columns or all columns if none are provided. It checks column validity, flattens nested structures, and updates the dataframe while displaying the distinct count and duplicate removal details. | def removeDuplicates(self, columns = None):
"""Function to remove the duplicates from the dataset and display the duplicates removed
Args:
columns (string, optional): Columns to check for duplicates. Defaults to None.
"""
df = self.df
if columns != None:
... |
def printAtEachStep(self, iteration):
print(COLOR['BOLD']+COLOR['UNDERLINE']+
COLOR['PURPLE']+"Iteration "+str(iteration)+COLOR['END'])
self.printPolicy(t=1)
def isTarget(self, state):
return self.target == state.vertex
def utilityFromAction(self, edge, consecutive_states):
... | The code implements value iteration for a reinforcement learning problem, updating each state's utility and optimal action until convergence. It iteratively evaluates all actions for non-terminal states, selects the highest-utility action, and updates state values if changes occur. The process repeats until no further ... | def valueIteration(self):
print_steps = HurricaneEnv.yesNoToBool(input("Do you want to print each step? (y/n)\t"))
changed = True
iteration = 0
while changed:
if iteration>10000:
raise Exception("didn't converge")
iteration += 1
if prin... |
def printInitialData(self):
print('graph: \n'+self.graph.to_print(start=self.start, target=self.target))
def constructStates(self, blockages):
self.belief_states = []
for vertex in self.graph.vertices:
for blockages_belief in (list(tup) for tup in product([BLOCKED, UNBLOCKED, UNKNOWN... | The main task of the code is to initialize and run an environment simulation involving blockages and states. It constructs states, performs value iteration for decision-making, and enters a loop to handle user actions like printing policies, running examples, or displaying the graph. The environment allows user interac... | def run_env(self):
self.printInitialData()
blockages = self.graph.getBlockages()
state_file.initBlockagesDictionary(blockages)
self.constructStates(blockages)
self.initializeStates()
self.valueIteration()
while True:
user_action = self.getUserAction()
... |
def blockify_chunks(chunks):
"""Joins chunks in up to 256-byte blocks, and generates
a stream of (block, original_byte_size)."""
acc = []
size = 0
for chunk, chunk_size in chunks:
assert len(chunk) == CHUNK_SIZE
assert len(acc) <= BLOCK_SIZE
if len(acc) == BLOCK_SIZE:
... | The function `umash_long` processes a buffer (`buf`) by chunking it, compressing the chunks using a key and seed, performing polynomial reduction on the compressed values, and finalizing the result to generate a hash or authentication tag. It ensures the buffer meets a minimum size requirement and leverages key compone... | def umash_long(key, seed, buf, secondary):
assert len(buf) >= CHUNK_SIZE / 2
blocks = blockify_chunks(chunk_bytes(buf))
oh_values = oh_compress(key.oh, seed, blocks, secondary)
poly_acc = poly_reduce(key.poly, len(buf), oh_values)
return finalize(poly_acc) |
def __assign_tokens(self, ddc_class_model_list):
self.tokens = [i.class_token_dict for i in ddc_class_model_list]
self.tokens = list(set().union(*self.tokens))
self.tokens.sort()
def __assign_ddc_classes(self, ddc_class_model_list):
self.ddc_classes = [i.ddc_class for i in ddc_class_mode... | The code constructs a model using the provided DDC class model list by assigning tokens, DDC classes, building a model matrix, and initializing threshold dictionaries, likely for classification or data processing tasks. | def construct_model(self, ddc_class_model_list):
self.__assign_tokens(ddc_class_model_list)
self.__assign_ddc_classes(ddc_class_model_list)
self.__construct_model_matrix(ddc_class_model_list)
self.__init_threshold_dicts() |
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0, num_layers - 1):
W = self.xavier_init(size=[layers[l], layers[l + 1]])
b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtype=tf.float32)
... | This code initializes a physics-informed neural network (PINN) for solving fluid dynamics equations. It sets up material properties, collocation points, boundary conditions, and neural network layers. Placeholder tensors are defined for different domains (inlet, outlet, internal points). The code computes physics-infor... | def __init__(self, Collo, INLET, internal, OUTLET_d, OUTLET_n, CYLD, TOP_BOTTOM, uv_layers, lb, ub, ExistModel, uvDir):
# Count for callback function
self.count=0
# Bounds
self.lb = lb
self.ub = ub
# Mat. properties
self.rho = 1.0
#self.mu = 0.02
... |
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0, num_layers - 1):
W = self.xavier_init(size=[layers[l], layers[l + 1]])
b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtype=tf.float32)
... | This code initializes a physics-informed neural network (PINN) for solving fluid dynamics problems governed by Navier-Stokes equations. It sets up collocation points for subdomains, boundaries (inlet, outlet, walls, cylinder), and interfaces. The class defines neural network layers, TensorFlow placeholders, and loss fu... | def __init__(self, collo1, collo2, interface, INLET, internal, OUTLET, CYLD, WALL, uv_layers, lb, ub, ExistModel=0, uvDir=''):
# Count for callback function
self.count=0
self.count2=0
# Bounds
self.lb = lb
self.ub = ub
# Mat. properties
self.rho = 1.0
... |
def initialize_NN(self, layers):
weights = []
biases = []
num_layers = len(layers)
for l in range(0, num_layers - 1):
W = self.xavier_init(size=[layers[l], layers[l + 1]])
b = tf.Variable(tf.zeros([1, layers[l + 1]], dtype=tf.float32), dtype=tf.float32)
... | This code initializes a physics-informed neural network (PINN) for solving partial differential equations (PDEs) in fluid dynamics. It sets up collocation points, boundary conditions (inlets, outlets, walls), and internal points, defines neural network layers, computes physics-based residuals (mass, momentum, stress), ... | def __init__(self, Collo, INLET, internal, OUTLET, WALL, uv_layers, lb, ub, ExistModel=0, uvDir=''):
# Count for callback function
self.count=0
# Bounds
self.lb = lb
self.ub = ub
# Mat. properties
#self.rho = 1.0
#self.mu = 0.02
#self.mu = 0.025... |
def get_prominent_segment(beat, A, R):
C = get_C_point(beat, R)
A = R
if len(beat[A:C]) < 3:
#print ('R and C too close')
return []
positive_segments = monotone_segments(beat[A:C])
prominent_segs = []
heights = []
count = 0
flag = 0
label = np.zeros(len(positive_segme... | The function identifies inflection points in a signal by analyzing the most prominent segment of a beat. It computes second and third derivatives, detects zero crossings in the third derivative, and filters them using thresholds based on a parameter H. Valid indices are combined with the prominent segment's starting in... | def get_inflection_points(beat, A, R, fs=500):
most_prominent_seg_index = get_prominent_segment(beat, A, R)
if len(most_prominent_seg_index) == 0:
analyze_segment = []
else:
most_prominent_seg = beat[most_prominent_seg_index]
H = get_dzdt_H(beat, A, R)
zero_crossing_kept = []... |
def get_prominent_segment(beat, A, R):
C = get_C_point(beat, R)
A = R
if len(beat[A:C]) < 3:
#print ('R and C too close')
return []
positive_segments = monotone_segments(beat[A:C])
prominent_segs = []
heights = []
count = 0
flag = 0
label = np.zeros(len(positive_segme... | The function identifies inflection points in a signal by analyzing zero-crossings of the third derivative (d3z/dt³) within a prominent segment of the beat signal. It filters these crossings using thresholds based on the second derivative (d2z/dt²) relative to a curvature parameter H, ensuring valid inflection points. I... | def get_inflection_points_relaxed(beat, A, R, B_old, fs=500):
most_prominent_seg_index = get_prominent_segment(beat, A, R)
if len(most_prominent_seg_index) == 0:
analyze_segment = []
else:
most_prominent_seg = beat[most_prominent_seg_index]
B_old = B_old - most_prominent_seg_index[0]... |
def get_inflection_points(beat, A, R, fs=500):
most_prominent_seg_index = get_prominent_segment(beat, A, R)
if len(most_prominent_seg_index) == 0:
analyze_segment = []
else:
most_prominent_seg = beat[most_prominent_seg_index]
H = get_dzdt_H(beat, A, R)
zero_crossing_kept = []... | The function determines the B point in a signal by analyzing zero-crossings and local maxima, ensuring it meets minimum distance constraints from R and A. It prioritizes the latest valid zero-crossing or local maximum, defaults to segment indices if needed, and adjusts using relaxed methods if B is too close to R, ensu... | def get_B_point(beat, length, A, R, fs=500, min_RB=int(30 / 2)):
flag = 0
zero_crossing, most_prom_seg_ind = get_inflection_points(beat, A, R, fs)
if not flag:
# C = get_C_point(beat, R)
local_max = get_local_max(beat, A, R, most_prom_seg_ind, fs)
if zero_crossing.size and local_max.... |
def diffusion_schedule(self, diffusion_times):
# diffusion times -> angles
start_angle = tf.acos(max_signal_rate)
end_angle = tf.acos(min_signal_rate)
diffusion_angles = start_angle + diffusion_times * (end_angle - start_angle)
# angles -> signal and noise rates
signal_... | This code evaluates a model by encoding input images into latent representations, adding noise via a diffusion process, and using a denoising network to reconstruct latents and noise. It computes losses for both components, updates metrics, and generates images for evaluation. The process involves diffusion scheduling,... | def test_step(self, images):
latents = self.encoder(images)
#latents = self.normalizer(latents, training=False)
latents = self.quantize(latents)
# normalize images to have standard deviation of 1, like the noises
noises = tf.random.normal(shape=(batch_size, latent_height, latent... |
def normalize(prop, obj):
# list of dict
key = prop_key[prop]
if obj is None:
return []
elif isinstance(obj, (string_type, dict)):
return [dict_box(obj, key)]
elif isinstance(obj, list):
return [dict_box(o, key) for o in obj]
assert False, "unexpected %s data type" % key
def merge_leaf(prop, a, b):
key =... | This function recursively flattens nested data structures by merging and normalizing values, handling lists and dictionaries. It processes keys in `prop_key`, ensuring entities have zero or one list, and yields flattened results while preserving or merging existing data in `base` through recursive calls. | def flatten(prop, data, base={}):
for vn in normalize(prop, data):
cur = {k:v for k,v in base.items() if k != prop}
if prop in base:
cur[prop] = merge_leaf(base[prop], vn)
else:
cur[prop] = merge_dict(data, {})
vars = []
for p in prop_key:
if p in vn:
vs = normalize(p, vn[p])
if isinstanc... |
def gen_nos(self):
num_list = []
for i in range(g.nos_k):
num_list.append(random.randint(1, g.max_n))
return num_list
def gen_aim(self):
num_list = utils.copy_list(g.nos)
# shuffle nos
lt = utils.shuffle(num_list)
# generate answer
buff = ""
... | This method initializes a game state by generating numbers and a target, copying lists, disabling specific buttons, setting the game state to 1, initializing mouse controls, starting an animation, and resetting the scored flag to False. | def new1(self):
g.nos = self.gen_nos()
g.aim = self.gen_aim()
g.top = utils.copy_list(g.nos)
g.buffr = []
buttons.off(['plus', 'times', 'equals'])
buttons.off('back')
g.state = 1
self.mouse_init()
self.anim_start()
self.scored = False |
def mouse_init(self):
self.mouse_ind = 0 # 1st number
if g.state == 2:
self.mouse_ind = 1 # plus
if len(g.top) == 0:
self.mouse_ind = 3 # equals
self.mouse_set()
def mouse_right1(self): # used for state 1
self.mouse_ind += 1
if self.mou... | This code handles a right mouse click event by checking the current state. If the mouse hasn't been initialized, it calls mouse_init(). Depending on the global state (1 or 2), it delegates to mouse_right1() or mouse_right2() methods respectively, enabling context-sensitive right-click behavior in a GUI application. | def mouse_right(self):
if self.mouse_ind is None:
self.mouse_init()
return
if g.state == 1:
self.mouse_right1()
return
if g.state == 2:
self.mouse_right2() |
def mouse_init(self):
self.mouse_ind = 0 # 1st number
if g.state == 2:
self.mouse_ind = 1 # plus
if len(g.top) == 0:
self.mouse_ind = 3 # equals
self.mouse_set()
def mouse_left1(self): # used for state 1
self.mouse_ind -= 1
if self.mous... | This method handles left mouse click events by checking the current state. If uninitialized, it calls `mouse_init()` to set up the mouse. Depending on the global state (`g.state`), it delegates to either `mouse_left1()` for state 1 or `mouse_left2()` for state 2, enabling context-specific mouse interaction logic. | def mouse_left(self):
if self.mouse_ind is None:
self.mouse_init()
return
if g.state == 1:
self.mouse_left1()
return
if g.state == 2:
self.mouse_left2() |
def calc(self):
a = []
for i in range(len(g.buffr)):
if g.buffr[i] == 'times':
ind = len(a) - 1
a[ind] *= g.buffr[i + 1]
g.buffr[i + 1] = 'ignore'
elif g.buffr[i] == 'ignore':
pass
elif g.buffr[i] != 'plu... | This function handles button press logic in a calculator interface. It processes 'equals' by performing calculations, disabling operation buttons, and resetting state if incomplete. 'Back' resets the interface, while 'new'/'green' triggers a new operation. Other buttons append input to a buffer, disable operation butto... | def do_button(self, button):
if button == 'equals':
self.calc()
buttons.off(['plus', 'times', 'equals'])
if not self.complete():
g.state = 1
self.mouse_init()
elif button == 'back':
self.reset()
elif button in ['new'... |
def do_button(self, button):
if button == 'equals':
self.calc()
buttons.off(['plus', 'times', 'equals'])
if not self.complete():
g.state = 1
self.mouse_init()
elif button == 'back':
self.reset()
elif button in ['new'... | This code handles key press events in a game or application, triggering actions like button interactions, mouse movements, state transitions, and feature toggles based on the pressed key. It checks the key against predefined groups (CROSS, UP, DOWN, etc.) and executes corresponding methods such as do_button, mouse_left... | def do_key(self, key):
if key in g.CROSS:
bu = buttons.check()
if bu != '':
self.do_button(bu)
return
if g.state == 1:
self.check_numbers()
return
if key in g.UP:
if self.back_button.mouse_on():
... |
def _conv_bn_relu(ip, filters, kernel_size=(3, 3), strides=(1, 1),
padding='same', bias=False, activation=True):
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
x = _conv_block(ip, filters, kernel_size, strides, padding, bias)
x = BatchNormalization(axis=channel_axi... | Your return The code defines a Keras model for the Octave ResNet architecture, which uses octave convolution blocks to process high- and low-frequency image features separately. It allows customization of network depth (via `layers`), input shape, pre-trained weights, and filter allocation ratios (`alpha`). The model i... | def OctaveResNet(layers,
include_top=True,
weights=None,
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
alpha=0.5,
expansion=1,
initial_filters=64,
... |
def createButton(buttonFrame, dspl_catg):
i = 1
for x, y in categoriesNames.items():
if(i%5 == 0):
frm_temp.pack()
frm_temp = tk.Frame(master=buttonFrame, borderwidth=5)
elif (i == 1):
frm_temp = tk.Frame(master=buttonFrame, borderwidth=5)
#create butt... | This code creates a Tkinter GUI window to display and manage transaction details (date, description, person, cost) with category selection. It includes buttons for adding new categories, saving as 'NONE', auto-adding, quitting, adding comments, and proceeding to the next item. Global variables track progress, and the i... | def createWindow(date, desc, debit, person, catg):
global totalItems
global curIndexItems
global curCat
# Establish window and Vars
root = tk.Tk()
root.title('CitiBank Helper')
root.geometry('+1000+300')
curCat = catg
curIndexItems = curIndexItems + 1
# Frames
frm_folder =... |
def items(data, values):
j = 1
i = 1
while(i < values):
data[6][i] = description(data[2][i])
data[6][i] = credit(data[3][i], data[6][i])
if(data[6][i] == 'NONE'):
j = j + 1
i = i+1
return j
def description(desc):
count = 0
catg = 'NONE'
for x, y i... | The function processes input data by loading category dictionaries from files, iterates through data items to generate descriptions and credits, updates global variables (curCat, curNote, totalItems), handles 'NONE' cases with window creation, and waits for user confirmation before returning modified data. | def fileLoop(data):
global curCat
global curNote
global totalItems
values = len(data[0])
i = 1
if(data[7][0] == True):
skip = True
data[7][0] = 'NONE'
else:
skip = False
data[7][0] = 'NONE'
# Load dictionary
f = open("diction.txt", "r")
for line i... |
def get_templated(self) -> Optional[ResourceRequirements]:
"""Returns the resource limits specified in the StatefulSet template."""
statefulset = self.client.get(
StatefulSet, name=self.statefulset_name, namespace=self.namespace
)
podspec_tpl = self._get_container(
... | The main task of the code is to determine if a resource patch has been successfully applied to a Kubernetes pod. It checks if the requested resources match the actual resources in the pod and if the patch is active. The function logs resource details and returns a boolean indicating whether both the patch is applied an... | def is_ready(self, pod_name, resource_reqs: ResourceRequirements):
"""Reports if the resource patch has been applied and is in effect.
Returns:
bool: A boolean indicating if the service patch has been applied and is in effect.
"""
logger.info(
"reqs=%s, templated... |
def determine_action(usv_pos, platypus_pos, turtle_pos, crocodile_pos, platypus_encircled, turtle_encircled):
if random.random() < 0.2:
return random.choice([Action.F, Action.L, Action.B, Action.R]), None, None
def calculate_distance(pos1, pos2):
return abs(pos1[0] - pos2[0]) + abs(pos... | This code simulates a game where an agent navigates a grid to encircle targets P and T within a time limit. It initializes game states, iteratively determines actions (movement/encirclement), updates the state, and records action history. The loop ends when both P and T are encircled or the time limit is exceeded. Fina... | def main():
game_state = GameState(
start_pos = (0, 0),
usv_dims = (1, 1),
P = (45, 45),
T = (10, 10),
C = (30, 30),
grid_length = 1,
time_limit = 200,
move_time = 1,
circle_time = 1
)
state = State(
pos=game_state.start_pos,
... |
def a_star_search(game_state: GameState, start_state: State, target: tuple):
def heuristic(pos, target):
return abs(pos[0] - target[0]) + abs(pos[1] - target[1])
def croc_obstacles (game_state: GameState):
# 10m euclidean radius circle around crocodile
obstacles = []
for i in range... | The code's main task is to navigate a drone to encircle a platypus and turtle while avoiding a crocodile's 10m radius obstacle. It uses A* search to find paths to target points near each animal, prioritizing the closest one first. After reaching a target, the drone encircles the animal, updates the state, and repeats t... | def main():
game_state = GameState(
start_pos = (0, 0),
usv_dims = (1, 1),
# case 1
# P = (0, 10),
# T = (10, 0),
# C = (15, 15),
# case 2
# P = (0, 30),
# T = (15, 15),
# C = (0, 15),
# case 3
# P = (39, 39),
... |
def check_winner(self, player):
for row in self.board:
if all(cell == player for cell in row):
return True
for col in range(3):
if all(row[col] == player for row in self.board):
return True
if all(self.board[i][i] == player for i in range... | This function handles a player's move in a Tic-Tac-Toe game by placing 'X' on the board if the cell is empty, checking for a win/draw, and switching to AI's 'O' turn if the game continues. | def on_click(self, row, col):
if self.board[row][col] == ' ' and self.current_player == 'X':
self.board[row][col] = self.current_player
self.buttons[row][col].config(text=self.current_player)
if self.check_winner(self.current_player):
messagebox.showinfo("Game... |
def get_adc_state(self):
adcState = VehicleState()
adcState.time = self.sim_time
adcState.speed = self.adc.state.speed
adcState.position = self.sim.map_to_gps(self.adc.state.transform)
adcState.attitude = [self.adc.state.rotation.x, self.adc.state.rotation.y, self.adc.state.rotat... | The code executes lateral and longitudinal control to determine steering and throttle values based on the current way point, speed, and yaw. It applies these controls, checks for lane change requirements, toggles the driving plan if needed, and returns the updated simulation state. | def run_control(self, curr_waypt):
sim_state = self.get_adc_state()
speed = sim_state.speed
yaw = np.radians(sim_state.position[5])
last_steering = self.ctrl.steering
s_2 = time.time()
steering = self.lateral_control(curr_waypt, speed, yaw)
throttle = self.longit... |
def try_load_or_process(filename, processor_fn, function_arg):
load_fn = None
save_fn = None
if filename.endswith("json"):
load_fn = load_json
save_fn = save_json
else:
load_fn = load_bin
save_fn = save_bin
if os.path.exists(filename):
print("Loading " + filen... | The code retrieves and analyzes Twitter follower data for a target account. It fetches follower IDs, extracts user profiles, categorizes accounts by creation date ranges, and summarizes follower counts and friend counts per age group. Results are saved as JSON files and returned as formatted text with statistics on fol... | def get_follower_data(target):
print("Processing target: " + target)
# Get a list of Twitter ids for followers of target account and save it
filename = target + "_follower_ids.json"
follower_ids = try_load_or_process(filename, get_follower_ids, target)
# Fetch Twitter User objects from each Twitter id fou... |
def get_rnames_and_rseq_fragments_from_bowtie_output(fn):
"""
From a bowtie output tsv file, return the reference (read) sequence
and strand as a dictionary, with the reference name as key.
That means duplicate reference names will be collapsed into one.
:param fn: string
path to the bowti... | The main task of the code is to process Bowtie alignment outputs (TSV/SAM format) to extract and analyze sequence fragments, generate chimeric target candidates, and compile metrics. It parses input files, maps sequences to identifiers, filters by minimum length, writes unique candidate sequences to an output file, and... | def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--bowtie_align",
required=True,
)
parser.add_argument(
"--fa_file",
required=True,
)
parser.add_argument(
"--out_file",
required=True,
)
parser.add_argument(
"--m... |
def parse_cutadapt_file(report, paired_end):
#############################
#print("parse_cutadapt_file report:", report)
if os.path.getsize(report) == 0:
return
old_cutadapt = get_cutadapt_version(report) <= 8
if paired_end:
if old_cutadapt:
return parse_old_cutadapt_file... | The function aggregates and organizes processing metrics from sequencing data analysis tools (Cutadapt, STAR, etc.) into a structured DataFrame. It parses input files to extract statistics like read counts, adapter trimming efficiency, alignment rates, and unique sequence identification, compiling them into a single or... | def generate_metrics(
cutadapt1_metrics, cutadapt2_metrics, uncollapsed_fasta, collapsed_fasta,
mir_bowtie_output,
extract_candidate_metrics, candidate_fa, star_genome_metrics,
rmdup_metrics):
"""
"""
metrics = OrderedDict()
cutadapt_round1_metrics_dict = parse_cutadapt_file(... |
def sse(actual, predicted):
'''
sum of squared error
'''
return (residuals(actual, predicted) ** 2).sum()
def ess(actual, predicted):
'''
explained sum of squared error
'''
return ((predicted - actual.mean()) ** 2).sum()
def tss(actual):
'''
total sum of squared error
'''
... | The code computes common regression evaluation metrics—SSE, ESS, TSS, MSE, RMSE, and R²—using actual and predicted values, then returns them as a pandas Series for analysis. | def regression_errors(actual, predicted):
return pd.Series({
'sse': sse(actual, predicted),
'ess': ess(actual, predicted),
'tss': tss(actual),
'mse': mse(actual, predicted),
'rmse': rmse(actual, predicted),
'r2': r2_score(actual, predicted),
}) |
def sse(actual, predicted):
'''
sum of squared error
'''
return (residuals(actual, predicted) ** 2).sum()
def mse(actual, predicted):
'''
mean squared error
'''
n = actual.shape[0]
return sse(actual, predicted) / n
def rmse(actual, predicted):
'''
root mean squared error
... | The code calculates the sum of squared errors (SSE), mean squared error (MSE), and root mean squared error (RMSE) between actual values and their mean as a baseline prediction, returning these metrics in a dictionary. | def baseline_mean_errors(actual):
predicted = actual.mean()
return {
'sse': sse(actual, predicted),
'mse': mse(actual, predicted),
'rmse': rmse(actual, predicted),
} |
def simplified(self, sentence):
self.pos_seq_simplified=[]
for word in sentence:
if word in self.word_dict.keys():
arr = self.word_pos_matrix[self.word_dict[word],:]
pos = np.where(arr == np.amax(arr))[0][-1]
self.pos_seq_simplified.app... | The code defines a method `solve` that selects and executes a text processing algorithm based on the input `model` parameter. If `model` is "Simple", it applies a simplified approach; "Complex" triggers a Markov Chain Monte Carlo method; "HMM" uses a Hidden Markov Model with Viterbi decoding. Unknown models raise an er... | def solve(self, model, sentence):
if model == "Simple":
return self.simplified(sentence)
elif model == "Complex":
return self.complex_mcmc(sentence)
elif model == "HMM":
return self.hmm_viterbi(sentence)
else:
print("Unknown algo!") |
def get_gtdbtk_classifications(self,
ar53_metadata_file,
bac120_metadata_file,
gtdbtk_output_dir,
gtdbtk_prefix):
"""Get GTDB-Tk classification files."""
gtdbtk_ar... | The main task of the code is to translate GTDB-Tk classifications into NCBI taxonomy using majority vote. It processes GTDB-Tk output, parses archaeal/bacterial classifications and phylogenetic trees, extracts NCBI taxonomy data, identifies GTDB species clusters, and assigns NCBI classifications to genomes via majority... | def run(self,
gtdbtk_output_dir,
ar53_metadata_file,
bac120_metadata_file,
gtdbtk_prefix,
output_file):
"""Translate GTDB to NCBI classification via majority vote."""
# create output file directory if required
output_dir = os.path.dirn... |
def ends(self, s):
"""ends(s) is TRUE <=> k0,...k ends with the string s."""
length = len(s)
if s[length - 1] != self.b[self.k]: # tiny speed-up
return 0
if length > (self.k - self.k0 + 1):
return 0
if self.b[self.k-length+1:self.k+1] != s:
ret... | This function performs step 1a and 1b of the Porter stemming algorithm, removing common suffixes like plurals (-s, -es) and past tense/gerund endings (-ed, -ing) to reduce words to their stems. It modifies the word by checking specific endings, adjusting the string length, and applying transformations like replacing 'i... | def step1ab(self):
"""step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> d... |
def m(self):
"""
m() measures the number of consonant sequences between k0 and j.
if c is a consonant sequence and v a vowel sequence, and <..>
indicates arbitrary presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvc... | The main task of `step5` is to remove a final `-e` if the measure `m()` > 1, or if `m()` = 1 and the preceding character isn't in a CVC pattern. It also replaces `-ll` with `-l` if `m()` > 1, ensuring proper stemming by adjusting suffixes based on morphological rules. | def step5(self):
"""step5() removes a final -e if m() > 1, and changes -ll to -l if
m() > 1.
"""
self.j = self.k
if self.b[self.k] == 'e':
a = self.m()
if a > 1 or (a == 1 and not self.cvc(self.k-1)):
self.k = self.k - 1
if self.b[s... |
def step1ab(self):
"""step1ab() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> d... | The code implements a stemming algorithm (e.g., Porter stemmer) to reduce words to their root forms. It processes a substring from index `i` to `j` in the input string `p`, applying sequential steps (step1ab, step1c, step2–step5) to remove suffixes and morphological affixes. If the string length is ≤2, it returns the o... | def stem(self, p, i=0, j=None):
"""In stem(p,i,j), p is a char pointer, and the string to be stemmed
is from p[i] to p[j] inclusive. Typically i is zero and j is the
offset to the last character of a string, (p[j+1] == '\0'). The
stemmer adjusts the characters p[i] ... p[j] and returns t... |
def tree(label, branches=[]):
"""Construct a tree with the given label value and a list of branches."""
for branch in branches:
assert is_tree(branch), 'branches must be trees'
return [label] + list(branches)
def label(tree):
"""Return the label value of a tree."""
return tree[0]
def branche... | The function `copy_tree(t)` creates a deep copy of the input tree `t` by recursively duplicating its structure. It constructs a new tree with the same root label as `t` and recursively copies each of `t`'s branches using `copy_tree(b)`. This ensures modifications to the original tree do not affect the copied tree, pres... | def copy_tree(t):
"""Returns a copy of t. Only for testing purposes.
>>> t = tree(5)
>>> copy = copy_tree(t)
>>> t = tree(6)
>>> print_tree(copy)
5
"""
return tree(label(t), [copy_tree(b) for b in branches(t)]) |
def copy_tree(t):
"""Returns a copy of t. Only for testing purposes.
>>> t = tree(5)
>>> copy = copy_tree(t)
>>> t = tree(6)
>>> print_tree(copy)
5
"""
return tree(label(t), [copy_tree(b) for b in branches(t)])
def branches(tree):
"""Return the list of branches of the given tree."""... | The function replaces all leaf nodes with the value "loki" in the given tree with the specified replacement value, returning a new tree without modifying the original. It recursively traverses the tree, checking each leaf node. If a leaf's value is "loki," it replaces it with the provided replacement. Non-leaf nodes ar... | def replace_loki_at_leaf(t, lokis_replacement):
"""Returns a new tree where every leaf value equal to "loki" has
been replaced with lokis_replacement.
>>> yggdrasil = tree('odin',
... [tree('balder',
... [tree('loki'),
... tree('fr... |
def _init_centroids(self) -> None:
self._init_centroids_randomly()
self.centroids_per_try.append(self.centroids)
def _single_pass(self) -> None:
for iteration_num in range(self.iterations):
if (self.prev_centroids is not None and np.array_equal(self.prev_centroids, self.centroids)):
... | The code performs multiple clustering attempts by initializing centroids, running a single-pass clustering algorithm, calculating cluster tightness for each attempt, and selecting the best result after all iterations. | def cluster(self) -> None:
for try_number in range(self.tries):
print('Try number: ', try_number)
self._init_centroids()
start_time = time.time()
self._single_pass()
print('Try took', time.time()-start_time, 'seconds')
self._compute_tightne... |
def remake_build_dir() -> None:
"""Remakes the build directory."""
if BUILD_PATH.is_dir():
logger.info(f"Removing the build directory.")
shutil.rmtree(BUILD_PATH, ignore_errors=True)
elif BUILD_PATH.is_file():
logger.error(f"{BUILD_PATH} is a file and deleting it.")
os.remove... | The main task of the code is to generate Nginx Dockerfiles by remaking a build directory, fetching repository structure and templates, modifying them, creating a file tree, retrieving entry points, and executing an update process. The function logs success upon completion and returns 0 to indicate successful execution. | def main(*args, **options) -> int:
remake_build_dir()
repo_structure = fetch_repot_structure()
fetch_nginx_executable()
fetch_nginx_templates(repo_structure)
modify_templates(repo_structure)
create_tree(repo_structure)
fetch_entrypoints(repo_structure)
run_update()
logger.success("Ng... |
def prog_opts():
parser = argparse.ArgumentParser(description='arg parser')
parser.add_argument('--config', type=str, action='store')
parser.add_argument('--port', dest='port', action='store', type=int)
parser.add_argument('--cam_dir', dest='cam_dir', action='store')
parser.add_argument('--cam_flip_h', dest='cam_f... | The main task of the code is to initialize and manage concurrent threads for camera data processing, state monitoring, and SSDV delivery using configuration parameters stored in GLOB. It creates directories, launches threads for CameraLoop, StateLoop, and SSDV_DeliverLoop, and handles graceful shutdown via KeyboardInte... | def main():
global THREADS_RUN
global GLOB
GLOB = prog_opts()
pprint(GLOB)
GLOB['cam_dir'] = GLOB['cam_dir'].replace('.', curdir())
if not os.path.isdir(GLOB['cam_dir']):
os.makedirs(GLOB['cam_dir'])
session_dir = next_path(GLOB['cam_dir'])
cam_process = None
state_process = None
try:
cam_process = thre... |
def gen_groups():
"""Generate and return list with 10 groups with random name"""
group_names_list_tuples = []
group_list = []
for _ in range(10):
name = ''
for i in range(4):
if i == 2:
name += '_'
name += random.choice(string.ascii_lowercase)
... | The main task of the code is to generate and insert test data into a database, including creating groups, students, courses, and establishing many-to-many relationships between entities through a series of data generation and insertion functions. | def insert_test_data():
groups_list, groups_for_sql = gen_groups()
students = generate_students(groups_list)
groups_insert(groups_for_sql)
students_insert(students)
courses_list = gen_courses()
course_insert(courses_list)
create_many_to_many() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.