dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def is_upper_diff(text: str) -> bool:
"""Check if some words are all caps while others aren't.
Args:
text (str): Text to parse through and check if some words are capitalized while others aren't
Returns:
bool: True if some words all caps while others aren't, False otherwise
"""
current_word = ""
upper_word... | The code processes text to compute valence scores by replacing emojis, tokenizing, handling negations/modifiers, and aggregating sentiment values. It strips punctuation, converts to lowercase, checks for sentiment lexicon matches, adjusts for negations via 'but_check', and returns a valence score dictionary. | def score(self, text: str) -> dict:
"""Score text.
Args:
text (str): Text to score
Returns:
dict: Valence scores
"""
text_no_emoji = ""
previous_char = " "
for char in text:
if char in emoji_dict:
if previous_char != " ":
text_no_emoji += " "
char = emoji_dict[char]
text_no_emo... |
def _map_one_digit_number(number: str) -> str:
return DIGITS[number]
def _map_two_digit_number(number: str) -> str:
if number[0] == ZERO:
return _map_one_digit_number(number[1])
if number[0] == ONE:
return TEENS[number]
result = TENS[number[0]]
if number[1] == ZERO:
re... | This function converts a numeric triplet string to its textual representation by delegating to helper functions based on the input's length: one-digit, two-digit, or three-digit. It returns the mapped text or an empty string if the input length doesn't match any case. | def _map_number_to_text(triplet: str) -> str:
length = len(triplet)
if length == ONE_DIGIT_NUMBER_LENGTH:
return _map_one_digit_number(triplet[0])
elif length == TWO_DIGIT_NUMBER_LENGTH:
return _map_two_digit_number(triplet[:2])
elif length == THREE_DIGIT_NUMBER_LENGTH:
return _m... |
def _validate_input(number: float) -> None:
if number > MAX_NUMBER or number <= MIN_NUMBER:
raise ValueError('Given value is out of allowed range')
_, cent_part = str(number).split(NUMBER_SEPARATOR)
if len(cent_part) > CENT_PART_MAX_LENGTH:
raise ValueError('Cent part must be less than... | The code converts a numeric dollar amount (including cents) into its English textual representation, such as transforming "123.45" into "one hundred twenty-three dollars and forty-five cents". It separates dollars and cents, processes each into words, then combines them into a formatted string. | def dollars_to_english_text(number: Union[float, int]) -> str:
"""
Takes a number of dollars and cents,
and represents it as an English text.
"""
number = float(number)
_validate_input(number)
dollar_part, cent_part = _separate_number_parts(number)
dollars_number = _get_dollars_n... |
def dealCards(self):
for i in range(2):
for player in self.players:
player.append(self.deck.pop())
self.board = [list(player) for player in self.players]
self.board[0][1] = '🂠'
def getBoard(self):
return self.board
def calculateScore(self, player):
s... | This code simulates a Blackjack game where players take turns hitting or standing based on their hand value. The dealer follows a fixed strategy (hitting until reaching 17). The game checks for busts, ends rounds, and allows replay. It validates player counts, manages card dealing, and handles game flow between players... | def play_game(self, players, againstDealer = True):
# Check if the number of players is valid
if len(players) != len(self.players):
raise ValueError("Invalid number of players.")
self.dealCards()
print("Initial Board: ", self.getBoard())
while True:
... |
def resetGame(self):
self.deck = self.initalizeDeck(self.decksNum)
self.shuffleDeck()
self.board = []
self.turn = 1
self.winner = None
self.moves = 0
for i in range(len(self.players)):
self.players[i] = []
def dealCards(self):
for i in range(2)... | This function simulates multiple rounds of a card game with automated players, tracking each player's wins and ties across specified games. It validates player inputs, executes game rounds, handles player and dealer actions, determines winners, and returns a list of win/tie counts for each player. | def multiGame(self, players, games, printOutput = True, againstDealer = True):
# List will be setup as,
# [(dealer wins, dealer ties), (player1 wins, player1 ties), ...]
wins = []
for i in range(len(players)):
if players[i].__class__.__name__ == "ManualPlayer":
... |
def removeDuplicateNodes(self, structure):
newStructure = {'nodes': [],
'speciality': structure['speciality']}
for nodeIndex in range(len(structure['nodes']) - 1):
if structure['nodes'][nodeIndex] != structure['nodes'][nodeIndex + 1]:
newStructure['no... | This function processes geometric structures by modifying their nodes through rotation, simplification, and gap-filling, then renders them as closed paths on a Cairo surface, applying a blue outline and saving the result as "AnglesRule.png" | def redrawForDegreesStructures(self):
pat = cairo.SolidPattern(1, 1, 1, 1)
self.ctx.set_source(pat)
self.ctx.fill()
# rotate odd angles
rotatedNode = {'x': -1, 'y': -1}
originNode = {'x': 0, 'y': 0}
for structure in self.structuresArray:
tempStructur... |
def calculateStructureCentroid(self, nodes):
xCoordinates = [vertex['x'] for vertex in nodes]
yCoordinates = [vertex['y'] for vertex in nodes]
x = sum(xCoordinates) / len(nodes)
y = sum(yCoordinates) / len(nodes)
return {'x': x, 'y': y}
def angleOfLongestDistanceBetweenNodes(self... | This code rotates each structure around its centroid based on the longest node distance, redraws the rotated nodes using Cairo, applies a color, and saves the transformed structures as "rotated.png". It calculates rotation angles, updates node positions, and renders paths for visualization. | def drawRotatedStructures(self):
pat = cairo.SolidPattern(1, 1, 1, 1)
self.ctx.set_source(pat)
self.ctx.fill()
# rotate all nodes
rotatedNode = {'x': -1, 'y': -1}
for structure in self.structuresArray:
originNode = self.calculateStructureCentroid(
... |
def roadsToGridCoorinates(self):
roads = []
for newRoad in self.roadsArray:
road = []
for node in newRoad:
x = round(node['x'] / self.pixelsPerGridSquare)
y = round(node['y'] / self.pixelsPerGridSquare)
road.append({'x': x, 'y': y})... | The code generates a dungeon-like image by combining assets (floors, walls, pillars, etc.) based on predefined grid coordinates. It loads textures, composites floors with structure masks, generates walls via recursive area division, places pillars, and saves the final image. | def drawForDungeonified(self):
Image.MAX_IMAGE_PIXELS = None
self.assetSize = 200.0
roads = []
structures = []
roads = self.roadsToGridCoorinates()
structures = self.structuresToGridCoordinatesAndReorder()
# Add first node to end so last wall is added.
#... |
def prompt_user():
print("-------------LOGIN/REGISTER-------------")
while True:
try:
# user options
print("1. Login")
print("2. Register")
userOption = int(input("Enter: "))
except ValueError:
print("Your input for Options is wrong. P... | The main task of the code is to prompt the user for a client ID, load the corresponding user data, and display available options to the user. It handles user interaction by retrieving input, fetching user information, and presenting choices for further actions. | def main():
#userLogin()
#createTask(userID)
#task = createTask()
clientId = prompt_user()
client = load_user(clientId)
# print("-------LOADED USER---------")
# print(client)
# print("---------------------------")
prompt_user_options(client) |
def merge_compute_minrun(n):
"""Returns the minimum length of a run from 23 - 64 so that
the len(array)/minrun is less than or equal to a power of 2."""
r = 0
while n >= 64:
r |= n & 1
n >>= 1
return n + r
def count_run(lst, s_run):
"""Count the length of one run, returns startin... | The code implements a **Timsort** algorithm, a hybrid stable sorting method combining merge sort and insertion sort. It processes the input list by identifying and extending "runs" (sequences of consecutive elements), ensuring each run meets a minimum length (`min_run`) using binary insertion sort. These runs are store... | def sort(lst):
"""The main function"""
# Starting index
s = 0
# Ending index
e = len(lst) - 1
# The stack
stack = []
# Compute min_run using size of lst
min_run = merge_compute_minrun(len(lst))
while s <= e:
# Find a run, return [start, end, bool, length]
ru... |
def calc_R_Patch(n):
#n_flatten = n.reshape(9,1,3) for rotation
n_flatten = n.reshape(9,3)
R = np.zeros((9,3,3), dtype=float)
for i in range(9):
r = calc_R(n_flatten[i,:])
#r = Rotation.align_vectors(n_map.reshape(1,3), n_flatten[i,:])
#R[i,:] = r[0].as_matrix()
R[i,... | The function G_N_patch iteratively computes the orientation of a local image patch (n_patch) by minimizing an error function (g) through Newton-like updates with a dogleg method. It initializes with a given guess, adjusts the patch's orientation (uvr_patch) and rotation matrices (R_patch), enforces constraints on uvr m... | def G_N_patch(I_patch, initial_guess, patch_G2 = 0):
err = 0
iter = 0
#other init guess
# n1 = np.sqrt(0.3)
# n2 = np.sqrt(0.3)
# n1 = np.random.random_sample() - 0.5
# n2 = np.random.random_sample() - 0.5
# n_0 = np.array([n1,n2, np.sqrt(1 - (n1**2 + n2**2))])
# 9 random initial g... |
def read_data_from_csv():
data = pd.read_csv("historical_data.csv", header=None)
data.columns = ["Date", "USDC", "FTM", "WETH"]
data = data.set_index("Date")
return data
def simulate_portfolio_allocations(data):
portfolio_allocations = []
for usdc_weight in np.linspace(0, 1, 21):
for ftm... | This code reads financial data from a CSV, simulates various portfolio allocations, visualizes them, identifies the most efficient portfolios using a risk/reward ratio, and prints the top allocations with their ratios. The main task is to analyze and optimize portfolio strategies for efficiency. | def main():
data = read_data_from_csv()
portfolio_allocations = simulate_portfolio_allocations(data)
plot_portfolio_allocations(portfolio_allocations)
efficient_allocations = identify_efficient_portfolios(portfolio_allocations)
print("Most Efficient Portfolio Allocations:")
for allocation in eff... |
def _404(self):
self.template = "404.html"
return self.render()
def error(self, text):
self.errors.append(text)
def assignDefaultArgs(self):
self.viewArg("PATH", Core.PATH())
self.viewArg("PARAMS", Core.PARAMS())
self.viewArg("CONFIG", Core.CONFIG())
self.viewArg("USER", Core.USER())
def render(self):
s... | This method handles request routing by determining an action based on parameters, executing the corresponding method if it exists, catching and logging errors, assigning default arguments, and rendering the view. | def run(self):
self.template = ""
self.view = View()
self.errors = []
action = Core.PARAMS()[1] if len(Core.PARAMS()) > 1 else 'index'
if not getattr(self, action, None):
return self._404()
try:
getattr(self, action)()
except Exception as e:
self.error('An error has occurred, please contact a... |
def check_place_in_col(i, j, right_queens):
for queen in right_queens:
if j == queen[1]:
return False
return True
def initboard(N, initQueen, need_placed_queens):
board = []
for i in range(N):
subboard = []
for j in range(N):
subboard.append(0)
boa... | The code solves the N-Queens problem using a modified A* algorithm. It initializes a chessboard with pre-placed queens and iteratively places remaining queens by exploring states in a priority queue, prioritized by cost (g) plus heuristic (h). The heuristic estimates the number of attacking pairs, aiming for zero. The ... | def solveNQueen():
right_placed_queens = []
need_placed_queens = []
visited_board = [] # if visited, ignore
for queen in initQueen:
right_placed_queens.append(queen)
for i in range(N):
for j in range(N):
if (i, j) not in initQueen and check_place_in_col(i, j, initQ... |
def create_output_directory(output_dir):
if not os.path.exists(output_dir):
os.mkdir(output_dir)
if not os.path.exists(os.path.join(output_dir, "cryptic_vcfs")):
os.mkdir(os.path.join(output_dir, "cryptic_vcfs"))
if not os.path.exists(os.path.join(output_dir, "cryptic_reads")):
os.mk... | The main task of the code is to identify cryptic SARS-CoV-2 lineages in wastewater samples by analyzing mutation data from BAM/VCF files against a predefined database. It processes metadata, reads genomic references, iterates through samples, and detects valid mutation combinations. Results are saved as CSV files in an... | def main():
'''
main function
'''
# Tested command: python crykey_wastewater.py -i test_input_metadata.tsv -r /home/Users/yl181/wastewater/SARS-CoV-2-reference.fasta -d /home/Users/yl181/wastewater/quaid/quarc_dbs_01102023_incl_recombinant
parser = argparse.ArgumentParser(description="Search fo... |
def group_tweets_by_state(tweets):
"""Return a dictionary that aggregates tweets by their nearest state center.
The keys of the returned dictionary are state names, and the values are
lists of tweets that appear closer to that state center than any other.
tweets -- a sequence of tweet abstract data ty... | The code generates a sentiment map visualizing the emotional tone of tweets related to a specified term, by grouping tweets by U.S. states, calculating average sentiment scores per state, and plotting both state-level averages and individual tweet locations with color-coded sentiment indicators. | def draw_map_for_term(term='my job'):
"""
Draw the sentiment map corresponding to the tweets that match term.
term -- a word or phrase to filter the tweets by.
To visualize tweets containing the word "obama":
# python3 trends.py obama
Some term suggestions:
New York, Texas, sandwich, my ... |
def compute_top_stats_year(info, formula, numplayers, year):
"""
Inputs:
info - Baseball data information dictionary
formula - function that takes an info dictionary and a
batting statistics dictionary as input and
computes a compound statistic
... | The code tests functions to compute and display top baseball statistics (e.g., batting averages, on-base percentage, slugging percentage, OPS) for specific years and careers using predefined CSV data formats. It verifies the correctness of statistical calculations and result retrieval by printing top-performing players... | def test_baseball_statistics():
"""
Simple testing code.
"""
#
# Dictionary containing information needed to access baseball statistics
# This information is all tied to the format and contents of the CSV files
#
baseballdatainfo = {"masterfile": "Master_2016.csv", # Name of Master CS... |
def find_table(image):
corners = find_table_corners(image)
# Find the corners
left_corners = sorted(corners, key=lambda x: x[0])[:2]
top_left_corner, bot_left_corner = sorted(left_corners, key=lambda x: x[1])
right_corners = sorted(corners, key=lambda x: x[0])[2:]
top_right_corner, bot_right_c... | The code processes an image by optionally undistorting it, applying a bilateral blur, detecting a table, identifying balls and a cue, and returning the simulated board. It also prints table corner coordinates and displays debug visuals if enabled. | def process_image(image, undistort=False):
if undistort:
h, w = image.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(MTX, DIST, (w, h), 1, (w, h))
dst = cv2.undistort(image, MTX, DIST, None, newcameramtx)
x, y, w, h = roi
dst = dst[y : y + h, x : x + w]
... |
def process_agg_line_struct(self, data, additional_data=None, map_created_objects=None):
reserved = ('__id__', '__instance__', 'model')
line_instance_id = data.get('__instance__', 'anon')
line_model = data.get('model')
if not line_model or line_model not in self.env or line_model not in... | This function processes a line of aggregated data to create objects in a system. It checks the model type, prepares additional data if needed, processes the line structure, and attempts to create an object. If successful, it maps the created object for future reference. If an error occurs, it logs details and raises a ... | def process_aggregated_data_line(self, line, bom_id, map_created_objects=None):
additional_data = None
if line['model'] in ('mrp.bom.line', 'mrp.routing.workcenter'):
additional_data = dict(bom_id=bom_id)
model, create, template_object = self.process_agg_line_struct(line, additional... |
def allowed_models(self):
allowed = {
'mrp.bom.line',
'mrp.routing.workcenter',
'product.product',
'sale.order.line',
}
user_allowed = self.env['konfoo.allowed.model'].search([('company_id', '=', self.env.user.company_id.id)])
for record i... | This function processes aggregated data to create a Bill of Materials (BOM) and its components. It validates each data line against allowed models, logs warnings for missing/invalid entries, and generates BOM lines using `process_aggregated_data_line`. The created BOM and its associated objects are returned. | def process_aggregated_data(self, product_tmpl_id, agg_data, parent=None):
bom = self.env['mrp.bom'].create({
'product_tmpl_id': product_tmpl_id,
})
allowed_models = self.allowed_models()
map_created_objects = dict()
created = list()
for line in agg_data['da... |
def _create_or_update_konfoo_session(self, session_id, session_data, bom_data):
json_session = json.dumps(session_data)
json_bom = json.dumps(bom_data)
session = self.env['konfoo.session'].search([('konfoo_session_id', '=', session_id)], limit=1)
if session:
session.write({
... | The function processes Konfoo sessions by creating/updating session data, extracting BOM metadata, generating or retrieving products, processing aggregated BOM data, updating costs, and creating/updating sale order lines based on product creation status. It ensures session-linked product and BOM data are synchronized w... | def process_konfoo_session(self, ctx, session_key, session_data, bom_data, parent):
logger.info('Creating/updating Konfoo session data: %s', session_key)
session_object = self._create_or_update_konfoo_session(session_key, session_data, bom_data)
line_vals = {}
template_product, product... |
def configure(self):
return KonfooContext(env=self.env)
def fetch_konfoo_data(konfoo_url, session_key):
response = requests.get(urljoin(konfoo_url, '/api/v1/state/{}'.format(session_key)))
if not response:
raise UserError(_('Could not fetch session "{}" from Konfoo backend'.format(session_key)))... | This function creates a sales order line from a session by retrieving a sale order, fetching Konfoo configuration and BOM data via a session key, then processing these to generate the line. It validates the sale order's existence, logs details, and handles errors. The TODO indicates future logic for Konfoo product inde... | def create_so_line_from_session(self, sale_order_id, session_key):
ctx = self.configure()
sale_order = self.env['sale.order'].browse([sale_order_id])
if not sale_order:
raise UserError(_('Could not find "sale.order" with id: {}'.format(sale_order_id)))
logger.info('Sale orde... |
def _create_parser(name: str) -> argparse.ArgumentParser:
return argparse.ArgumentParser(description=name)
def _args_add_data_init(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"-i", "--init-db", help="Initialize database", action="store_true", dest="init_db", default=False
)
def _a... | The main task of the code is to set up and process command-line arguments for a CLI tool, handling commands like "build" (to build a Poetry package) and "data" (for database operations: init, update, roles, domains, info). It defines subparsers, associates help messages, adds argument handlers, parses user inputs, and ... | def main() -> int:
# region create parsers
parser = _create_parser("main")
subparser = parser.add_subparsers(dest="command")
# endregion create parsers
_ = subparser.add_parser(name="build", help="Build the package using Poetry in a custom environment.")
data_subparser = subparser.add_parser(na... |
def generateRandomOptions(self, numberOfOptions):
"""
Generates random groups and caculates their respective score.
"""
groupOptions = []
for _ in range(0, numberOfOptions):
groups = self.generatePermutations()
groupScores = self.scoreGroups(groups)
... | The code's main task is to optimize group configurations across multiple rounds by generating random options, iteratively mutating them through generations, and selecting the best-performing options based on total scores. It breaks early if a group achieves a zero score, updates weights using the best groups, and colle... | def solve(self):
"""
The main function to call.
For each round first a start generation is generated.
This is then mutated until a good total score is achieved or
self.GENERATIONS is reached.
The best option for each round is returned at the end.
"""
round... |
def main_email_to_customer_id_and_devices(email):
try:
user_data = get_userdata_by_email(email)
if user_data:
user_membership = get_membership(user_data)
if user_membership:
return user_membership
except Exception as e:
print(e)
... | The function `get_cri1_license` checks if a user has an active license based on their email. It retrieves user details like customer ID, name, company, and max devices if the license is active, returning a structured dictionary with a `valid_license` flag. If inactive or data is unavailable, it returns default values w... | def get_cri1_license(email: str):
try:
main_user_membership = main_email_to_customer_id_and_devices(email)
if main_user_membership is not None:
if main_user_membership["status"] == "active":
return {
"customer_id": main_user_member... |
def get_all_capturing_moves(self, tile: Tile, piece: Piece,
capturing_vector: Optional[tuple[int, int]] = None) -> list[Move]:
if piece.king:
return self.get_all_capturing_moves_for_king(tile, piece, capturing_vector)
else:
return self.get_all_capt... | The function `get_all_moves` determines all valid moves for a given piece on a tile. It first retrieves all capturing moves; if any exist, it filters them to return only valid ones. If no capturing moves are available, it returns all non-capturing moves instead. This prioritizes capturing moves when possible, ensuring ... | def get_all_moves(self, tile: Tile, piece: Piece) -> list[Move]:
capturing_moves = self.get_all_capturing_moves(tile, piece)
if capturing_moves:
return self.filter_out_capturing_moves(capturing_moves)
return self.get_all_non_capturing_moves(tile, piece) |
def get_all_capturing_moves(self, tile: Tile, piece: Piece,
capturing_vector: Optional[tuple[int, int]] = None) -> list[Move]:
if piece.king:
return self.get_all_capturing_moves_for_king(tile, piece, capturing_vector)
else:
return self.get_all_capt... | The function generates all possible moves for the current player's pieces, prioritizing capturing moves. It checks the current turn to determine active pieces, iterates through each piece to collect capturing and non-capturing moves, and returns filtered capturing moves if available; otherwise, returns non-capturing mo... | def get_all_possible_moves(self) -> list[Move]:
whites = self.board.current_position.whites
blacks = self.board.current_position.blacks
tiles = whites if self.board.current_position.turn == WHITES_TURN else blacks
capturing_moves = []
non_capturing_moves = []
for tile, pi... |
def exposed_setAddress(self, row, place):
self.exposed_writeReg(0x10,[0xE7,row,place,0xE7,0xE7])
self.exposed_writeReg(0x0A,[0xE7,row,place,0xE7,0xE7])
return
def exposed_setColour(self, r1, g1, b1, r2, g2, b2, calibration=True):
pl = pwmlist(r1, g1, b1, r2, g2, b2, calibration)
self.exposed_writePa... | The main task of the code is to configure an address and color settings for a device, then send the configured data. It sets the address using `row` and `place`, defines two color values (RGB pairs), and triggers a send operation. The function acts as a control interface for device configuration and data transmission, ... | def exposed_do(self, row, place, r1, g1, b1, r2, g2, b2):
self.exposed_setAddress(row, place)
self.exposed_setColour(r1, g1, b1, r2, g2, b2)
return self.exposed_send() |
def _filter(self, record, where):
operator = where["symbol"]
column = where["column"]
condition = str(where["condition"])
# get index of column to check
column_index = [x.attribute_name for x in self.columns].index(column)
if operator == "==":
if str(record... | This function filters and sorts data records based on specified conditions. It handles single/multiple `where` clauses recursively, leveraging indexes for efficient lookup. If no conditions are provided, it yields all records. For sorting, it uses `_select_sort`. It supports operators like `==`, `<`, `>`, and `<>` to f... | def _select_filter(self, where=None, order_by=None, direction="asc"):
# if there are no such conditions, simply yield one record at a time
if where is None and order_by is None:
for key in self.data:
yield self.data[key]
return
if order_by is None:
... |
def _filter(self, record, where):
operator = where["symbol"]
column = where["column"]
condition = str(where["condition"])
# get index of column to check
column_index = [x.attribute_name for x in self.columns].index(column)
if operator == "==":
if str(record... | The function `_select_filter` processes data filtering and sorting by applying `where` conditions and `order_by` directives. It uses indices for efficient filtering (e.g., `==`, `<`, `>`) and recursively handles multiple conditions. If no filters exist, it yields records directly. For sorting, it delegates to `_select_... | def _select_filter(self, where=None, order_by=None, direction="desc"):
# if there are no such conditions, simply yield one record at a time
if where is None and order_by is None:
for key in self.data:
yield self.data[key]
return
if order_by is None:
... |
def _select_filter(self, where=None, order_by=None, direction="asc"):
# if there are no such conditions, simply yield one record at a time
if where is None and order_by is None:
for key in self.data:
yield self.data[key]
return
if order_by is None:
... | This function updates specific columns in records that match a given condition. It identifies column indices, filters records using the 'where' clause, removes the filtered records, updates the specified columns with provided values, and reinserts the modified records into the dataset. | def update_record(self, columns_to_be_updated, values_to_be_updated, where=None):
# column_names = [x.attribute_name for x in self.columns]
indices = []
for column in columns_to_be_updated:
indices.append([x.attribute_name for x in self.columns].index(column))
... |
def tuple_hasher(self, record):
hash = hashlib.md5()
for element in record:
hash.update(str(element).encode())
return hash.hexdigest()
def _select_filter(self, where=None, order_by=None, direction="asc"):
# if there are no such conditions, simply yield one record at a time
... | This code performs a SELECT operation on a dataset, supporting filtering (WHERE), grouping (GROUP BY), aggregation (e.g., SUM, COUNT), sorting (ORDER BY), and result formatting. It processes input columns, applies aggregate functions to grouped data, and outputs a PrettyTable with results, handling both simple selectio... | def select(self, columns, aggregates=None, group_by=None, where=None, order_by=None, direction="asc"):
if aggregates is not None:
group_by_columns = {}
order_by_cols = []
for ag in aggregates:
order_by_cols.append(ag[0])
toPrint = []
... |
def _select_filter(self, where=None, order_by=None, direction="desc"):
# if there are no such conditions, simply yield one record at a time
if where is None and order_by is None:
for key in self.data:
yield self.data[key]
return
if order_by is None:
... | This function updates specific columns in records that match a given condition. It identifies column indices, filters records using the 'where' clause, removes the original records, applies new values to specified columns, and reinserts the modified records. | def update_record(self, columns_to_be_updated, values_to_be_updated, where=None):
# column_names = [x.attribute_name for x in self.columns]
indices = []
for column in columns_to_be_updated:
indices.append([x.attribute_name for x in self.columns].index(column))
for record i... |
def tuple_hasher(self, record):
hash = hashlib.md5()
for element in record:
hash.update(str(element).encode())
return hash.hexdigest()
def _select_filter(self, where=None, order_by=None, direction="desc"):
# if there are no such conditions, simply yield one record at a time
... | This function performs a SQL-like SELECT operation with optional aggregation and grouping. It filters records using 'where', applies aggregate functions (e.g., SUM, COUNT) on specified columns, groups results by specified attributes, and returns either filtered records or aggregated values. When aggregates are used, it... | def select(self, columns, aggregates=None, group_by=None, where=None, order_by=None, direction="desc"):
# this is the function were the code lost its structure completely
if aggregates is not None:
order_by_cols = []
for ag in aggregates:
print(ag[0])
... |
def _make_map(self):
"""
Create an empty map.
"""
# Make 2D array filled with zeros
for _ in range(0, self.height // 10 + 1):
row = []
for _ in range(0, self.width // 10 + 1):
row.append(0)
self.map.append(row)
def _generate_pla... | The main task of the code is to initialize the game by randomly generating map components (platforms, ladders, stars), ensuring the player has a path to the top, and organizing these elements into groups for gameplay. The loop guarantees a valid map configuration before finalizing boundaries, references, and star place... | def initialize_game(self):
"""
Initialize the game by calling the methods to make the map, generate
platforms, ladders, and stars randomly, populating the map with our
game components, then creating the groups of those game components.
"""
# Loop to keep generating board ... |
def reset_groups(self, score, lives):
"""
Reset game components. This includes the score, lives, map,
and lists of game component instances.
Args:
score: An int that represents player's current score.
lives: An int that represents player's current number of lives... | This method handles button click events in a game. It checks which button is pressed (start, exit, restart, or "I'm stuck!") and performs corresponding actions: changing game states, quitting the game, resetting game elements, or logging state. It manages interactions between mouse input, button activation flags, and g... | def process_button(self):
"""
Perform needed actions when a button is clicked.
"""
# If the start button is pressed
if self.Active_buttons[0] == 1 and \
self.Buttons[0].rect.collidepoint(pg.mouse.get_pos()):
self.game_state = 1
self.Active_butto... |
def reset_groups(self, score, lives):
"""
Reset game components. This includes the score, lives, map,
and lists of game component instances.
Args:
score: An int that represents player's current score.
lives: An int that represents player's current number of lives... | The main task of the code is to initialize a game state while preserving the player's current score and remaining lives. It resets game groups with the provided score and lives, initializes the game (including map generation), and creates necessary game groups to start a new level. | def update_level(self, current_score, current_lives):
"""
Initialize the game, preserving the player's score and
remaining number of lives.
Args:
current_score: player's current score.
current_lives: player's current number of lives.
"""
self.rese... |
def ssh_connection(ip):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username='root', password='123')
return ssh
def bridge_setup():
for bridge in [bridge1, bridge2]:
run_command(bridge, 'ethtool -K eth1 gso off gro off tso off')
... | The function `start_test` configures network devices with specified bandwidth, delay, and loss parameters, measures single-path and multi-path (MPBA) performance using curl and iperf tests, collects latency and throughput data, and returns median results for direct, tunnel, and shadowsocks connections alongside single-... | def start_test(bandwidth1, delay1, bandwidth2, delay2, queueSize1, queueSize2, loss1, loss2):
global server, hag, hcpe, client, bridge1, bridge2
client.close()
hcpe.close()
hag.close()
server.close()
bridge1.close()
bridge2.close()
server = ssh_connection('10.60.1.3')
hag = ssh_con... |
def ssh_connection(ip):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username='root', password='123')
return ssh
def run_command(ssh, command):
print('### ' + command)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)
for l... | The code establishes SSH connections to multiple network devices, configures network interfaces, runs an iperf3 server, and executes a series of network performance tests (direct, tunnel, shadowsocks) for specified bandwidth paths. It logs results including goodput metrics and percentages into a timestamped CSV file, i... | def run_unified_format(paths, name):
global server, hag, hcpe, client, bridge1, bridge2
server = ssh_connection('10.60.1.3')
hag = ssh_connection('10.60.1.2')
hcpe = ssh_connection('192.168.178.117')
client = ssh_connection('10.60.2.3')
bridge1 = ssh_connection('10.60.1.11')
bridge2 = ssh_co... |
def subscription_list(context, test_type="positive"):
"""Invoke the subscription list CLI subcommand."""
logger.info("subscription_list | starting")
command = assemble_command(context, " subscription list")
try:
logger.debug("subscription_list | running command: {0}".format(command))
co... | The main task of the code is to execute subscription-related CLI subcommands. It invokes `subscription_list`, `subscription_activate`, and `subscription_deactivate` functions sequentially, passing the `context` parameter, to manage subscription lifecycle operations. The function logs the initiation of these subcommands... | def subscription(context):
"""Invoke the subscription CLI subcommands."""
logger.info("subscription | starting subcommands")
subscription_list(context)
subscription_activate(context)
subscription_deactivate(context) |
def account_user_list(context, test_type):
"""Invoke the account user list CLI subcommand.
We execute 4 cases:
1. Default user list using admin (no --account)
2. User list for an account without users using admin
3. User list for an account with users using admin
4. User list using a non-admin ... | This function tests account user management CLI subcommands by executing operations like listing, adding, deleting, retrieving, and updating user accounts, using a test context and fake data to validate functionality. | def account_user(context, test_type="positive"):
"""Invoke the account user CLI subcommands."""
logger.info("account_user | starting subcommands")
account_user_list(context, test_type)
context = copy.deepcopy(root_context)
acct = fake_account_with_user()
account_add(context, acct["account_name"]... |
def random_image_data(context):
"""Helper method to grab random image metadata (for one image)."""
images = image_get(context, return_images=True, log=False)
return random.choice(images)
def log_explicit_failure(test_type, action, message, exit_on_fail=False):
if test_type == "positive":
logger.... | The main task of the code is to add an image to an analysis archive by first generating test image data, waiting for the image to be available, and then executing the "analysis-archive images add" CLI command with the image's digest. It handles exceptions during data retrieval, image availability checks, and command ex... | def analysis_archive_images_add(context, test_type="positive"):
"""Invoke the analysis-archive images add CLI subcommand."""
logger.info("analysis_archive_images_add | starting")
try:
image_data = random_image_data(context)
image = "{0}:{1}".format(
image_data[0]["image_detail"]... |
def random_image_data(context):
"""Helper method to grab random image metadata (for one image)."""
images = image_get(context, return_images=True, log=False)
return random.choice(images)
def log_explicit_failure(test_type, action, message, exit_on_fail=False):
if test_type == "positive":
logger.... | This function invokes the 'analysis-archive images del' CLI command to delete a randomly generated image from an archive, waits for image availability, handles exceptions, and logs results. It constructs image identifiers, executes commands via subprocess, checks responses, and records success/failure outcomes, includi... | def analysis_archive_images_del(context, test_type="positive"):
"""Invoke the analysis-archive images del CLI subcommand."""
logger.info("analysis_archive_images_del | starting")
try:
image_data = random_image_data(context)
image = "{0}:{1}".format(
image_data[0]["image_detail"]... |
def account_add(context, name, email, test_type="positive", log=True):
"""Invoke the account add CLI subcommand."""
if log:
logger.info("account_add | starting")
command = assemble_command(
context, " account add --email {0} {1}".format(email, name)
)
if log:
logger.debug("ac... | The code tests account-related CLI subcommands by generating fake data, executing operations like adding, retrieving, disabling, enabling, and deleting accounts, and validating edge cases with negative tests. It uses a deep-copied context for isolated tests and logs execution steps. | def account(context):
"""Invoke the account CLI subcommands."""
logger.info("account | starting subcommands")
faker = Faker()
account_name = faker.name().replace(" ", "")
account_email = faker.email()
account_add(context, account_name, account_email)
account_get(context, account_name)
ac... |
def analysis_archive_images_add(context, test_type="positive"):
"""Invoke the analysis-archive images add CLI subcommand."""
logger.info("analysis_archive_images_add | starting")
try:
image_data = random_image_data(context)
image = "{0}:{1}".format(
image_data[0]["image_detail"]... | The code performs operations on archive images by calling functions to add, delete, retrieve, list, and restore images within a given context. It manages archive image data through these actions, enabling comprehensive handling of image storage and retrieval processes. | def analysis_archive_images(context):
analysis_archive_images_add(context)
analysis_archive_images_del(context)
analysis_archive_images_get()
analysis_archive_images_list()
analysis_archive_images_restore() |
def system_feeds_list(context, test_type="positive", return_feeds=False, log=True):
"""Invoke the system feeds list CLI subcommand."""
if log:
logger.info("system_feeds_list | starting")
command = assemble_command(context, " system feeds list")
try:
if log:
logger.debug("sys... | The main task of the code is to manage system feeds by listing them, configuring their settings, and enabling deletion. The function `system_feeds` orchestrates these operations through three sub-functions: `system_feeds_list` (to retrieve feed data), `system_feeds_config` (to modify configurations), and `system_feeds_... | def system_feeds(context):
system_feeds_list(context)
system_feeds_config(context)
system_feeds_delete(context) |
def unit_tangent_vector(fi, fj, fk, point):
di = derivative(fi, point)
dj = derivative(fj, point)
dk = derivative(fk, point)
magnitude = vector_magnitude_3D([di, dj, dk])
return [di / magnitude, dj / magnitude, dk / magnitude]
def unit_normal_vector(fi, fj, fk, point):
f = vector_function(fi, fj... | The code computes the binormal vector at a given point for a curve defined by functions fi, fj, fk. It calculates the unit tangent and unit normal vectors at the point, then returns their 3D cross product, which defines the binormal direction perpendicular to both tangent and normal vectors. | def binormal_vector(fi, fj, fk, point):
tangent = unit_tangent_vector(fi, fj, fk, point)
normal = unit_normal_vector(fi, fj, fk, point)
return vector_cross_3D(tangent, normal) |
def surface_integral(f, surface, range, f_lower, f_upper, proj="xy", axis=0, xn=10, yn=10):
result = 0
if proj == "yz":
result = double_integral(lambda y, z: f(surface(y, z), y, z) *
np.sqrt(partial_derivative_2D_by_x(surface, [y, z])**2 +
... | The function computes the surface integral of a 2-form (vector field components p, q, r) over a given surface, using parametric derivatives to calculate the differential area vector. It evaluates the integrand by combining the vector field components with normalized partial derivatives of the surface, then calls a surf... | def surface_integral_of_2form(p, q, r, surface, range, f_lower, f_upper, proj="xy", axis=0, xn=10, yn=10):
# dsdx = partial_derivative_2D_by_x(surface, [-1.94, -0.40])
# dsdy = partial_derivative_2D_by_y(surface, [-1.94, -0.40])
# denominator = np.sqrt(dsdx**2 + dsdy**2 + 1)
# i = -dsdx / denominator
... |
def write_command(self, command_byte):
self.cbuffer[1] = command_byte
self.i2c.SendBuffer(self.cbuffer)
def clear(self):
for i in range(self.offset, len(self.buffer)) :
self.buffer[i] = 0
def display(self) :
if self.isSSD1306 :
self._display_ssd1306()
else :
self._display_sh1106() | This code initializes an OLED display by configuring essential parameters like charge pump, multiplex ratio, contrast, and precharge settings based on hardware conditions. It sends a sequence of display commands to set up the SH1106 display controller, enabling normal operation, and then clears the screen and turns the... | def init_display(self):
chargepump = 0x10 if self.external_vcc else 0x14
precharge = 0x22 if self.external_vcc else 0xf1
multiplex = 0x1f if self.height == 32 else 0x3f
compins = 0x02 if self.height == 32 else 0x12
contrast = 0x9f
# again note CHARGEPUMP isn't really on the SH1106. w/e
... |
def assemble_static_namespaced_paths(self, walk_root, walk_frag):
src_abspath = os.path.abspath(os.path.join(walk_root, walk_frag))
res_relpath = os.path.relpath(src_abspath, self.upstream_abspath)
dest_abspath = os.path.abspath(os.path.join(self.static_namespaced_abspath, res_relpath))
return (src_abspath, res... | This function copies upstream files to their destination paths, skipping specified relative paths. It transforms the host page template if the source matches the expected host page path, otherwise copies the file asynchronously. It yields the relative path of each processed file for further handling. | def _copy_walking_upstream_files(self, root, files):
for f in files:
src, rel, dest = self.assemble_static_namespaced_paths(root, f)
if rel in self.skip_relpaths:
continue
if src == self.expect_hostpage_abspath:
_transform_to_host_page_template(self.template_namespaced_abspath, src, self.static_names... |
def set_target(self):
if self.personality == "speedy" or self.personality == "slow":
return self.app.player.grid_pos
else:
if self.app.player.grid_pos[0] > COLS // 2 and self.app.player.grid_pos[1] > ROWS // 2:
return vec(1, 1)
if self.app.player.grid_... | The code updates an entity's position by setting a target, moving it pixel-by-pixel in a direction, and converting pixel coordinates to grid coordinates for collision detection or grid-based logic. It checks if movement is needed, adjusts the pixel position, and recalculates grid coordinates using buffer offsets and ce... | def update(self):
self.target = self.set_target()
if self.target != self.grid_pos:
self.pix_pos += self.direction * self.speed
if self.time_to_move():
self.move()
# Setting grid position in reference to pix position
self.grid_pos[0] = (self.pix_po... |
def install_phenix(password = None, version = None):
if os.path.isfile("PHENIX_READY"):
print("Phenix is already installed")
return
if ((not version) or (not password)):
exit("Need version and password for Phenix")
if (os.path.isfile("PHENIX_DOWNLOADED") or os.path.isfile("PHENIX_READY")):
print... | The function installs bioinformatics software (e.g., Bioconda, Phenix, AlphaFold, mmseq2) based on user-specified flags, handling versions, passwords, and directories. It executes installation routines for selected tools, adjusts working paths, and ensures proper configuration via sub-functions like `install_phenix`, `... | def install_software(
bioconda = True,
phenix = True,
phenix_version = None,
phenix_password = None,
alphafold = True,
alphafold_version = '',
biopython = True,
mmseq2 = True,
pdb_to_cif = True,
fix_paths = True,
content_dir = None,
):
if content_dir is None:
content_dir = os.getc... |
def train_base_inner(self, X, y, cv_outer, cv_inner, base_predictors=None, modality=None):
"""
Perform a round of (inner) k-fold cross validation on each outer
training set for generation of training data for the meta-algorithm
Parameters
----------
X : array of shape (n... | The main task of the code is to train base predictors for a multimodal ensemble model, setting their random states, generating meta-training/test data, and summarizing performance. It appends modality-specific data, updates predictors, and optionally prepares final models if enabled, returning the updated object with t... | def train_base(self, X, y, base_predictors=None, modality=None):
separator = "#" * 40
if modality is None:
text = separator * 2
else:
text = f"{separator} {modality} modality {separator}"
print("\n")
print("#" * len(text))
print(text)
pri... |
def clean_input(bacteria_input): #TODO: decide if there are more "mistakes" we want to allow the user to do
result = bacteria_input.lower().replace("_", " ")
return result
def download_stats(ftp, bacteria_folders_clean, save_folder, bacteria_input):
start = time.time()
print(datetime.now())
num_alr... | This function connects to an FTP server to download bacterial genome data matching a user-specified input. It filters bacterial folders, retrieves assembly statistics, downloads FASTA files based on criteria (level/date), organizes outputs into folders, and archives FASTA files into a ZIP. The task involves querying NC... | def get_genomes(num_try: int, save_folder, bacteria_input, filter_by_level, filter_by_date):
print(f'starting num_try {num_try}')
ftp = FTP(SERVER_PATH)
ftp.login()
print('logged in')
ftp.cwd(SERVER_BACTERIA_LOCATION)
print(f'changed dir to {SERVER_BACTERIA_LOCATION}')
all_ncbi_bacterias ... |
def __read_processes_state_dict2file(self):
dict2return = {}
if os.path.isfile(sc.PATH2SAVE_PROCESS_DICT):
file_to_read = open(sc.PATH2SAVE_PROCESS_DICT, "rb")
dict2return = pickle.load(file_to_read)
file_to_read.close()
logger.info(f'dict2return = {dict2retur... | This code initializes a process manager that tracks and controls multiple processes using state dictionaries, synchronization locks, and a scheduler. It validates input functions and paths, sets up listeners for state changes, and schedules periodic checks to monitor process states and handle job prefixes. | def __init__(self, max_number_of_process: int, upload_root_path: str, function2call_processes_changes_state: dict, function2append_process: dict, paths2verify_process_ends: dict):
self.__max_number_of_process = max_number_of_process
self.__upload_root_path = upload_root_path
self.__processes_sta... |
def bitsel (x, hi, lo):
mask = ((1 << (hi +1 - lo)) - 1)
return (x >> lo) & mask
def disasm_32b_instr (xlen, instr):
if ((instr >> 32) != 0):
return "[ERROR: 'instr' is > 32 bits: {:_x}]".format (instr)
s = ""
opcode7 = bitsel (instr, 6, 0)
rd = bitsel (instr, 11, 7)
funct3... | The code disassembles a given instruction (`instr`) based on its type, determined by the lower two bits. If the lower two bits are `0x3`, it uses a 32-bit disassembly function; otherwise, it uses a 16-bit function. It first checks if `instr` is negative, returning an error message if true. The main task is to decode RI... | def disasm (xlen, instr):
if (instr < 0):
return "[ERROR: 'instr' is negative: {:_x}]".format (instr)
if (bitsel (instr,1,0) == 0x3):
return disasm_32b_instr (xlen, instr)
else:
return disasm_16b_instr (xlen, instr) |
def calcPhiMn2(self, asInferior, asSuperior):
fs = self.calcFs(asInferior, asSuperior)
aWhitney = (asInferior*self.fy-asSuperior*fs)/(0.85*self.fc*self.bw)
phiMnConcreto = 0.90*0.85*aWhitney * \
self.fc*self.bw*(self.d-(aWhitney/2))
phiMnAceroComp = 0.90*asSuperior*fs*(self.d... | This method calculates required steel reinforcement (asReq) and related parameters for structural design. It checks if the applied moment (Mu) exceeds the maximum moment capacity (phiMnMax). If true, it computes additional steel area (asReq2) and updates total steel area (asReq), reinforcement ratio (cuantiaReq), and m... | def calcAsDef(self):
if(self.Mu > self.phiMnMax):
mc = (self.Mu-self.phiMnMax)*(np.power(10, 5))
div = self.phiFlexion*self.fy*(self.d-self.r)
self.asReq2 = round(mc/div, 2)
self.asReq = round(self.asMax+self.asReq2, 2)
self.cuantiaReq = round(self.cua... |
def calcAsTemp(self):
return 0.0018*self.bw*self.hw
def calcAsMin(self):
cuantiaMin1 = (0.8*np.sqrt(self.fc)/self.fy)*(self.bw*self.d)
cuantiaMin2 = 14*self.bw*self.d/self.fy
if cuantiaMin1 >= cuantiaMin2:
return cuantiaMin1
else:
return cuantiaMin2
def ca... | This method initializes object attributes by calculating and rounding key parameters like 'd', 'asTemp', 'asMin', 'cuantia' values, 'asMax', and 'phiMnMax' using helper methods. It prepares the object's state for subsequent operations by storing derived numerical values with specified precision. | def initialize(self):
self.d = round(self.hw-self.r, 2)
self.asTemp = round(self.calcAsTemp(), 2)
self.asMin = round(self.calcAsMin(), 2)
self.cuantiaTemp = round(self.calcCuantia(self.asTemp, self.hw), 4)
self.cuantiaMin = round(self.calcCuantia(self.asMin, self.d), 4)
s... |
def transform(board_or_space: int | NPArray | list[float],
transform_type: int) -> int | NPArray:
""" according to the transform number,
transform all the values on a board
or (overload) transform the index of 1 space """
if isinstance(board_or_space, (np.ndarray, list)):
return np... | The code tests the correctness of transformation functions by verifying that applying different transformation parameters yields consistent results, validating specific transformation outputs against expected values, and ensuring the choose_transformation and equal_transformations functions behave as intended across va... | def _test():
original = np.array([randrange(-1, 2) for _ in range(9)])
# sets that were a problem for previous implementation
# original = [-1, -1, 0, 0, -1, 0, 1, 0, -1]
# original = [0, 1, 0, -1, 0, -1, 0, 1, 0]
# original = [1, 0, -1, 0, 0, 0, -1, 0, 1]
# test transform
# print(transform(... |
def check_win(board: "SupportsGetItem[int, float]", player: int) -> bool:
""" player is 1 or -1 """
target = 3 * player
for win in possible_win_sets:
total = 0
for i in win:
total += board[i]
if total == target:
return True
return False
def get_winning_mov... | The code tests three functions in a tic-tac-toe-like game: `check_win` verifies win conditions, `get_winning_moves` identifies positions to force a win, and `can_block` checks if a player can block an opponent's win. The assertions validate these functions against various board states and player values (1/-1), ensuring... | def _test():
assert check_win([0, 1, 0, 0, 1, 0, 0, 1, 0], 1)
assert not check_win([0, 1, 0, 0, -1, 0, 0, 1, 0], 1)
assert check_win([0, 1, -1, 0, -1, 0, -1, 1, 0], -1)
assert not check_win([-1, 1, 0, 0, -1, -1, -1, -1, 0], -1)
assert get_winning_moves([0, 1, 0, 0, 0, 1, 1, 0, 0], 1) == []
asse... |
def _create_matindex(nrow, ncol):
"""
Create a 2D array of indexes used for the sorting technique.
"""
listindex = cp.arange(0.0, ncol, 1.0)
matindex = cp.tile(listindex, (nrow, 1))
return matindex
def _rs_dead(sinogram, snr, size, matindex, norm=True):
"""
Remove unresponsive and fluctu... | The function `remove_all_stripe` removes stripe artifacts from 3D tomographic data using Nghia Vo's combined algorithm (3,4,5,6). It applies median filters with specified window sizes (`la_size` for large stripes, `sm_size` for small-to-medium) to each sinogram slice, iteratively correcting artifacts. The `snr` paramet... | def remove_all_stripe(tomo,
snr=3,
la_size=61,
sm_size=21,
dim=1):
"""
Remove all types of stripe artifacts from sinogram using Nghia Vo's
approach :cite:`Vo:18` (combination of algorithm 3,4,5, and 6).
Parameters
... |
def get_token():
# Encode the client ID and client secret in base64
encoded_credentials = base64.b64encode((client_id + ':' + client_secret).encode()).decode('utf-8')
url = "https://accounts.spotify.com/api/token"
headers = {
"Authorization" : "Basic " + encoded_credentials,
"Content-T... | The main task of the code is to collect Spotify data for multiple rock bands by searching for artists, retrieving their datasets, aggregating them into a unified DataFrame, saving it as a CSV file, uploading it to Google Cloud Storage, and then deleting the temporary CSV file. | def populate_data():
token = get_token()
for band in rock_bands:
artist = search_artist(token,band)
artist_id = artist['id']
dataset = create_dataset(artist_id)
df = pd.DataFrame(dataset)
dfs.append(df)
# Concatenate all dataframes into a single DataFrame
df = pd... |
def get_starting_temps(start, end, frequency, amplitude, noisy, trend, mean, std_dev, **kwargs) -> pd.DataFrame:
dates = pd.date_range(start, end)
num_rows = len(dates)
normal1 = np.random.normal(loc=mean, scale=std_dev, size=num_rows // 2).clip(min=0, max=78)
normal1 = np.sort(normal1)
normal2 = np... | The function generates synthetic IoT data by creating initial device records, enriching them with timestamps, weather data, lifetime features, trip features, and defects using Spark and configuration parameters. It processes data in stages, grouping by device/trip IDs and applying custom functions to simulate sensor da... | def generate_iot(spark, dgconfig):
temps = get_starting_temps(**dgconfig['shared'] | dgconfig['temperature']['lifetime'])
starting_temps = spark.createDataFrame(temps)
add_timestamps = create_add_timestamps_func(**dgconfig['shared'] | dgconfig['timestamps'])
add_weather = create_add_weather_func(**dgcon... |
def make_grid(rows, width):
grid = []
gap = width // rows
for i in range(rows):
grid.append([])
for j in range(rows):
spot = Spot(i, j, gap, rows)
if i==0 or j==0 or i==rows-1 or j==rows-1:
spot.make_barrier()
grid[i].append(spot)
retu... | This code implements an interactive pathfinding visualization using Pygame. It initializes a grid, allows users to set start/end points and barriers via mouse clicks, and executes a pathfinding algorithm (e.g., A*) when the spacebar is pressed. The algorithm uses the grid's neighbor relationships and updates the visual... | def main(win, width):
ROWS = 50
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
if st... |
def get_max_players(self):
if self._max_players == 0:
return_func = Function('GETSLOTCOUNT', 1)
self._max_players = self._rabbithole.send_return_func(return_func)
return self._max_players
def _initialize(self):
self.build_players()
self._plugin_manager.propagate_on_server_init()
def _run(self):
while T... | This code initializes a server by loading configuration files, setting up a connection to a communication interface (Rabbithole), initializing event parsing, managing plugins, and starting the server if configured. It reads 'config.ini' and 'plugin_config.ini', initializes variables, connects to the Rabbithole interfac... | def __init__(self):
self._alice_config = ConfigParser()
self._plugin_config = ConfigParser()
self._alice_config.read('config.ini')
self._plugin_config.read('plugin_config.ini')
self._players = []
self._server_initialized = False
self._max_players = 0
rabbit_hole_path = "/tmp/rabbithole.ipc.28960"
... |
def modifyGaussianPrior(prior):
global PRIOR
PRIOR = prior
def getAllNames(curr_matches):
return set(match[1] for match in curr_matches) | set(match[2] for match in curr_matches)
def initializeParams(params, all_names, curr_period, prev_period):
'''
Initializes the parameters for each athlete's p... | The PAPERS function probabilistically initializes and updates athlete performance parameters across time periods using match and athlete data. It processes each period's matches, updates observation-based parameters, handles non-observation updates, and computes average performance metrics. The function returns total a... | def PAPERS(period_data, match_data, athlete_data, modifyPrior = None, verbose = False):
'''
PAPERS - probabilistically initializes and updates the performance functions for each athlete.
'''
if modifyPrior is not None:
modifyGaussianPrior(modifyPrior)
all_periods = sorted(period_d... |
def check_args(self, args):
assert(args.arch_interaction_op == "cat" and "Sparse and dense features must be concatenated in wide and deep")
ln_bot = np.fromstring(args.arch_mlp_bot, dtype=int, sep="-")
assert(len(ln_bot) == 1 and "There is no MLP layers to process input continuous features")
r... | This code initializes a multi-task wide-and-deep neural network model. It parses architecture parameters, configures input/output dimensions for interaction layers, sets up Caffe2 model helpers, and prepares model components based on command-line arguments. The constructor handles both new model creation and reuse of e... | def __init__(
self,
cli_args,
model=None,
tag=None,
enable_prof=False,
id_qs = None,
len_qs = None,
fc_q = None # TODO: Rename this as there are no bottom fc layers
):
super(MT_Wide_and_Deep, self).__init__()
self.args = cli_args
... |
def create_emb(self, m, ln, model, tag, id_qs = None, len_qs = None):
(tag_layer, tag_in, tag_out) = tag
emb_l = []
weights_l = []
for i in range(0, ln.size):
n = ln[i]
# create tags
len_s = tag_layer + ":::" + "sls" + str(i) + "_l"
ind_s ... | This code constructs a sequential neural network model for recommendation systems by integrating user profile, behavior, candidate ad, and context features. It generates embeddings, applies attention mechanisms to user behavior data, concatenates attention outputs with other feature embeddings, and feeds them into a mu... | def create_sequential_forward_ops(self, id_qs = None, len_qs = None, fc_q = None):
# embeddings
tag = (self.temb, self.tsin, self.tsout)
self.emb_l, self.emb_w = self.create_emb(self.m_spa, self.ln_emb,
self.model, tag,
... |
def _to_char_pointer(self, s):
if isinstance(s, str):
s = self._odbc_encode(s)
return c_char_p(s)
def _to_wchar_pointer(self, s):
if self._sqlwchar_size == 2:
return c_char_p(self._odbc_encode(s))
return c_wchar_p(s)
def check_success(
self, return_code: U... | This function connects to a database using the provided connection string, selecting between ANSI or Unicode versions of the SQLDriverConnect ODBC API based on the 'ansi' parameter. It initializes the connection handle, passes the connection string and configuration flags, and verifies the operation's success through e... | def sql_driver_connect(
self, connection: Connection, connection_string: str, ansi: bool
) -> None:
if ansi:
c_connect_string = self._to_char_pointer(connection_string)
f = self.cdll.SQLDriverConnect
else:
c_connect_string = self._to_wchar_pointer(connecti... |
def _to_wchar_pointer(self, s):
if self._sqlwchar_size == 2:
return c_char_p(self._odbc_encode(s))
return c_wchar_p(s)
def _count_odbc_encoded_bytes(self, s) -> int:
"""Return the number of bytes required in the DriverManager's encoding."""
return int(len(self._odbc_encode(s)... | This method executes a SQL query directly using ODBC by converting the query string to a wide-character format, calculating its encoded byte length, and invoking SQLExecDirectW with the cursor handle. It then verifies the operation's success via return code checking. | def sql_exec_direct(self, cursor: Cursor, query_string: str) -> None:
c_query_string = self._to_wchar_pointer(query_string)
length = self._count_odbc_encoded_bytes(query_string)
return_code = self.cdll.SQLExecDirectW(cursor.handle, c_query_string, length)
self.check_success(return_code, ... |
def _to_buffer(self, init, size=None):
if self._sqlwchar_size == 2:
return create_string_buffer(init, size)
return create_unicode_buffer(init, size)
def check_success(
self, return_code: Union[int, ReturnCode], handler: Handler
) -> None:
if isinstance(return_code, int):
... | This function retrieves metadata about a specific SQL column using ODBC's SQLDescribeColW, extracts details like name, data type, size, and nullability, maps SQL types to Python types, and returns a structured SqlColumnDescription object with optional lowercase conversion for the column name. | def sql_describe_col(
self,
cursor: Cursor,
column_number: int,
lowercase: typing.Optional[bool] = None,
) -> SqlColumnDescription:
buffer_length = 1024
column_name = self._to_buffer(buffer_length)
name_length = SQLSMALLINT()
data_type = SQLSMALLINT()
... |
def _to_buffer(self, init, size=None):
if self._sqlwchar_size == 2:
return create_string_buffer(init, size)
return create_unicode_buffer(init, size)
def check_success(
self, return_code: Union[int, ReturnCode], handler: Handler
) -> None:
if isinstance(return_code, int):
... | This function retrieves data from a database cursor using ODBC, converts raw data to Python types based on column metadata, handles null values, and returns the processed result. It uses a buffer to fetch data, checks for success, interprets indicators, and applies type-specific conversion handlers from a predefined ma... | def sql_get_data(
self, cursor: Cursor, column_description: SqlColumnDescription
) -> typing.Any:
buffer_size = 4096
buffer = self._to_buffer(buffer_size)
length_or_indicator = SQLLEN()
return_code = self.cdll.SQLGetData(
cursor.handle,
column_descri... |
def _to_buffer(self, init, size=None):
if self._sqlwchar_size == 2:
return create_string_buffer(init, size)
return create_unicode_buffer(init, size)
def check_success(
self, return_code: Union[int, ReturnCode], handler: Handler
) -> None:
if isinstance(return_code, int):
... | This function retrieves specific database metadata from a connection using ODBC's SQLGetInfoW, based on the provided InfoType. It allocates a buffer, executes the API call, validates success, and converts the result buffer to a Python object for return. | def sql_get_info(self, connection: Connection, info_type: InfoType) -> typing.Any:
buffer_size = 4096
buffer = self._to_buffer(buffer_size)
string_len = SQLSMALLINT()
return_code = ReturnCode(
self.cdll.SQLGetInfoW(
connection.handle,
info_ty... |
def _to_buffer(self, init, size=None):
if self._sqlwchar_size == 2:
return create_string_buffer(init, size)
return create_unicode_buffer(init, size)
def check_success(
self, return_code: Union[int, ReturnCode], handler: Handler
) -> None:
if isinstance(return_code, int):
... | This function retrieves a list of SQL drivers available in the specified environment, optionally including driver attributes. It uses ODBC's SQLDriversW function to fetch driver descriptions and attributes, handling pagination via SQL_FETCH_FIRST and SQL_FETCH_NEXT. If include_attributes is True, attributes are split b... | def sql_drivers(
self, environment: Environment, include_attributes: bool = False
) -> list[str]:
buffer_size = 1000
direction = SqlFetchType.SQL_FETCH_FIRST
buffer_length = c_short(buffer_size)
description_length = c_short()
attributes_length = c_short()
driv... |
def jsonToHeadOveriew(cfgJsonObject):
html = ""
if cfgJsonObject.get('config', False) and cfgJsonObject.get('global', False):
logo = "fortigate2.png"; device = cfgJsonObject['config']['version']['version'].split('-')
firewallversion = getPopoverContents(device[1]) # Get the versionnumber
... | This function converts a JSON configuration object into HTML cards for a dashboard interface, generating styled Bootstrap cards with icons, titles, and content for specified sections (e.g., 'interface', 'firewall policy'). It skips unconfigured sections, handles debug logging, and appends unconfigured items to a backlo... | def jsonToCardMenus(jsonConfigObject, gradeColor="warning"):
global jsonConfigObjectGlobal; jsonConfigObjectGlobal = jsonConfigObject
html = jsonToHeadOveriew(jsonConfigObjectGlobal) # header
htmlBacklog = "" # Init of backlog variable for unconfigured settings/information
arguments = ['interface', 'fi... |
def get_colors(self, df, color_by=None, color_map='viridis',
highlight_best=None):
"""
"""
# Choose colors for each step option and collect corresponding
# pipeline indices
step_colors = self.get_step_colors(df, color_by=color_by,
... | This function generates box-and-whisker plots comparing pipeline performance across outer folds in a cross-validation setup. It aggregates test scores from inner loops, optionally separates plots per fold or combines all data, sorts pipelines by median scores, and applies customizable coloring, legends, and visual styl... | def plot_contest(self, fontsize=6, figsize=(10, 30), markersize=2,
all_folds=False, color_by=None, color_map='viridis',
legend_loc='best', legend_font_size='10',
legend_marker_size=0.85, box_line_thickness=0.5,
draw_points=False, highli... |
def GetIOServicesByType(service_type: bytes) -> list[ctypes._CData]:
"""List specified ``service_type``."""
serial_port_iterator = ctypes.c_void_p()
iokit.IOServiceGetMatchingServices(
kIOMasterPortDefault, iokit.IOServiceMatching(service_type), byref(serial_port_iterator)
)
services = []
... | This function scans for serial ports on macOS using IOKit, gathers USB-related information (VID, PID, serial number, etc.), and returns a list of PortInfo objects containing device details. It processes IOKit services, extracts properties from USB devices, and associates each port with interface data. The include_links... | def comports(include_links: bool = False) -> list[PortInfo]:
# include_links is currently ignored. Are links in /dev even supported here?
# Scan for all iokit serial ports
services = GetIOServicesByType(b"IOSerialBSDClient")
ports = []
serial_interfaces = scan_interfaces()
for service in service... |
def prepare_tokenizer(args):
tokenizer = get_tokenizer(args)
num_tokens = tokenizer.num_tokens
before = num_tokens
after = before
multiple = args.make_vocab_size_divisible_by * \
mpu.get_model_parallel_world_size()
while (after % multiple) != 0:
after += 1
print_rank... | The main task of the code is to execute a training program that disables CuDNN, initializes distributed training, sets up a model and tokenizer, and generates images continually using PyTorch. It configures devices, random seeds, and arguments for reproducibility, then invokes `generate_images_continually` with the pre... | def main():
"""Main training program."""
print('Generate Samples')
# Disable CuDNN.
torch.backends.cudnn.enabled = False
# Arguments.
args = get_args()
# Pytorch distributed.
initialize_distributed(args)
# set device, this args.device is only used in inference
if args.device... |
def printHelp():
print('Type 1 to add users')
print('Type 2 to show users')
print('Type 3 to show user by name')
print('Type 4 to show users that have password longer than 8')
print('Type 5 to show user with longest name')
print('Type 6 to print help')
print('Type 7 to exit')
def addToDb():
... | The code defines a menu-driven interface for user management. It continuously prompts the user for commands to add users, display all users, search by name, filter by password length, find the user with the longest name, show help, or exit. Each command triggers specific database operations like adding, retrieving, or ... | def start():
printHelp()
while True:
cmd = input('enter command>> ')
if cmd == "1":
count = input('Enter count of users you want add: ')
for i in range(int(count)):
print(f"Add user no.{i+1}")
addToDb()
elif cmd == "2":
... |
def force(tt,vel):
global ball
return(np.array([0,-ball['mass']*g]))
def gl_stupid(): #NO IDEA WHAT HALF THIS DOES! SOMETHING WITH BUFFERS AND MATRICES
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
glViewport(0, 0, *screen['dim'])
glMatrixMode(GL_PROJECTION)
glLoadIdentit... | This code simulates a physics-based ball movement with real-time OpenGL rendering. It initializes a Pygame window, processes mouse clicks to apply forces, calculates acceleration/velocity, updates ball position, checks collisions, and renders a trail. The main loop handles event input, physics calculations, OpenGL rend... | def main():
global t, dt, screen, ball
pg.init()
pg.display.set_mode(tuple(screen['dim']), DOUBLEBUF|OPENGL)
clock = pg.time.Clock()
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
quit()
if event.type == pg... |
def start_scan(self, start_scan_callback):
user_input = dict()
user_input['phone'] = self.input_vars.PHONE_INPUT_VAR.get()
user_input['state'] = (self.state_id_map[self.input_vars.STATE_INPUT_VAR.get()],self.input_vars.STATE_INPUT_VAR.get())
user_input['districts'] = [ (self.district_id_... | The main task of the code is to set up a GUI interface with Tkinter, creating frames, labels, buttons, and text displays for a CoWIN Helper Portal. It organizes elements like a header label, a "Submit" button linked to a scan function, and sections for displaying selected districts. The layout includes structured frame... | def setup_widgets(self, bt_callback):
Style.configure()
self.main_frame = tk.Frame(master=self.master)
self.main_frame.pack()
header_frame = tk.Frame(master=self.main_frame)
header_frame.pack(expand=True, pady=10)
header_label = ttk.Label(master=header_frame, text='CoWI... |
def m_a_at_abs_zero_from_shellard(f_a):
"""
Classic T = 0 axion mass form shellard (original from weinberg)
"""
return model.m_pi0 * model.f_pi0 * np.sqrt(model.m_u * model.m_d) / (model.m_u + model.m_d) / f_a
def m_a_at_high_T_from_fox(T, f_a, with_correction):
"""
Compute axion mass at high te... | This function computes the mass parameter $ m_a $ from chi data using Borsamyi's lattice QCD simulations. It applies $ m_a(T=0) $ from Shellard's model for temperatures below the paper's data domain and switches to $ m_a $ from Fox's high-temperature model for temperatures above the domain. For intermediate temperature... | def m_a_from_chi_general(T, f_a, chi_interp_to_use=None):
"""
Compute m_a fro chi data from Borsamyi's lattice qcd simulations but use m_a(T = 0) below its domain and
m_a = m_a_shellard for T above its domain.
"""
if chi_interp_to_use is None:
chi = chi_interp_paper
return np.where(T < T_... |
def _deleteConsultations(data):
removed_room_data = _deleteFromLecturer(data)
if removed_room_data is None:
return False
_deleteFromRooms(removed_room_data, data['lecturer_id'])
return True
def _addConsultations(data):
_addToLecturer(data)
_addToRooms(data)
def _getConsultations(data):
... | This function handles HTTP requests for consultation data. It processes JSON payloads to perform CRUD operations: DELETE removes data via _deleteConsultations, PUT adds data via _addConsultations, POST retrieves data via _getConsultations, and returns appropriate HTTP status codes (200/500 for success/errors). Unsuppor... | def consultations(request):
data = json.loads(request.body.decode('utf-8'))
if request.method == 'DELETE':
return HttpResponse(status=200) if _deleteConsultations(data) else HttpResponse(status=500)
elif request.method == 'PUT':
_addConsultations(data)
return HttpResponse(status=200)... |
def find_datafiles(self):
datafiles = []
for package in self.datafile_packages:
pkg_datafile_function = DATAFILE_REGISTRY.get(package)
if pkg_datafile_function is None:
pkg = importlib.import_module(package)
pkg_datafile_function = pkg.find_datafiles
datafiles.extend(pkg_datafile_function())
if s... | This code builds a cross-platform installer for a Python application using setuptools, handling platform-specific configurations (Windows, macOS), certificate password input, and packaging options. It validates required parameters, constructs setup arguments with metadata, build tools (py2exe, py2app, innosetup), and g... | def build_installer(self):
if None in (self.name, self.main_module):
raise RuntimeError("Insufficient information provided to build")
if is_windows and self.certificate_file is not None and self.certificate_password is None:
self.certificate_password = os.environ.get('CERTIFICATE_PASS') or getpass.getpass("Ce... |
def remove_embedded_interpreter(self):
print("Replacing the embedded interpreter with a dumby file")
interpreter_path = os.path.join(self.get_app_path(), 'python')
os.remove(interpreter_path)
self.execute_command('touch %s' % interpreter_path)
self.execute_command('chmod +x %s' % interpreter_path)
def shrink_... | The main task of the code is to finalize a macOS application build by removing embedded interpreters, optimizing binaries, creating a DMG file, and moving output files. It also conditionally generates an update archive if specified. | def finalize_build(self):
print("Finalizing build...")
if platform.system() == 'Darwin':
self.remove_embedded_interpreter()
self.shrink_mac_binaries()
self.lipo_file(os.path.join(self.get_app_path(), self.name))
self.create_dmg()
self.move_output()
if self.create_update:
self.create_update_archiv... |
def prebuild_message(self):
print("Installer builder version %s" % __version__)
print("Building %s installer for %s %s" % (platform.system(), self.name, self.version))
def remove_previous_build(self):
print("Removing previous output directories")
directories = self.build_dirs + [self.output_directory]
for dir... | The code's main task is to orchestrate a build process by initializing timing, preparing the build environment, removing prior builds, constructing an installer, finalizing the build, executing post-build commands, and reporting statistics to manage the lifecycle of software compilation and deployment. | def build(self):
self.build_start_time = time.time()
self.prebuild_message()
self.remove_previous_build()
self.build_installer()
self.finalize_build()
self.perform_postbuild_commands()
self.report_build_statistics() |
def _set_source_destination(self):
source = wrapper.prompt_alias("source")
destination = wrapper.prompt_alias("destination")
return (source, destination)
def prompt_properties(self):
text = "What properties do you want to sort? separate properties with a comma and use the = for a desired... | The code's main task is to move items from a source to a destination based on specified properties. It retrieves items from the source, checks if they meet predefined properties, and transfers qualifying items to the destination, pausing briefly after each move to manage processing load. | def sort_items(self):
# type: () -> None
source, destination = self._set_source_destination()
property_dict = {}
res, response = self.prompt_properties()
if res:
property_dict = self._parse_property_response(response)
else:
return
item_list... |
def _validate_integer(self, action_result, parameter, key, allow_zero=False):
"""
Validate an integer.
:param action_result: Action result or BaseConnector object
:param parameter: input parameter
:param key: input parameter message key
:allow_zero: whether zero should b... | The main task of the code is to retrieve a list of firewall policies from a Fortigate device. It handles parameters like vdom and limit, authenticates if needed, paginates results, and returns the data along with a summary of total policies fetched. It ensures error handling for invalid inputs and API calls, updating t... | def _list_policies(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
# fetch vdom
vdom = param.get(FORTIGATE_JSON_VDOM, '')
if not vdom and self._api_vdom:
vdom = self._api_vdom
# fetch limit
ret_val, limit = self._validate_int... |
def _login(self, action_result):
credential_data = {
"username": self._api_username,
"secretkey": self._api_password
}
# Initializing session object which would be used for subsequent API calls
self._sess_obj = requests.session()
status, response = self.... | The main task of the code is to test connectivity to a Fortigate device by verifying credentials and network configuration. It attempts login using provided credentials, checks SSL certificate validity if enabled, and sends a REST request to a specific endpoint. Success or failure status is logged based on API response... | def _test_connectivity(self, param):
"""
Called when the user depresses the test connectivity button on the Phantom UI.
Use a basic query to determine if the device IP/hostname, username and password is correct
"""
action_result = self.add_action_result(ActionResult(dict(param)... |
def _login(self, action_result):
credential_data = {
"username": self._api_username,
"secretkey": self._api_password
}
# Initializing session object which would be used for subsequent API calls
self._sess_obj = requests.session()
status, response = self.... | The main task of the code is to unblock a specific IP address by removing it from a Fortigate firewall policy. It handles authentication, extracts parameters, verifies the IP's existence, checks if it's already unblocked, and uses REST API calls to delete the blocked entry. The function returns success or error statuse... | def _unblock_ip(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
if not self._api_key:
# Initiating login session
ret_val = self._login(action_result)
if phantom.is_fail(ret_val):
return action_result.get_status()
... |
def _login(self, action_result):
credential_data = {
"username": self._api_username,
"secretkey": self._api_password
}
# Initializing session object which would be used for subsequent API calls
self._sess_obj = requests.session()
status, response = self.... | The function blocks an IP address by creating an address entry if it doesn't exist, retrieving the policy ID, and updating the policy's destination to block the IP. It handles API authentication, parameter validation, and REST API calls to a firewall system, returning success or error statuses based on operations. | def _block_ip(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
if not self._api_key:
# Initiating login session
ret_val = self._login(action_result)
# Something went wrong
if phantom.is_fail(ret_val):
retur... |
def __getTotalLength(self) -> float:
return self.dayCourse[Course.HIGH.value] - self.dayCourse[Course.LOW.value]
def __getTransformedBodySize(self) -> float:
bodySize = self.__getBodySize()
return abs(bodySize)
def __getBalance(self) -> str:
difference = self.__getBodySize()
re... | This method returns a dictionary containing key candlestick properties such as total length, body size, balance, and wick lengths, calculated using internal helper methods. It aggregates these metrics into a structured format for further analysis or pattern recognition in candlestick data. | def __getAbsoluteCandleStickCriteria(self) -> dict:
return {
CandleStickProp.TOTAL_LENGTH.value: self.__getTotalLength(),
CandleStickProp.BODY_SIZE.value: self.__getTransformedBodySize(),
CandleStickProp.BALANCE.value: self.__getBalance(),
CandleStickProp.UPPER_WI... |
def get_reservation_from_tensor(self, r):
arr = []
x_range = self.duration - (r.begin - self.time_range[0])
x_start = r.begin - self.time_range[0] + 1
# this must always start at 8 because of this example [8-15] and [9-10] 1 interferes with 2
y_range = r.ending - self.time_range... | The code's main task is to fit reservations into a space by adjusting their x-positions. It iterates through each reservation, identifies interfering ones, sorts them by x-coordinate, finds the first valid position to place the reservation, and updates its x-coordinate if a valid spot is found (x_pos ≥ 0), ensuring non... | def try_fit(self):
for i in range(len(self.reservations)):
interfering_reservations = self.get_reservation_from_tensor(self.reservations[i])
interfering_reservations.sort(key=lambda element: element.x, reverse=False) # sort the reservations after x position
x_pos = self.find... |
def get_grid_in_brick(survey, brickname, rng=None, seed=None):
brick = survey.get_brick_by_name(brickname)
brickwcs = wcs_for_brick(brick)
W, H, pixscale = brickwcs.get_width(), brickwcs.get_height(), brickwcs.pixel_scale()
if rng is None:
logger.info('Using seed = %d',seed)
rn... | This function generates random galaxy catalogues for specified survey bricks using a given truth catalog. It initializes a random number generator, aggregates random galaxy data from each brick, sets photometric system flags (S/N) based on the southern hemisphere flag, and populates the random catalog by sampling from ... | def get_grid_randoms(truth_fn, bricknames=[], south=True, seed=None):
rng = np.random.RandomState(seed=seed)
randoms = 0
survey = LegacySurveyData(survey_dir='/global/cfs/cdirs/cosmo/work/legacysurvey/dr9')
for iseed,brickname in enumerate(bricknames):
randoms += get_grid_in_brick(survey,br... |
def read(self, now):
# type: (float) -> None
"""
Read character by character from stdin when bytes available to prevent blocking.
When a whole line has been read (current character is newline), run dispatcher.
"""
while runtime.serial_bytes_available:
char = s... | This code continuously runs a loop to manage communication state, handling timeouts for active connections, retrying handshakes if inactive for 15 seconds, sending "451" after 2 seconds of inactivity, and performing garbage collection to optimize memory. It monitors time-based conditions to maintain or reset connection... | def start(self):
# type: () -> None
while True:
now = monotonic()
self.read(now)
self.debounce(now)
if self.active and now > (self.rx_time + 15): # timeout, retry handshake
self.send("DBG=Timeout, retrying handshake")
self.... |
def configure_environment(args, contexts):
wdk_found = False
headers_found = False
# Look for WDK
print(" Looking for WDK in %s... " % args.wdk, end='')
if(os.path.exists(args.wdk)):
print("found!")
wdk_found = True
else:
print("not found!")
wdk_found = False
... | The main task of the code is to parse DirectX 11/12 DDI header files from the Windows Driver Kit (WDK) to generate stubbed entry-point code. It uses template files and argument name hints from a CSV to produce output in a specified directory, handling environment configuration, input validation, and file generation. | def main():
success = True
parser = argparse.ArgumentParser(
description='Parse D3D11/12 DDI header files to produce stubbed entry-points.')
parser.add_argument('--wdk', metavar='PATH',
required=True, help='Define WDK path')
parser.add_argument('--output', metavar='PATH'... |
def points(self, map):
def ev(part): return 1 if isinstance(part, Dado) else 3
return sum([ev(map._map[pos]) for pos in map._pieceTeams[2]]) -\
sum([ev(map._map[pos]) for pos in map._pieceTeams[1]])
def whoCanMove(self, map, time):
array = []
capturePositions = map.someoneCan... | The code implements the Minimax algorithm for a board game, recursively evaluating possible moves for a player (1 or 2) up to a specified depth. It explores all valid moves, simulates them using deepcopy, and returns the best move (position and action) by minimizing/maximizing the evaluation score, with terminal states... | def _minimax(self, board, depth, player, bestPos=None):
if depth == self.depth:
return self.points(board), bestPos
if board.gameover(1):
board.print()
return -999, bestPos
if board.gameover(2):
board.print()
return 999, bestPos
... |
def close():
root.destroy()
def game():
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.tracer(False)
screen.title(f"{cur_player_name}")
game_is_running = True
snake = Snake()
food = Food()
score = Score()
screen.listen()
screen.onk... | The function fetches a player's name from an entry widget, validates it's not empty, stores it globally, then triggers game closure, game initiation, and leaderboard display. | def fetch_player_name():
player_name = player_entry.get()
if not player_name:
tk.messagebox.showinfo(message="Player Name field is empty!")
else:
global cur_player_name
cur_player_name = player_name
close()
game()
show_leaderboard() |
def _add_to_write(self, text: str):
self.assembly_command.append(text+"\n")
def _pop_common_pattern(self, assembly_pointer: str, index: int) -> None:
# addr = segmentPointer + i, SP - -, *addr = *SP
self._add_to_write(f"@{assembly_pointer}")
self._add_to_write("D=M")
self._add_to... | This function generates assembly code to implement 'push' or 'pop' commands for specified memory segments and indexes. It handles eight memory segments (local, argument, this, that, static, temp, pointer, constant) with distinct handling for each, using helper methods for common patterns. For 'pop', it decrements the s... | def write_push_pop(self, command: CommandNameEnum, segment: str, index: int) -> None:
"""
Writes to the output file the assembly code that implements the given command
:param command: C_PUSH or C_POP
:param segment: str
:param index: int
:return:
"""
self.... |
def _add_to_write(self, text: str):
self.assembly_command.append(text+"\n")
def _arith_multi_param(self, return_value: str):
self._decrement_segment_pointer_and_go_to_memory_address_one_below_sp()
self._add_to_write(f"M={return_value}")
def _arith_single_param(self, return_value: str):
s... | (The function `write_arithmetic` translates a given arithmetic command into corresponding assembly code. It maps commands like "add", "sub", "neg", etc., to specific assembly operations using helper methods, handling both unary and binary operations. It writes a comment for the command, applies the appropriate logic (e... | def write_arithmetic(self, command: str) -> None:
"""
Writes to the output file the assembly code that implements the given arithmetic command.
:param command: str
:return: None
"""
self._add_to_write(f'// {command}')
match command:
case "add":
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.