dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def rouletteWheel(population):
cumulative = sum(population)
increment = 0
hit = random.random()
for i in range(len(population)):
increment += population[i].highest_fitness/cumulative
if(increment > hit):
selected = population.pop(i)
return selected, population
def... | The main task of the code is to implement a genetic algorithm step that evolves a population by selecting parent candidates via roulette wheel selection, saving them, and generating a new population using multi-threading. It returns the newly created population for the next generation. | def geneticAlgorithm(population, gen_num):
# select parent candidates
parent_candidates = []
pop_count = len(population)
for _ in range(len(population)//2):
selected_parent, population = rouletteWheel(population)
parent_candidates.append(selected_parent)
# save parents to a file
... |
def plurality_value(examples):
value = None
max_weight = -1
count = count_goals(examples)
for ex in examples:
if count[ex.goal] > max_weight:
max_weight = count[ex.goal]
value = ex.goal
return value
def same_goal(examples):
goal = examples[0].goal
for i i... | This function constructs a decision tree recursively by selecting the feature with maximum information gain, splitting examples into subtrees, and creating leaf nodes based on majority voting when examples are exhausted, depth limit is reached, or all examples share the same goal. | def d_tree(examples, features, parent_examples, depth=20):
if not examples:
return DNode(plurality_value(parent_examples), is_leaf=True)
if same_goal(examples):
return DNode(examples[0].goal, is_leaf=True)
if not features:
return DNode(plurality_value(examples), is_leaf=True)
f... |
def parseLinesList(linesListRaw):
return [
[(int(x1), int(y1)), (int(x2), int(y2))]
for x1, y1, x2, y2 in [re.split(",| -> ", lineStr) for lineStr in linesListRaw]
]
def createCoor(xSize, ySize):
return [[0 for x in range(xSize)] for y in range(ySize)]
def countCoor(coor):
return len([x ... | The main task of the code is to process a list of lines by parsing them, creating a coordinate system, inserting horizontal and vertical lines into this system, and then counting the resulting coordinate intersections or overlaps. The function returns the count of these calculated coordinates after processing. | def firstResult():
lines = parseLinesList(linesListRaw)
coor = createCoor(1000, 1000)
return countCoor(insertHVLines(coor, lines)) |
def parseLinesList(linesListRaw):
return [
[(int(x1), int(y1)), (int(x2), int(y2))]
for x1, y1, x2, y2 in [re.split(",| -> ", lineStr) for lineStr in linesListRaw]
]
def createCoor(xSize, ySize):
return [[0 for x in range(xSize)] for y in range(ySize)]
def countCoor(coor):
return len([x ... | The function processes a list of lines by parsing them, creating a coordinate grid, inserting horizontal, vertical, and diagonal lines into the grid, and then counting the resulting coordinates to return the final result. | def secondResult():
lines = parseLinesList(linesListRaw)
coor = createCoor(1000, 1000)
return countCoor(insertHVDLines(coor, lines)) |
def dna_preprocess(dna1, dna2, sat=0.1):
# add channels to increase signal:
add = add_ims(dna1, dna2).astype('uint16')
# remove singleton dimension:
add = np.squeeze(add)
# change bit depth:
_16bit = img_as_uint(add)
# adjust contrast:
adjusted = adjust_contrast(_16bit, sat)
return i... | The main task of the code is to generate a pseudo-color image by processing DNA and counterstain images through normalization, contrast adjustment, denoising, and applying custom color maps (purple for DNA, magenta for counterstain), then combining them into a final 16-bit unsigned integer image. | def make_pseudo(dna_img1, dna_img2, counterstain_img):
'''
Input = raw tiff images.
'''
# ensure float for rescaling:
counterstain_img = counterstain_img / counterstain_img.max()
dna_img1 = dna_img1 / dna_img1.max()
dna_img2 = dna_img2 / dna_img2.max()
# cnvert to 16bit uint:
ruth ... |
def dna_preprocess(dna1, dna2, sat=0.1):
# add channels to increase signal:
add = add_ims(dna1, dna2).astype('uint16')
# remove singleton dimension:
add = np.squeeze(add)
# change bit depth:
_16bit = img_as_uint(add)
# adjust contrast:
adjusted = adjust_contrast(_16bit, sat)
return i... | The main task of the code is to generate a pseudo-IHC composite image by processing three input channels (DNA, counterstain, and IHC stain) through contrast adjustment, denoising, color mapping via LUTs, and merging. Each channel is individually enhanced and color-transformed (e.g., DNA to blue, counterstain to pink) b... | def make_pseudo_IHC(dna_img1, dna_img2, counterstain_img, IHC_stain_img):
'''
Input = raw tiff images.
'''
ruth = img_as_uint(counterstain_img)
dna1 = img_as_uint(dna_img1)
dna2 = img_as_uint(dna_img2)
IHC_stain = img_as_uint(IHC_stain_img)
##### DNA: BLUE #####
# adjus... |
def add_cmd_handler(self, cmd, func):
"""Adds a command handler for a command."""
len_args = len(inspect.getargspec(func)[0])
def add_meta(f):
def decorator(*args, **kwargs):
f(*args, **kwargs)
decorator.bytes_needed = len_args - 1 # exclude self
... | This method automatically detects and configures a board's layout by querying its capabilities via Firmata's capability response. It registers a handler for capability responses, sends a capability query, waits for serial data, processes incoming bytes, and initializes the board layout if detected. If no layout is iden... | def auto_setup(self):
"""
Automatic setup based on Firmata's "Capability Query"
"""
self.add_cmd_handler(CAPABILITY_RESPONSE, self._handle_report_capability_response)
self.send_sysex(CAPABILITY_QUERY, [])
self.pass_time(0.1) # Serial SYNC
while self.bytes_availa... |
def pass_time(self, t):
"""Non-blocking time-out for ``t`` seconds."""
cont = time.time() + t
while time.time() < cont:
time.sleep(0)
def setup_layout(self, board_layout):
"""
Setup the Pin instances based on the given board layout.
"""
# Create pin in... | This code initializes a serial connection to a hardware device (like an Arduino), waits for it to reset, configures the device's name/layout, and reads initial firmware data. It sets up communication parameters, handles auto-configuration if no layout is provided, and iterates through received bytes to process initial ... | def __init__(self, port, layout=None, baudrate=57600, name=None, timeout=None):
self.sp = serial.Serial(port, baudrate, timeout=timeout)
# Allow 5 secs for Arduino's auto-reset to happen
# Alas, Firmata blinks its version before printing it to serial
# For 2.3, even 5 seconds might not b... |
def log_message(message):
print(message)
with open(LOG_FILE, 'a') as log_file:
log_file.write(message + '\n')
def handle_get(path, client_connection):
if path.startswith("/messages"):
try:
# Assuming path format is "/messages" or "/messages/{id}"
# Return all messages... | This function handles incoming HTTP client connections by checking connection limits, parsing requests, dispatching to appropriate handlers (GET/POST/PUT/DELETE), logging actions, and ensuring proper cleanup by decrementing the connection counter and closing the socket after processing. | def handle_client_connection(client_connection, client_address):
global active_connections
print("num active connections: " + str(active_connections) + "\n")
if active_connections >= max_connections:
print("exceeded server load of max #connections :(")
client_connection.close()
retur... |
def getTopXCatagoricalData(attr ,x ,expectedValue):
Catagoricals = helperFunctions.getResultOfQuery(metaDBCon, f"Select val2, IDF from {attr}IDF where val1 = {expectedValue} order by IDF desc;")
result = []
for i in range(len(Catagoricals)):
if (len(result) < x):
helpers = (helperFunctions.getResultOfQuery(main... | This code retrieves the top K cars based on weighted scores from multiple attributes, handling both categorical and numerical data. It calculates QF scores, aggregates top candidates, and dynamically updates max values to select the highest-ranked cars efficiently. | def topK(attrNeededValuess,k):
x = len(attrNeededValuess)*k*1.5 + 5
topK = []
categorischeIDFDictionairy = {}
attrList = []
QFWights = []
for attr in attrNeededValuess:
if attr[0] in categorischeData:
QFWights.append(helperFunctions.getResultOfQuery(metaDBCon, f"SELECT QFScore FROM {attr[0]}QF WHERE val = {a... |
def argparser():
parser = argparse.ArgumentParser(description="Issues a batch of requests.")
parser.add_argument(
"-o", "--hostname", type=str, default="localhost",
metavar="localhost", help="Hostname to connect to."
)
parser.add_argument(
"-p", "--port", type=int,
metava... | The code processes a sequence of network-related events (e.g., LOAD, UNLOAD, SEND_BODY) using epoll for I/O multiplexing. It parses command-line arguments, manages request creation, sends/receives data over sockets, and logs operations. The main task is to execute a predefined workflow of HTTP-like operations, handling... | def main():
requests = {}
receivers = {}
args = argparser()
poller = select.epoll()
basename = f"{args.hostname}:{args.port}"
outdir = ""
if len(args.dir) > 0:
outdir = args.dir
try:
os.mkdir(outdir)
except:
pass
for event in toml.load(ar... |
def update_lists(self):
self.list1.clear()
self.list2.clear()
for id_data in self.get_fdi_ids():
item = id_data['name']
id = id_data['ID']
self.list1.addItem(f'{id} - {item}')
already_annotated = set(self.associations.keys())
for id_data in ... | The code removes associations from a dictionary based on selected items in a list. It checks if selected items contain ' > ', splits them to extract IDs, deletes corresponding entries from the associations dictionary, then updates UI elements, saves changes, and reloads data. | def reset_assoc(self,):
selected_items_list2 = self.list2.selectedItems()
if len(selected_items_list2) == 0:
return
for item2 in selected_items_list2:
item2 = item2.text()
if ' > ' not in item2:
continue
print(f"selected: {item2... |
def _check_keydown_event(self, event):
"""Function react on pressing a keyboard key and let the spaceship move
left or right, fire a bullet or exit the game"""
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship... | This function handles user input events in a Pygame game. It detects quit requests, keyboard presses/releases, and mouse clicks. For mouse clicks, it retrieves the cursor position and triggers the play button functionality. The event checks enable game control, movement, and interaction with game elements like buttons. | def _check_events(self):
"""React on events during the game. Check for proper system react when player want to quit the game,
press up/down button and get mouse cursor position"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
el... |
def _check_fleet_edges(self):
"""Check if the edge of screen is reached and change fleet direction"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
"""Update player lives when reac... | The function updates alien positions, checks for collisions between the player's ship and aliens, and determines if aliens have reached the screen's bottom to trigger game loss or life deduction. It calls methods to handle edge detection, alien movement, collision response, and bottom-bound checks for game state update... | def _update_aliens(self):
"""Update alien objects location. Check for alien and player ship objets collision or
if alien fleet reached the bottom of the screen for player to loose live or game"""
self._check_fleet_edges()
self.aliens.update()
if pygame.sprite.spritecollideany(se... |
def _check_events(self):
"""React on events during the game. Check for proper system react when player want to quit the game,
press up/down button and get mouse cursor position"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
el... | The code runs the main game loop, continuously checking for events, updating game elements (ship, bullets, aliens) when the game is active, and refreshing the screen to render changes. It maintains gameplay flow by handling user input, object movement, bullet behavior, alien updates, and screen display in an infinite l... | def run_game(self):
""" Run main loop"""
while True:
self._check_events()
if self.stats.game_active:
self._check_events()
self.ship.update()
self.bullets.update()
self._update_bullets()
self._update_... |
def isSufficientMaterial(board):
whiteMaterial = getMaterial(board,1)
blackMaterial = getMaterial(board,-1)
if blackMaterial[:5] == (0,0,0,0,0) and whiteMaterial[:5] == (0,0,0,0,0):
return False
if (whiteMaterial[:5] == (0,1,0,0,0) and blackMaterial[:5] == (0,0,0,0,0)) or (whiteMaterial[:5] == (... | This function generates legal chess moves for a player, considering rules like check, threefold repetition, 50-move draw, and insufficient material. It checks each piece's possible moves, filters out those leaving the king in check, and returns valid moves or a status indicating checkmate/stalemate. | def getLegalMoves(board,player,castle,en,halfmove,history):
attack_mask = 0
legalMoves=[]
for move in set(history):
if history.count(move) > 2:
return [2,[]]
if halfmove == 100:
return [2,[]]
if not isSufficientMaterial(board):
return [2,[]]
... |
def _other_i_state(self):
assert self.i_state in [-1, 1]
if self.i_state == -1:
return 1
else:
return -1
def handle_one_piece_main_ljo(self, piece_type):
game = self.game
if self.ljo_state == LJO_INDETERMINATE_ORDER:
order = self._determine_ljo... | This code handles a Tetris-like piece's rotation and movement based on its type. It processes 'I', 'L/J/O', and 'S/T/Z' pieces differently: rotating/hard-dropping the I-piece, using specialized methods for L/J/O, and state-driven transitions for S/T/Z. If no valid transition exists for S/T/Z, it swaps pieces and retrie... | def handle_one_piece(self):
game = self.game
piece = game.piece
phase = 'main' # 'main' | 'rebalance'
if phase == 'main':
if piece.type == MinoType.I:
game.rotate(self.i_state)
game.hard_drop()
self.i_state = self._other_i_stat... |
def get_days(request):
"""
It sets the timeframe for the calendar and
the classes that will be displayed.
"""
today = date.today()
start = today - timedelta(days=today.weekday())
end = start + timedelta(days=13)
dates = [start + timedelta(days=i) for i in range((end-start).days+1)]
r... | The code handles booking yoga classes by rendering a template with time slots, days, and available classes. It processes POST requests to validate and save reservations, associating them with the user. The function prepares context data for the template, including forms and class availability, to enable users to create... | def book(request):
"""
It renders book_class and passes classes to the template.
It passes days and time_slots to the
template to create and update the calendar.
It renders the Reservation form and handles validation.
"""
time_slots = ["9:00 - 10:00", "10:00 - 11:00",
"11:0... |
def generate_circle_samples(nb_samples, seed=42):
"""Generate data as asked in the project description.
Args:
nb_samples (int): How many samples are required
seed (int, optional): Seed of random generator, for reproducibility. Defaults to 42.
Returns:
(samples, labels): (2D points ... | The code compares the performance of SGD (without and with momentum) and Adam optimizers on a circular boundary classification task. It trains models with varying learning rates, evaluates F1 scores over epochs, and identifies the best-performing learning rate for each optimizer. Results are visualized and printed, hig... | def compare_optims(nb_samples=1000, nb_epochs=70, sgd_momentum=0.9, use_sigmoid=False, ):
"""Simple first experiment with circular boundary
Args:
nb_samples (int, optional): Number of samples for train/test. Defaults to 1000.
nb_epochs (int, optional): Number of training epochs. Defaults to 300... |
def generate_circle_samples(nb_samples, seed=42):
"""Generate data as asked in the project description.
Args:
nb_samples (int): How many samples are required
seed (int, optional): Seed of random generator, for reproducibility. Defaults to 42.
Returns:
(samples, labels): (2D points ... | The main task of the code is to generate circularly distributed data samples, visualize them, and compare different optimization algorithms. It creates 1000 labeled samples using `generate_circle_samples`, plots them with `plot_circle_samples`, and executes `compare_optims` to evaluate optimizer performance. This likel... | def main():
samples, labels = generate_circle_samples(1000)
plot_circle_samples(samples, labels)
compare_optims() |
def build_team_from_pokemon(self, pokemon):
"""
Builds a team with the given pokemon by choosing counters to it's weaknesses
"""
print(f"Building a team around {pokemon}")
lead_weaknesses = self.species_counters_dict[pokemon]
# Determine pokemon weakness typings
... | The code generates a Pokémon team centered around a randomly selected lead Pokémon from an anti-meta list. If no specific lead is provided, it selects a lead, identifies counters for its weaknesses, and constructs a team with those counters. If a user-specified lead is given, it builds a team around that Pokémon, adjus... | def recommend_team(self, chosen_pokemon=None, position="lead"):
"""
Returns a team around a random lead mon picked from the anti-meta list.
After picking a lead, the two back pokemon are chosen as counters to the lead's weaknesses
"""
if chosen_pokemon:
if position ==... |
def adjacent_nlets(q, n):
return zip(*[q[c:] + q[:c] for c in range(n)])
def normalized(v):
return v/np.linalg.norm(v)
def merge(a, b):
shared = [p for p in indexable(b) if p in indexable(a)]
assert len(shared) == 2, "Shapes share {0} points, not 2".format(len(shared))
def rotated(f):
f_i =... | The code merges coplanar faces by checking adjacent edges and comparing face normals. It uses a FaceTracker to store faces, identifies coplanar pairs via dot product checks, merges them, and updates the tracker. The goal is to combine adjacent, coplanar faces into unified surfaces for 3D mesh simplification or optimiza... | def merge_coplanar_faces(faces, face_normals):
tracker = FaceTracker()
for face, norm in zip(map(list, faces), face_normals):
for e in adjacent_nlets(face, 2):
try:
face_mate, norm_mate = tracker.get(e)
if np.isclose(np.dot(normalized(norm), normalized(norm_ma... |
def indexable(a):
try:
return tuple(indexable(v) for v in a)
except TypeError:
return a
def adjacent_nlets(q, n):
return zip(*[q[c:] + q[:c] for c in range(n)])
def _keyify(self, point_pair):
return frozenset(indexable(point_pair)) | This method removes a specified face from the object by deleting it from the faces list and corresponding normals, then updates adjacent point keys in two dictionaries by removing entries linked to the face's adjacent elements, while handling potential KeyErrors gracefully. | def remove(self, face):
if indexable(face) in indexable(self.faces):
i = indexable(self.faces).index(indexable(face))
del self.faces[i]
del self.normals[i]
for e in adjacent_nlets(face, 2):
try:
del self._point_keys_to_face[self... |
def adjacent_nlets(q, n):
return zip(*[q[c:] + q[:c] for c in range(n)])
def angle_between_three_points_2d(a, b, c):
return angle_between_three_points(np.append(a, 0.0), np.append(b, 0.0), np.append(c, 0.0),
np.array([0.0, 0.0, 1.0]))
def normalized(v):
return v/np.lina... | This function adjusts a 2D polygon's vertices by applying uneven offsets. It converts input points to arrays, iterates through adjacent point groups, calculates angles between points, and updates vertex positions using offset values scaled by normalized vectors and sine of computed angles to achieve non-uniform polygon... | def uneven_offset_polygon_2d(points, offsets):
adjusted = [np.array([float(v) for v in p]) for p in points]
for a_i, a, b_i, b, c_i, c, d_i, d in map(chain.from_iterable, adjacent_nlets(list(enumerate(points)), 4)):
cba = angle_between_three_points_2d(c, b, a)
adjusted[b_i] += offsets[b_i] * nor... |
def disas_single(code, addr):
md = Cs(CS_ARCH_X86, CS_MODE_32)
for i in md.disasm(code, addr):
return (i.address, i.mnemonic, i.op_str)
def log(txt):
if DEBUG:
print(txt)
def exception_handler_cc(self, mu):
''' emulates exception handler
'''
keys = ['A', 'B', 'C', 'D'... | This function hooks into memory execution by reading and disassembling instructions at a given address. It logs the disassembled opcode (address, mnemonic, operands) and checks for specific opcodes: if 'int3' (0xcc), it triggers an exception handler; if 'hlt' (0xf4), it prints "win". The main task is to monitor and res... | def hook_code(self, mu, addr, size, user_data):
mem = mu.mem_read(addr, size)
dis = disas_single(mem, addr)
addr, mnemonic, op_str = dis
log("0x%x\t%s\t%s"%(addr, mnemonic, op_str))
# int3
if mem == b'\xcc':
self.exception_handler_cc(mu)
# hlt
... |
def find_background(img):
h, s, v = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))
blue = [0.5 * 180, 0.65 * 180]
background = threshold_in_range(h, blue)
background = cv2.morphologyEx(background, cv2.MORPH_DILATE, np.ones((7, 7), np.uint8))
contours, hierarchy = cv2.findContours(background, cv2.RE... | The function `get_board_and_background` segments an image's foreground (board) by analyzing contours and convex hulls. It generates a mask to isolate the background, using the original contour if it covers more than half the convex hull area; otherwise, it uses the convex hull. The function then returns the image with ... | def get_board_and_background(img):
contour = find_background(img)
img_size = img.shape[:2]
mask = np.zeros(img_size, dtype=np.uint8)
contour_hull = cv2.convexHull(contour, False)
# If the contour is not solid draw the covex hull instead
if cv2.contourArea(contour) > 0.5 * cv2.contourArea(contour... |
def get_board_and_background(img):
contour = find_background(img)
img_size = img.shape[:2]
mask = np.zeros(img_size, dtype=np.uint8)
contour_hull = cv2.convexHull(contour, False)
# If the contour is not solid draw the covex hull instead
if cv2.contourArea(contour) > 0.5 * cv2.contourArea(contour... | The code processes an image to identify and extract hexagonal grid elements. It first separates the board and background, detects edges using Canny, identifies markers, and applies watershed segmentation to delineate hexagons, returning the segmented hexagonal regions. | def get_hex_grid(img):
board, background = get_board_and_background(img)
canny = get_canny_edges(board)
markers = get_markers(board)
hexes = get_watershed(canny, markers, background)
return hexes |
def get_board_and_background(img):
contour = find_background(img)
img_size = img.shape[:2]
mask = np.zeros(img_size, dtype=np.uint8)
contour_hull = cv2.convexHull(contour, False)
# If the contour is not solid draw the covex hull instead
if cv2.contourArea(contour) > 0.5 * cv2.contourArea(contour... | The code detects movement differences between two images by subtracting them, thresholding the result to identify contours, calculating their centers, mapping these to predefined vertices, and publishing the detected piece and vertex index as a message. It visualizes the difference mask and sends data via a publisher. | def find_and_send_moves(before, after):
before, background = get_board_and_background(before)
after = cut_background(after, background)
# subtract to get difference
diff = cv2.subtract(before, after)
# create grayscale of diff
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
# create a mask f... |
def get_hex_grid(img):
board, background = get_board_and_background(img)
canny = get_canny_edges(board)
markers = get_markers(board)
hexes = get_watershed(canny, markers, background)
return hexes
def get_vertices(watershed_hexes):
corner_probs = cv2.cornerHarris(watershed_hexes,21,23,0.04)
... | The code captures video from a webcam, processes the first frame to detect a hexagonal grid and its vertices, displays them, and waits for user input to capture 'before' and 'after' images. It compares these images to detect and send moves, using OpenCV for image processing and display. | def main():
# Initialize video stream
vid = cv2.VideoCapture(1)
time.sleep(1)
# Take first image to initialize vertices data structures
_, img = vid.read()
hexes = get_hex_grid(img)
cv2.imshow('hexes', hexes)
vertices_img, vertices = get_vertices(hexes)
global vertex_list
vertex... |
def Ep(image, px, py, sx, sy):
result = 0.0
spx = sx - px
spy = sy - py
d = np.hypot(spx, spy)
if d == 0.0: return 0.0
num_steps = int(np.ceil(d))
num_steps = max(1, min(10, num_steps))
step_x = spx / num_steps
step_y = spy / num_steps
h, w = image.shape[:2]
for i in r... | The main task of the code is to gather foreground and background samples around each unknown pixel in a trimap, compute their energy-based cost, and update the alpha matte and color estimates using the optimal foreground-background pair. It uses angular sampling to collect neighboring pixels, evaluates their contributi... | def sample_gathering(
gathering_F,
gathering_B,
gathering_alpha,
image,
trimap,
num_angles,
eN,
eA,
ef,
eb,
Np_radius,
):
h, w = trimap.shape
max_steps = 2 * max(w, h)
for y, x in pndindex((h, w)):
fg_samples = np.zeros((num_angles, 3), dtype=np.float32)... |
def expand_trimap(expanded_trimap, trimap, image, k_i, k_c):
# NB: Description in paper does not match published test images.
# The radius appears to be larger and expanded trimap is sparser.
h, w = trimap.shape
for y, x in pndindex((h, w)):
if trimap[y, x] == 0 or trimap[y, x] == 1: continue
... | The function `estimate_alpha_sm` estimates an alpha matte from an input image and trimap using Shared Matting (Gastal & Oliveira, 2010). It expands the trimap, computes foreground/background samples via weighted cost functions, refines these samples, and applies local smoothing to produce a final alpha matte. Optional ... | def estimate_alpha_sm(
image,
trimap,
return_foreground_background=False,
trimap_expansion_radius=10,
trimap_expansion_threshold=0.02,
sample_gathering_angles=4,
sample_gathering_weights=(3.0, 2.0, 1.0, 4.0),
sample_gathering_Np_radius=1,
sample_refinement_radius=5,
local_smoothi... |
def read_data(csv_file):
"""Read the CSV file and generate datasets as neseted np array"""
with open(csv_file, 'r') as f:
reader = csv.reader(f)
dataset_list = list(reader)
# dataset_list = weighted_by_frequency(dataset_list)
# dataset_list = np.array(dataset_list)
# change string ... | The code evaluates the performance of a KNN classifier on three text feature representations (TF, IDF, n-gram) by reducing dimensionality with PCA, calculating TPR/FPR across thresholds, and plotting ROC curves to compare detection capabilities against attack/normal datasets. | def main():
dataset_list_normal_tf = read_data(dataset_file_normal_tf)
dataset_list_attack_tf = read_data(dataset_file_attack_tf)
dataset_list_normal_idf = read_data(dataset_file_normal_idf)
dataset_list_attack_idf = read_data(dataset_file_attack_idf)
dataset_list_normal_ngram = read_data(dataset_f... |
def validate_input(self, player, words):
return False if len(player) != 5 else words.word.str.contains(player).any()
def set_update(self):
self.to_update = {
key: 1 for key in self.players
}
def check_word(self, player) -> list:
self.last_update = 0x01
if player == se... | The code processes a player's move in a game by validating input, decrementing lives, switching to the next player, updating the game state, and checking if the move is correct. It returns -1 for invalid input or the result of `check_word(move)` to determine the move's validity. | def make_move(self, move, words):
if not self.validate_input(move, words):
return -1
self.lives -= 1
self.current_player = (self.current_player + 1) % len(self.players)
self.set_update()
return self.check_word(move) |
def speak(audio) :
engine.say(audio)
engine.runAndWait()
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
... | The function detects user sadness by prompting for input, updates the sentiment score using the response, checks the sentiment level with specific emails, and returns the adjusted score. | def emotion_sad(Sentiment):
speak("Hey ! You seem a little sad ? Wats the matter")
response = takeCommand().lower()
Sentiment+=(S.get_Sentiment(response)*10)
check_Sentiment_level(Sentiment,'ahjsm@example.com','jlxug@example.com')
return Sentiment |
def speak(audio) :
engine.say(audio)
engine.runAndWait()
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
... | The main task of the code is to detect and analyze user anger through dialogue, update a sentiment score based on the response, and trigger a sentiment level check. It prompts the user about their anger, captures their input, adjusts the sentiment value using a sentiment analysis function, and passes the updated score ... | def emotion_angry(Sentiment):
speak("Hey ! You seem angry ? Wats the matter")
response = takeCommand().lower()
Sentiment+=(S.get_Sentiment(response)*5)
check_Sentiment_level(Sentiment,'ahjsm@example.com','jlxug@example.com')
return Sentiment |
def populateRequiredDate(element):
print(type(element))
element.click()
pickRandomDate()
label = findElementsXpath(ELEMENT_LABEL, element)[0].text
requiredField.append(label)
print(label)
def populateRequiredInput(element):
label = findElementsXpath(ELEMENT_LABEL, element)[0].text
print(... | The function `populateReqFields` dispatches to specific handlers to populate form fields based on the `dict_key` value. It uses `ActionChains` for interactions, calling methods like `populateRequiredDate`, `populateRequiredInput`, etc., to fill date, input, text, select, or radio fields. The task is to automate data en... | def populateReqFields(dict_key, element):
actions = ActionChains(driver)
if(dict_key=='requiredDateField'):
populateRequiredDate(element)
elif(dict_key=='requiredInputField'):
populateRequiredInput(element)
elif(dict_key=='requiredTextField'):
populateRequiredTextField(element)
... |
def traverseAdvSrchElements(args):
global appErrors
action = ActionChains(driver)
time.sleep(1)
for element in listOfActions:
checkAllDictElements(element,args)
time.sleep(2)
applyButton = checkElementToBeClickable(APPLY_BUTTON,"xpath")
action.move_to_element(applyButton).cli... | The main task of the code is to test an advanced search functionality by traversing elements within a specified range (1-29), checking if claims are found, and logging the status (found/not found) into a CSV file named 'advSearchtest1.csv' using a pandas-based printing function. The global variable 'elementFoundStatus'... | def test1():
global elementFoundStatus
args = {
"From" : 1,
"To" : 29
}
claimsLength = traverseAdvSrchElements(args)
elementFoundStatus = checkTestStatus(claimsLength)
print(elementFoundStatus)
print_to_pandas(appErrors+elementFoundStatus+'advSearchtest1.csv') |
def traverseAdvSrchElements(args):
global appErrors
action = ActionChains(driver)
time.sleep(1)
for element in listOfActions:
checkAllDictElements(element,args)
time.sleep(2)
applyButton = checkElementToBeClickable(APPLY_BUTTON,"xpath")
action.move_to_element(applyButton).cli... | The code's main task is to test an advanced search function by setting parameters ("From" and "To" ranges), traversing elements, checking if claims were found, updating a global status variable, and logging the result along with errors into a CSV file named 'advSearchtest2.csv' using a pandas-based function. | def test2():
global elementFoundStatus
args = {
"From" : 1,
"To" : 29,
"FROM" : 29,
"TO" : 1
}
claimsLength = traverseAdvSrchElements(args)
elementFoundStatus = checkTestStatus(claimsLength)
print(elementFoundStatus)
print_to_pandas(appErrors+elementFoundStat... |
def traverseAdvSrchElements(args):
global appErrors
action = ActionChains(driver)
time.sleep(1)
for element in listOfActions:
checkAllDictElements(element,args)
time.sleep(2)
applyButton = checkElementToBeClickable(APPLY_BUTTON,"xpath")
action.move_to_element(applyButton).cli... | The main task of the code is to test an advanced search functionality by passing predefined parameters ("Vehicle year" and "Claim number"), checking the search results' status, and exporting the status along with potential errors to a CSV file for analysis. | def test3():
global elementFoundStatus
args = {
"Vehicle year" : "2010",
"Claim number" : "00118310V2"
}
claimsLength = traverseAdvSrchElements(args)
elementFoundStatus = checkTestStatus(claimsLength)
print(elementFoundStatus)
print_to_pandas(appErrors+elementFoundStatus+'adv... |
def traverseAdvSrchElements(args):
global appErrors
action = ActionChains(driver)
time.sleep(1)
for element in listOfActions:
checkAllDictElements(element,args)
time.sleep(2)
applyButton = checkElementToBeClickable(APPLY_BUTTON,"xpath")
action.move_to_element(applyButton).cli... | The code tests an advanced search function by passing specific parameters ("Vehicle year" and "Claim number"), processes the results via `traverseAdvSrchElements`, checks the status with `checkTestStatus`, and logs the outcome (including errors) into a CSV file named 'advSearchtest4.csv' using `print_to_pandas`. The gl... | def test4():
global elementFoundStatus
args = {
"Vehicle year" : "20102010",
"Claim number" : "00118310V2"
}
claimsLength = traverseAdvSrchElements(args)
elementFoundStatus = checkTestStatus(claimsLength)
print(elementFoundStatus)
print_to_pandas(appErrors+elementFoundStatus+... |
def traverseAdvSrchElements(args):
global appErrors
action = ActionChains(driver)
time.sleep(1)
for element in listOfActions:
checkAllDictElements(element,args)
time.sleep(2)
applyButton = checkElementToBeClickable(APPLY_BUTTON,"xpath")
action.move_to_element(applyButton).cli... | The main task of the code is to test an advanced search function by passing predefined parameters ("Vehicle year" and "Claim number"), evaluate the search results' length, check the test status, and log the status to a CSV file using pandas. It uses global variables and external functions to process inputs and record o... | def test5():
global elementFoundStatus
args = {
"Vehicle year" : "201020102010",
"Claim number" : "00118310V2"
}
claimsLength = traverseAdvSrchElements(args)
elementFoundStatus = checkTestStatus(claimsLength)
print(elementFoundStatus)
print_to_pandas(appErrors+elementFoundSta... |
def traverseAdvSrchElements(args):
global appErrors
action = ActionChains(driver)
time.sleep(1)
for element in listOfActions:
checkAllDictElements(element,args)
time.sleep(2)
applyButton = checkElementToBeClickable(APPLY_BUTTON,"xpath")
action.move_to_element(applyButton).cli... | The main task of the code is to test an advanced search feature for "Repair facility" location type by traversing elements, checking the test status based on the number of claims, and logging the result (elementFoundStatus) into a CSV file named 'advSearchtest6.csv' using a helper function. The global variable elementF... | def test6():
global elementFoundStatus
args = {
"Location type" : "Repair facility"
}
claimsLength = traverseAdvSrchElements(args)
elementFoundStatus = checkTestStatus(claimsLength)
print(elementFoundStatus)
print_to_pandas(appErrors+elementFoundStatus+'advSearchtest6.csv') |
def traverseAdvSrchElements(args):
global appErrors
action = ActionChains(driver)
time.sleep(1)
for element in listOfActions:
checkAllDictElements(element,args)
time.sleep(2)
applyButton = checkElementToBeClickable(APPLY_BUTTON,"xpath")
action.move_to_element(applyButton).cli... | The code tests a claims search functionality by setting specific criteria ("Claim status": "New", "Owner type": "Claimant"), retrieving the number of claims, checking if the test passes based on the result length, printing the status, and appending the outcome to a CSV file named 'advSearchtest7.csv' for logging. | def test7():
global elementFoundStatus
args = {
"Claim status" : "New",
"Owner type" : "Claimant"
}
claimsLength = traverseAdvSrchElements(args)
elementFoundStatus = checkTestStatus(claimsLength)
print(elementFoundStatus)
print_to_pandas(appErrors+elementFoundStatus+'advSearc... |
def find_searchClaims():
action = ActionChains(driver)
time.sleep(2)
print('function call')
searchContainer = checkPresenceOfElement("css-15oyjs9-container", "class")
searchBar = searchContainer.find_element_by_class_name('css-1fjg8gh-control')
action.reset_actions()
action.move_to_element(s... | The code automates testing by interacting with a web UI to search claims, select random options, perform actions, and log results. It identifies elements via XPath, filters options, clicks on selected items, generates random arguments, adds notes, and exports data to a JSON file. The process includes refreshing pages a... | def start_testing():
searchBar = find_searchClaims()
options = [x.text for x in checkPresenceOfAllElements("//div[@class = ' css-1ljkvdv']"
+"//div[starts-with(@id, 'react')]"
+"//div[@class = 'claim-option-header']", "xpath")]
constraint5 = len(options) >= 5 and 5 or len(options)
options = rand... |
def find_allRequiredElements():
reqInput = findElementsXpath(REQUIRED_FIELDS+REQUIRED_INPUT_FIELD)
reqSelect = findElementsXpath(REQUIRED_FIELDS+REQUIRED_SELECT_FIELD)
reqRB = findElementsXpath(REQUIRED_FIELDS+REQUIRED_RB_FIELD)
reqText = findElementsXpath(REQUIRED_FIELDS+REQUIRED_TEXT_FIELD)
reqDat... | The main task of the code is to automate form submission by traversing a dictionary to populate required fields, clicking a "Create" button, waiting for elements, handling errors, and updating global state variables (counter, checkOtherPhone) for subsequent operations. | def traverseDom():
global counter
global checkOtherPhone
find_allRequiredElements()
for i in my_dict.items():
for a in i[1]:
populateReqFields(i[0],a)
create = WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,
"//button[con... |
def test1():
global elementFoundStatus
args = {
"From" : 1,
"To" : 29
}
claimsLength = traverseAdvSrchElements(args)
elementFoundStatus = checkTestStatus(claimsLength)
print(elementFoundStatus)
print_to_pandas(appErrors+elementFoundStatus+'advSearchtest1.csv')
def test2():
... | The function `test_dicts(x)` returns a value from a predefined dictionary where keys are strings '1' to '7' and values are results of corresponding test functions (`test1()` to `test7()`). It uses `.get(x, 1)` to retrieve the value associated with key `x`; if `x` is not found, it defaults to `1`. The main task is to dy... | def test_dicts(x):
return {
'1': test1(),
'2': test2(),
'3': test3(),
'4': test4(),
"5": test5(),
'6': test6(),
'7': test7()
}.get(x, 1) |
def findNumOfCreatedClaims():
driver.get("https://clarity-staging.acdcorp.com/adjuster/claims/all/my-recent-claims")
numberOfClaimsElement = WebDriverWait(driver,20).until(
EC.visibility_of_element_located((By.XPATH,"//span[@class = 'index-tracker']")))
print(numberOfClaimsElement.text)
return (... | The main task of the code is to automate testing of a claim creation process in a web application. It retrieves the number of existing claims, navigates to create new claims, iterates through multiple attempts to validate claim status, traverses DOM elements, collects data into lists, and exports results to a JSON file... | def startTesting():
global numOfCreatedClaims
numOfCreatedClaims = findNumOfCreatedClaims()
print("num of created claims iznosi"+ str(numOfCreatedClaims))
time.sleep(2)
findElementsXpath("//a[@title = 'Create a new claim']")[0].click()
time.sleep(2)
for i in range(0, numOfAttempts):
... |
def find_searchClaims():
action = ActionChains(driver)
time.sleep(2)
print('function call')
searchContainer = checkPresenceOfElement("css-15oyjs9-container", "class")
searchBar = searchContainer.find_element_by_class_name('css-1fjg8gh-control')
action.reset_actions()
action.move_to_element(s... | The main task of the code is to test an advanced search feature by locating a search bar, clicking the "Advanced search" link, populating a dictionary with data via `putInDict()`, validating it with `test_dicts()`, and exporting the results to a JSON file named 'advancedSearch.json' in the specified directory. | def testAdvancedSearch():
searchBar = find_searchClaims()
time.sleep(3)
advancedSearch = WebDriverWait(driver,20).until(EC.element_to_be_clickable(
(By.LINK_TEXT,"Advanced search"))).click()
putInDict()
time.sleep(2)
test_dicts(str(1))
dumpToJson(os.getcwd()+'/Error_output/advancedSe... |
def get_disease_sets(file_path):
set_dict = {} #{dis_pair: rr}
disease_genes_dict = {} #{disease: [gene_1, gene_2, ...]}
f = open(file_path, "r")
head = True
for line in f:
if head:
head = False
continue
row = line.strip().split("\t")
d... | The main task of the code is to evaluate a classification model on disease gene pairs using graph-based features derived from a human interactome. It compares accuracy before and after applying a feature selection method (BSE) to optimize dimensions for SVM classification. The code processes train/test datasets, extrac... | def main():
# from command line arguments
rr_dataset = sys.argv[1]
method = sys.argv[2]
#------------------------Pre_setting_block_start---------------------------#
input_folder = 'input'
edge_list_file_path = f'{input_folder}/interactom_edges.txt' # stores the edges for the largest conne... |
def get(self, url):
""" Loads a given url with the chromedriver. """
self.driver.get(url)
def accept_privacy_notices(self):
notice_clicked = False
while not notice_clicked:
log("Checking for notices")
# Larger privacy notice
if notice_clicked := self.... | The main task of the code is to load a MyAnimeList anime page using a given MAL ID, accept privacy notices, and check if a specific element (`.js-scrollfix-bottom .ac`) exists on the page, returning `True` or `False` accordingly. It automates web navigation and element verification for anime page accessibility. | def load_anime_page(self, mal_id: str) -> bool:
log("Loading anime page")
self.get(f"https://myanimelist.net/anime/{mal_id}")
self.accept_privacy_notices()
log("Checking if page loaded")
return self.element_exists('.js-scrollfix-bottom .ac') |
def logged_in(self, wait: bool = True) -> bool:
log("Checking if login was successful")
return self.element_exists(".header-profile-link", wait)
def apply_cookies(self):
self.get(f"https://myanimelist.net/")
self.driver.add_cookie({'name': 'm_gdpr_mdl', 'value': '1'})
def get(self, url):... | The code attempts to log in to MyAnimeList using provided credentials, retrying up to 5 times if initially unsuccessful. It applies cookies, navigates to the login page, inputs the username and password, and submits the form. If login succeeds, it logs the success and returns True; otherwise, returns False after all at... | def login_myanimelist(self, mal_username: str, mal_password: str) -> bool:
if self.logged_in(wait = False):
return True
for i in range(1, 6):
log(f"Logging into MyAnimeList attempt: {i}")
self.apply_cookies()
self.get(f"https://myanimelist.net/login.php?f... |
def create_complete_board():
board = np.zeros((8, 8))
for i in range(len(board)):
for j in range(len(board[0])):
# place tree
if random.uniform(0,1) < 0.3 and tent_available_space(board, i, j):
board[i][j] = 1
# place tent
available... | The code generates 250,000 puzzle-solution pairs by creating a board, rotating it three times (90° increments), calculating constraints for each rotation, consolidating data for both solved and unsolved versions, and saving them as CSV rows. It iteratively builds lists of unsolved and solved boards, then combines them ... | def main():
all_s_boards = []
all_u_boards = []
for _ in range(250000):
# Get all boards from this iteration
board1, constraints1 = create_complete_board()
board2 = rotate_board_90_degrees(board1)
constraints2 = calculate_constraints(board2)
board3 = rotate_board_90_d... |
def fetch_disk_usage(server_name, disk_path):
total_space = int(input('Enter Total Space (in MB): '))
used_space = int(input('Enter Used Space (in MB): '))
free_space = total_space - used_space
insert_disk_usage(server_name, disk_path, total_space, used_space, free_space)
def get_disk_usage(server_name)... | The code defines a menu-driven Disk Space Management Tool, allowing users to add, view, update, delete, analyze disk usage data, and get cleanup suggestions. It loops to display options, processes user input, and calls respective functions for data operations, providing an interactive interface for managing server disk... | def menu():
print("Disk Space Management Tool")
while True:
print("\n1. Add Disk Usage Data")
print("2. View Disk Usage Data")
print("3. Update Disk Usage Data")
print("4. Delete Disk Usage Data")
print("5. Analyze Disk Space Usage")
print("6. Suggest Cleanup Act... |
def execute_cmd(self, request, cmd_args):
LOG.info(cmd_args)
with subprocess.Popen(
cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE
) as proc:
# at this point the subprocess is done
# Here we call the followup processing function specific to that terr... | (The function recreates a Terraform environment for an organization by deleting and re-creating a directory, downloading specified Terraform files from an S3 bucket, initializing and validating the Terraform configuration, and ensuring the correct workspace is created and selected. If the download fails, it logs errors... | def recreate_env_for_org(self,request):
LOG.info("%s recreating dir, downloading and validating terraform files -------",request.org.org_name)
destination_dir = os.getcwd() + "/" + request.org.org_name + "/terraform"
cmd_args = ["rm", "-rf", destination_dir]
yield from self.execute_cmd(r... |
def update_refresh_node_name_table(self):
for i in range(self.ui.node_name_table.rowCount()):
self.ui.node_name_table.removeRow(0)
for node in self.node_list:
self.ui.node_name_table.insertRow(self.ui.node_name_table.rowCount())
item = QtWidgets.QTableWidgetItem(node... | This function updates a table based on the selected operation from a combo box. It first refreshes the node name table, then checks the current index of the combo box to determine which operation to perform: search/replace, insert/overwrite, or numbering. Each operation corresponds to a specific table modification meth... | def update_trim_toggle_select(self):
self.update_refresh_node_name_table()
index = self.ui.operation_combo.currentIndex()
if index == 0:
self.op_search_replace_table()
if index == 1:
self.op_insert_overwrite_table()
if index == 2:
self.op_numb... |
def _calculate_transportation_costs(self, solution) -> float:
"""K_t"""
supp_to_fact_trans_cost = self._calculate_partial_trans_cost(
paths=self._solution_splitter.get_suppliers_to_factories_partial_solution(solution),
num_of_entities_from=self._mscn.suppliers_count,
... | The code calculates the profit by subtracting transportation and startup costs from income, using helper methods to compute each component. It rounds the result to two decimal places and returns the profit. | def calculate(self, solution: List[float]) -> float:
tranportation_costs = self._calculate_transportation_costs(solution)
startup_costs = self._calculate_startup_costs(solution)
income = self._calculate_income(solution)
profit = round(income - startup_costs - tranportation_costs, 2)
... |
def _get_oauth_request_params(self, url, parameters={}, method="GET",
timestamp=None, nonce=None):
"""Returns the OAuth parameters as a dict for the resource request"""
if timestamp is None:
timestamp = int(time.time())
if nonce is None:
... | The main task of the code is to upload an image file to a specified SmugMug album using the PUT method. It validates required parameters (File, AlbumID), generates necessary headers including MD5 hashes and OAuth/session authentication, reads the binary file data, and sends the request. The function handles authenticat... | def images_upload(self, **kwargs):
"""Upload an image
Provide a file and album id to upload to a given album. Using PUT
method as described in the API Documentation.
http://wiki.smugmug.net/display/API/Uploading
"""
if "File" not in kwargs or "AlbumID" not in kwargs:
... |
def _get_oauth_request_params(self, url, parameters={}, method="GET",
timestamp=None, nonce=None):
"""Returns the OAuth parameters as a dict for the resource request"""
if timestamp is None:
timestamp = int(time.time())
if nonce is None:
... | This function makes an API request to Smugmug's service, constructing a URL with version and authentication parameters. It handles OAuth signing, API key authentication, or session ID authentication based on version and credentials. The function encodes parameters, sends the request, and returns the processed response. | def api_request(**kwargs):
"""Fetches the given API call"""
if secure:
url = "https://secure.smugmug.com/services/api/json/"
else:
url = "http://api.smugmug.com/services/api/json/"
url = url + self.api_version + "/"
kwargs.updat... |
def load_settings(self):
with open("./bot/settings.json", "r") as f:
data = json.loads(f.read())
self.trade_settings = {
k: TradeSettings(v, k) for k, v in data["pairs"].items()
}
self.trade_risk = data["trade_risk"]
def setup_logs(self):
s... | The main task of the code is to initialize a trading bot by loading settings, setting up logging, creating an Oanda API instance, and initializing a CandleManager for handling market data. It logs a "Bot started" message to both main and error logs, establishing foundational components for trading operations. | def __init__(self):
self.load_settings()
self.setup_logs()
self.api = OandaApi()
self.candle_manager = CandleManager(
self.api, self.trade_settings, self.log_message, Bot.GRANULARITY
)
self.log_to_main("Bot started")
self.log_to_error("Bot started") |
def __get_next_time(self) -> int:
return min(
np.inf
if not self.customers_ptr != len(self.customers)
else self.customers[self.customers_ptr].enter_time,
self.reception.get_next_event_time(),
self.__get_next_services(),
)
def plot_queue_length(... | This code simulates a system where customers arrive, are processed by services, and their times are tracked. The loop advances time, handles customer arrivals, processes service completions, updates queue/service times, and calculates metrics. It manages customer flow through reception and services, marking departures ... | def loop(self):
now = datetime.datetime.now()
print(now)
while True:
next = self.__get_next_time()
if next == np.inf:
break
self.timer.set_time(next)
# new customer enter the system
if (
self.customer... |
def rexmpls(lines) -> list:
igp = exigp(lines)
bgp = exbgp(lines, igp)
mpls = exmpls(lines, bgp)
mplsf = exvrfint(lines, mpls)
bdi = exbridgedomain(mplsf)
mplsf = exbdiinterface(lines, mplsf, bdi)
result = []
for r in mplsf:
result.append(r)
return result
def exfilter(lines, ... | The function `rexunifiedmpls` processes input lines by sequentially applying three filtering operations: `rexmpls`, `exfilter`, and `exumplsbgp`. It concatenates the results of these operations into a unified list, combining unprocessed MPLS data, filtered results, and BGP-related entries. The main task is to aggregate... | def rexunifiedmpls(lines) -> list:
result = []
umpls = rexmpls(lines)
fil = exfilter(lines, umpls)
ibgp = exumplsbgp(lines, fil)
result = result + umpls + fil + ibgp
return result |
def create_matrix(n):
matrix = np.zeros((n,n), dtype=np.complex64)
for x in range(n):
for y in range(n):
matrix[y][x] = (complex(x/n*4-2, y/n*4-2))
return matrix
def find_zeros(z, n):
for i in range(n):
z -= f(z)/df(z)
if round(abs(f(z)), 6) == 0:
return z
els... | The main task of the code is to compute and visualize a Newton's fractal by finding polynomial zeros, applying Newton's method on a larger matrix, tracing zero origins, and generating a colormap. It measures computation time and plots the resulting fractal pattern. | def main(n):
#find the zeros of the polynomial
matrix = create_matrix(100)
zeros = find_zeros(matrix, 100)
#create a new and larger matrix
matrix = create_matrix(n)
start = time()
#find the starting location of the zeros using newtons method
matrix = newtons_method(matrix, 100)
#ro... |
def build_adj_matrix(abstract_list, doc_list, triplet_list):
# Step 1: split the triplets into words
words, word_freq, entities, relation, stop_words = build_set(triplet_list)
# Step 3: using all the vocab to build an adjacent matrix
vocab_size = len(words)
adj_matrix = np.zeros((vocab_size, vocab... | The code constructs a graph representation of documents combined with knowledge graph (KG) data. It builds an adjacency matrix, extracts features and embeddings, splits data into training/validation/test masks, and creates a PyTorch Geometric Data object containing node features, edges, labels, and masks for downstream... | def build_graph(dataset):
abs_doc_list, KG_doc_list, KG_list = read_KG(args.dataset)
adj, pool_index, word_to_index = build_adj_matrix(abs_doc_list, KG_doc_list, KG_list)
edge_index = dense_to_sparse(adj)[0]
edge_attr = dense_to_sparse(adj)[1].float()
feature_matrix, emb_matrix = build_feature(... |
def get_matrices(m,x,y,n_inv):
lmax = len(x)
model,derivs = get_model_derivs(m,lmax)
r = y-model
lhs = derivs.T@n_inv@derivs
rhs = derivs.T@(n_inv@r)
chisq = r.T@n_inv@r
return chisq,lhs,rhs
def linv(mat,lam):
mat = mat+lam*np.diag(np.diag(mat))
return np.linalg.inv(mat)
def update_l... | This function iteratively refines a model parameter `m` by minimizing chi-squared using regularization (lambda). It updates `m` via matrix inversions and adjusts lambda based on convergence of chi-squared values. The process continues for `niter` iterations or until the chi-squared change falls below `chitol`, returnin... | def fit_lm(m,x,y,errs,niter=10,chitol=0.01):
t1 = time.time()
lam = 0
lmax = len(y)
n_inv = np.diag(errs**-1)
chisq,lhs,rhs = get_matrices(m,x,y,n_inv)
for i in range(niter):
lhs_inv = linv(lhs,lam)
dm = lhs_inv@rhs
m_new = m+dm
chisq_new,lhs_new,rhs_new = get_mat... |
def main1():
# LM fit (question 2)
pars_lm,curvature = fit_lm(pars,x,y,errs)
cov = np.linalg.inv(curvature)
p_errs_lm = np.diag(cov)
np.savetxt("planck_fit_params.txt",np.asarray([pars_lm,p_errs_lm]).T)
def main2():
# MCMC fit (question 3)
pfm = np.loadtxt("planck_fit_params.txt").T
pars... | The main task of the code is to execute the three functions main1(), main2(), and main3() sequentially within the main() function, likely coordinating their combined operations as part of a larger program structure. | def main():
main1()
main2()
main3() |
def random_choice(self) -> int:
sleep(1)
return choice(self.get_possible_moves())
def get_possible_moves(self, board = None) -> list[int]:
"""Returns list of possible moves"""
return [i for i, v in enumerate(self.board if board is None else board) if v == 0]
def minimax(self, board: list[int], depth: in... | The code determines the AI's move based on difficulty: easy AI selects randomly, while other AIs use the minimax algorithm with a specified depth and maximizing status to choose optimal moves. | def ai_move(self, player: Player, symbol: Symbol) -> int:
if player == Player.AI_EASY:
print()
return self.random_choice()
else:
if len(self.get_possible_moves()) == 9:
return self.random_choice()
is_maximizing = True if symbol.value == 1 else False
return self.minimax... |
def get_possible_moves(self, board = None) -> list[int]:
"""Returns list of possible moves"""
return [i for i, v in enumerate(self.board if board is None else board) if v == 0]
def update_player(self, symbol: Symbol) -> Player:
"""Returns proper player based on given symbol"""
if symbol == Symbol.O: r... | This code runs a game loop for a turn-based game, alternating between players to make moves, checking for win/tie conditions after each move. It initializes the board if not already set, takes player input, updates the game state, and terminates when a player wins or the game ends in a tie. | def start(self, starts: Symbol = Symbol.O):
"""Runs game itself"""
if len(self.get_possible_moves()) != 9:
self.board = [0 for _ in range(9)]
curr_symbol = starts
curr_player = self.update_player(curr_symbol)
while curr_player is not None:
if self.is_tie():
print(f"\nIt's a ti... |
def corr(arr1, arr2):
global n
mean1 = mean(arr1)
mean2 = mean(arr2)
conv = 0.0
for i in range(n):
conv += (arr1[i] - mean1) * (arr2[i] - mean2)
return conv/(n*std(arr1)*std(arr2))
def std(a):
global n
mu = mean(a)
sum_ = 0.0
for i in range(n):
sum_ += ((a[i] - mu... | This code performs linear regression to predict the value of Y for a given x1 using the input data X and Y. It calculates the slope (b) and intercept (a) of the regression line, then outputs the predicted value rounded to three decimal places. | def liner(X, Y, x1):
b = corr(X,Y)*(std(Y)/std(X))
a = mean(Y) - (b*mean(X))
print(round(a + (b*x1), 3)) |
def select(self, node):
# make sure that we're dealing with non-terminal nodes
while not node.is_terminal:
# case where the node is fully expanded
if node.is_fully_expanded:
node = self.get_best_move(node, 2)
# case where the node is not f... | This code implements a Monte Carlo Tree Search (MCTS) algorithm. It constructs a tree of game states starting from an initial position, iteratively selecting nodes, simulating game outcomes, and backpropagating results to update scores. After 1000 iterations, it identifies and returns the optimal move based on accumula... | def search(self, initial_state):
# create root node
self.root = TreeNode(initial_state, None)
# walk through 1000 iterations
for iteration in range(1000):
# select a node (selection phase)
start = time.time()
node = self.select(self.root)
... |
def _should_replan(lidar_points):
print(len(lidar_points))
if path_polygon is None: return True
for p in lidar_points:
if path_polygon.contains_points([p])[0]: return True
return False
def _best_path(car_pos, lidar_points):
global path_polygon
p = _a_star(car_pos, lidar_points)
if p is not None: path_polygon =... | This function updates a vehicle's route based on LiDAR data. If replanning is needed, it calculates a new optimal path; otherwise, it checks if the vehicle has progressed along the current path. If the vehicle has moved past the current path segment, it advances the path index and updates direction. Returns True on suc... | def _update_route(car_pos, lidar_points):
if _should_replan(lidar_points):
path = _best_path(car_pos, lidar_points)
if path is None:
return False
car_pos.path = path
car_pos.path_index = 0
_update_direction(car_pos)
else:
dx, dy, rx, ry = car_pos.path[car_pos.path_index+1].x - car_pos.path[car_pos.path... |
def fast_non_dominated_sort(objectives):
'''
Fast NonDominated Sort
Return the non-dominated sets
'''
f = []
f.append([])
dominated_index = []
dominated_count = []
for i in objectives:
dominated_index.append([])
dominated_count.append(0)
# calculate th... | This function trains neural networks in parallel using multi-objective optimization. It generates random seeds, computes rewards via parallel jobs, sorts solutions by performance, selects non-dominated individuals, identifies a 'knee' optimal solution, and applies gradient updates to boundary parameters. The task invol... | def train(X, Y, I, L, net_shapes, net_params, optimizer, utility, pool, individual_size, sigma, boundary_size=4):
noise_seed = np.random.randint(
0, 2 ** 32 - 1, size=individual_size, dtype=np.uint32).repeat(2) # mirrored sampling
pick_seed = np.random.randint(
0, boundary_size, size=indivi... |
def get_str_offsets(call_site):
#Get first call within nested operands, does not account for nested
#calls, but we haven't seen those.
rcall = recurse_get_call(call_site.hlil)
#Get first constant within operands of call
rconst = recurse_get_const(rcall)
if rconst:
return rconst.value.va... | This function processes call sites in a binary to decrypt strings using offsets from a decrypted string table. It checks for campaign and C2-related data, then annotates each call site with the decrypted string as a comment. The result is a dictionary mapping addresses to decrypted strings, aiding reverse engineering b... | def markup_str_as_comments(decrypted_str_table, inst):
rstr = {}
for callsite in inst.function.source_function.caller_sites:
#print(F"Found call site: {callsite.address:08X}")
str_offset = get_str_offsets(callsite)
dec_str = decrypted_str_table[str_offset:].split(b"\x00")[0]
#Wh... |
def get_xor_key_and_ct(inst):
#mw_decrypt_data(&data_180027240, 0x5ab, &data_1800271a0, 0x90,\
# &data_180027150, 0x47, arg1)
tokens = inst.tokens
ct_addr = tokens[3].value
ct_len = tokens[5].value
ct = bv.read(ct_addr, ct_len)
iv_xor_ct_data_addr = tokens[8].value
iv_xor_ct_data_le... | The code processes a `Localcall` instruction with 7 parameters and a single internal instruction. It extracts an XOR key and ciphertext, decrypts the data using XOR, inserts the decrypted string as comments, and returns `False` to halt further processing. | def visitor(_a, inst, _c, _d):
if isinstance(inst, commonil.Localcall):
if len(inst.params) == 7:
if len(list(inst.function.instructions)) == 1:
xor_key, ct = get_xor_key_and_ct(inst)
decrypted_str_table = xor_byte_data(ct, xor_key)
markup_str_as_c... |
def _parse_arguments():
"""Parse arguments"""
argparser = argparse.ArgumentParser(
description='Create HTML documentation pages from Python module files')
argparser.add_argument('input_files', help='Path to input files or '
'directories', nargs='+')
... | This code generates documentation pages from input files or directories by parsing modules and packages, using specified template formatters. It creates an output directory, processes each module to write documentation, and optionally generates index pages for non-empty packages, based on command-line arguments like in... | def main():
"""Application entry point"""
arguments = _parse_arguments()
output = Path(arguments.output)
parser = ModuleParser(arguments.nonpublic, arguments.empty)
template_formatter = try_get_template_formatter()
package_parser = PackageParser(try_read, parser, arguments.ignore,
... |
def _split_lines(self, lines, separator_marker):
"""Split lines into groups by lines containing the separator string"""
result = []
current_group = []
for line in lines:
if re.match(rf'[^\S\n]*{separator_marker}\w+(\(.*\))?:', line):
if current_group:
... | The code extracts class objects from input lines by splitting them using a title marker, parsing each class's name, parent, docstring, and methods, then filtering public or specified non-public classes into a list for return. | def get_classes(self, lines):
"""Extract class objects from lines"""
result = []
classes = self._split_lines(lines, Class.TITLE_MARKER)
for c in classes:
signature = self._get_group_title(c, Class.TITLE_MARKER)
name, parent = self._split_title(signature)
... |
def generate_chain(length=9, start = None, verbose = False):
if start:
if verbose:
print(f"Trying {start} with words {word_dicts[length][start]}")
chain = find_subchain(start)
if chain != []:
detailed_dict = {}
for letters in chain:
detai... | The code implements a word game where users guess valid words using progressively longer letter sets. It validates guesses, allows hints, tracks progress, and displays answers. Players advance through stages, earning points for correct answers and using hints, with an option to replay or exit after completing all level... | def play_game(length = 9, start_length = 3):
while True:
chain_dict = generate_chain(length = length, start=None, verbose=False)
user_word = ''
user_words = []
hints = 0
current_length = start_length
while current_length <= length:
current_stage = current... |
def adds_table_description(execute_segment):
function = get_exec_function(execute_segment)
args = get_exec_args(execute_segment)
return (function == "SP_ADDEXTENDEDPROPERTY") \
and args[0].upper() == "MS_DESCRIPTION" \
and args[-2].upper() == "TABLE"
def get_described_table(execute_segment):... | The main task of the code is to recursively collect tables with their descriptions from a given parent_segment. It iterates through each segment, checks if it's an "execute_script_statement" with a table description, and either appends the described table directly or processes nested segments recursively. The function ... | def get_tables_with_descriptions(parent_segment):
tables_with_description = []
for segment in parent_segment.segments:
if segment.is_type("execute_script_statement") and adds_table_description(segment):
tables_with_description.append(get_described_table(segment))
else:
ta... |
def spaceBelow(self, y = -25):
if (y == -25): y = self.currTile.y
for p in self.currTile.listLoc:
if(self.disTiles[self.currTile.x + p[0]][y + p[1] + 1].occupied == 2):
return False
return True
def disTilesUpdate(self):
for i in range(len(self.disTiles)):
... | The main task of the code is to handle tile movement and collision detection in a game. If space is available below the current tile, it moves the tile down and updates the display. If not, it marks the tile's position as occupied, triggers row clearing, resets the tile, and checks for game over. Recursive calls ensure... | def frameUpdate(self):
# If there is a space below
if(self.spaceBelow()):
self.currTile.y += 1
self.disTilesUpdate()
self.disTilesDraw()
self.drawBottom()
else:
for p in self.currTile.listLoc:
self.disTiles[self.currTile... |
def translate(self,direc,amt = 1):
canTrans = True
if(direc == 1):
for q in self.currTile.listLoc:
if((self.currTile.x + q[0]) == len(self.disTiles) - 1):
canTrans = False
break
elif(self.disTiles[self.currTile.x + q[0] ... | This code checks if rotating the current tile is possible without collisions. It calculates adjustment indices based on edge proximity, verifies valid rotation positions, and applies the rotation if feasible, updating the display accordingly. | def rotate(self):
canRot = True
if self.currTile.anchorIndex != None:
tempListLoc = self.currTile.sampleRot()
index = 0
if (self.currTile.x < 4):
for p in tempListLoc:
if(p[0] + self.currTile.x < 0):
index = ... |
def setup(self):
self.screen.fill((0,0,0))
# Border
pygame.draw.rect(self.screen, (192,192,192), pygame.Rect(self.xL-6, self.yL-6, Window.xS+12, Window.yS+12))
# Display
pygame.draw.rect(self.screen, (0,0,0), pygame.Rect(self.xL, self.yL, Window.xS, Window.yS))
for i in ... | This code initializes a tile-based game component by setting up a grid of Node objects, configuring game attributes like screen, position, and highest row, and preparing the game state with methods for setup, tile reset, and frame updates. It initializes game variables such as current tile, game status, and input flags... | def __init__(self, xL, yL, screen, highestRow = -1):
self.screen = screen
self.xL = xL
self.yL = yL
self.disTiles = [[Node()]*20 for _ in range(15)]
for i in range(len(self.disTiles)):
self.disTiles[i].append(Node(occupied = 2))
self.currTile = None
se... |
def spaceBelow(self, y = -25):
if (y == -25): y = self.currTile.y
for p in self.currTile.listLoc:
if(self.disTiles[self.currTile.x + p[0]][y + p[1] + 1].occupied == 2):
return False
return True
def disTilesUpdate(self):
for i in range(len(self.disTiles)):
... | The code moves a tile downward as long as there is space below it, updating the display tiles during each step, then triggers a frame update to finalize the movement. | def drop(self):
while(self.spaceBelow()):
self.currTile.y +=1
self.disTilesUpdate()
self.frameUpdate() |
def generate_keys() -> ((int, int, int), int):
p = generate_large_random_prime()
start = time.time()
g = find_generator_faster_hopefully(p)
end = time.time()
print(f"Finding {g} took {end - start}")
# start = time.time()
# g = find_generator(p)
# end = time.time()
# print(f"Finding ... | The code tests the correctness of an RSA encryption/decryption implementation by running 10,000 iterations. In each iteration, it generates key pairs, encodes a message, encrypts it, decrypts it, and verifies the decrypted result matches the original message using assertions. | def test():
for i in range(10000):
pub_key, priv_key = generate_keys()
rem, quot = encode_text(message, pub_key[0]) # message, 0 < m < p-1
encoded = encrypt(rem, pub_key)
decoded = decrypt(encoded, priv_key, pub_key[0])
assert decode_text(decoded, pub_key[0], quot) == messa... |
def get_object(self):
_id = self.parse_obj_id(_id=self.kwargs.get(self.lookup_field, None))
obj = get_object_or_404(self.get_queryset(), id=_id)
self.check_object_permissions(self.request, obj)
return obj
def check_if_exist_responses(self):
_id = self.parse_obj_id(_id=self.kwargs... | The code handles adding a new question to a survey, ensuring no existing responses are present and the question name is unique. It validates input data, checks for existing responses and duplicate names, and adds the question to the survey if valid, returning a 201 Created response upon success. | def post(self, request, parent_pk):
survey = self.get_object()
if self.check_if_exist_responses() is True:
return self.bad_request("You can't modify the questions if there already are responded surveys")
serializer = QuestionSerializer(data=request.data)
serializer.is_valid... |
def get_object(self):
_id = self.parse_obj_id(_id=self.kwargs.get(self.lookup_field, None))
obj = get_object_or_404(self.get_queryset(), id=_id)
self.check_object_permissions(self.request, obj)
return obj
def bad_request(message):
return Response({"Error": message}, status=status... | This code allows partial updating of a survey's question name via PATCH request, validating that only the 'name' field is modified and the question exists. It checks request data validity, ensures the question's existence, updates the survey, and returns a 200 OK response upon successful update. | def patch(self, request, parent_pk):
survey = self.get_object()
if 'name' not in request.data.keys() or len(request.data.keys()) > 1:
return self.bad_request('You can only update the field "name"')
if self.check_if_exists_question(self.request.query_params.get('current_name')) is Fa... |
def _convolution(self, net, fsize, fin, fout, stride, name="convolution"):
with tf.variable_scope(name):
num_net = fsize * fsize * fout
k = tf.get_variable(
"weights",
shape=[fsize, fsize, fin, fout],
dtype=self._dtype,
... | This code implements an image classification model using a residual network architecture. It processes input through convolutional layers, residual blocks with varying depths and strides, batch normalization, average pooling, and a fully connected layer with softmax activation to generate class probabilities. | def _inference(self):
#depth = self._params.depths
depth = [16, 64, 128, 256]
ones = [1] * 4
twos = [1,2,2,1]
strides = [None, ones, twos, twos]
num_depth = len(depth)
num_units = self._params.num_resunits_per_block
num_labels = self._params.num_labels
... |
def _inference(self):
#depth = self._params.depths
depth = [16, 64, 128, 256]
ones = [1] * 4
twos = [1,2,2,1]
strides = [None, ones, twos, twos]
num_depth = len(depth)
num_units = self._params.num_resunits_per_block
num_labels = self._params.num_labels
... | The code defines the `build` method, which constructs a TensorFlow model's computational graph. It initializes a global step counter, builds the inference graph, computes loss, and sets up training operations if in training mode. Finally, it merges all summaries for monitoring training progress. | def build(self):
self.global_step = tf.contrib.framework.get_or_create_global_step()
self._inference()
self._loss()
if self.is_training():
self._train()
self.summary = tf.summary.merge_all() |
def drawBoard(bob):
if graphics:
c1="gray"
c2="red"
for x in range(8):
drawRow(bob,c1,c2)
bob.up()
bob.goto(0,x+1)
bob.down()
#switch c1 and c2 colors
temp=c1
c1=c2
c2=temp
drawLabels(bob)... | The main task of the code is to initialize a checkers game by setting up the graphical interface, board structure, and initial checker positions. It creates a turtle graphics window, draws the board, populates the game board with checkers either randomly or from a specified file, determines the starting player, and ret... | def setupGame(inFileName):
#Set up graphics for game
wn=turtle.Screen()
wn.setworldcoordinates(-2,9,10,-2)
bob=turtle.Turtle()
bob.hideturtle()
wn.tracer(False)
drawBoard(bob)
#Set up logical and graphical checkers
row=["e","e","e","e","e","e","e","e"]
board=[]
for i in rang... |
def clock():
global startTime
return time.time()-startTime
def generateMoves(board,player):
moves = listValidMoves((board), player)
jumps = listSingleJumps((board), player)
jumps = listMultipleJumps((board), player, jumps)
crowningMoves = []
crowningJumps = []
if not moves == []:
... | The code implements a Minimax algorithm with alpha-beta pruning for a board game (likely checkers or similar), evaluating optimal moves for a player ('r' or 'b') by recursively exploring possible moves. It prioritizes maximizing the player's advantage while minimizing the opponent's, using heuristics to avoid repetitiv... | def miniMax(board,player,level,moveHistory,alpha,beta): #Positive is Red advandage, Negative is Black
if player == 'r':
sign=1
enemy='b'
else:
sign=-1
enemy='r'
if timeRestriction and clock() > .98: # Prevent timeout
return (-2000*sign,'Timeout')
allMoves=gener... |
def setupGame(inFileName):
#Set up graphics for game
wn=turtle.Screen()
wn.setworldcoordinates(-2,9,10,-2)
bob=turtle.Turtle()
bob.hideturtle()
wn.tracer(False)
drawBoard(bob)
#Set up logical and graphical checkers
row=["e","e","e","e","e","e","e","e"]
board=[]
for i in rang... | The code runs a checkers game, handling player moves, enforcing time limits, and determining the winner. It initializes the game board, alternates turns between players, processes moves and jumps, updates the graphical interface, checks for game over conditions, and returns the result (winning player or timeout). It al... | def checkersMain(inFileName,player1,player2):
wn,bob,board,player=setupGame(inFileName)
print(' ',player1,'is Red ',player2,'is Black')
if player=="b":
playerColor="black"
else:
playerColor="red"
gameOver=False
if step:
input('Press enter to procede')
starti... |
def generateMoves(board,player):
moves = listValidMoves((board), player)
jumps = listSingleJumps((board), player)
jumps = listMultipleJumps((board), player, jumps)
crowningMoves = []
crowningJumps = []
if not moves == []:
crowningMoves, moves = listCrowningMoves((board), player, moves... | The function `getValidMove` selects the optimal move for a player on a board game using a minimax algorithm with adaptive depth control. It generates possible moves, adjusts the search depth based on historical move complexity and timing, and employs heuristic rules to balance computational efficiency and decision qual... | def getValidMove(board, player):
global startTime
global globalLevel
global globalBench
global moveLenHistory
global moveHistory
moves=generateMoves(board,player)
startTime = time.time()
#if isGameStart(board):
if moveHistory==[] and diagnostics:
print('Minimax Player is colo... |
def _read_halo_info(self, halo_fns, load_fields):
# Open all the files, validate them, and count the halos
# Lazy load, but don't use mmap
afs = [asdf.open(hfn, lazy_load=True, copy_arrays=True) for hfn in halo_fns]
N_halo_per_file = np.array([len(af[self.data_key]['id']) for af in afs]... | The code initializes an object to load halo data from simulation files, including halo records, subsample particle data (positions, velocities, IDs), and metadata. It processes input paths, validates parameters (e.g., `load_subsamples`, `convert_units`), reads header metadata, and selectively loads specified fields or ... | def __init__(self, path, load_subsamples=False, convert_units=True, unpack_bits=False, fields='all'):
"""
Loads halos. The ``halos`` field of this object will contain
the halo records; and the ``subsamples`` field will contain
the corresponding halo/field subsample positions and velocit... |
def __extract_market_price__(self, direction, symbol):
market_price = self.get_discount(symbol=symbol)[0]
if direction == OrderDirection.BUY:
market_price = float(market_price["Ask"])
else:
market_price = float(market_price["Bid"])
return market_price
def _api_key... | This function places a trade order by handling conversions between quantity and total values based on order type (limit/market), validating inputs, formatting parameters according to market rules, and sending the signed request to the trading API. It ensures proper decimal precision, enforces required parameters, and c... | def place_order(self, symbol: str, category: OrderType, direction: OrderDirection,
price: Optional[float] = None, qty: Optional[float] = None,
total: Optional[float] = None, handle_conversions: bool = True,
**kwargs):
"""
Places an order.
... |
def default(val, d):
if exists(val):
return val
return d() if isfunction(d) else d
def Downsample(dim, dim_out=None):
# No More Strided Convolutions or Pooling
return nn.Sequential(
Rearrange("b c (h p1) (w p2) -> b (c p1 p2) h w", p1=2, p2=2),
nn.Conv2d(dim * 4, default(dim_out,... | This code defines a UNet-like neural network for image processing, incorporating residual blocks, attention mechanisms, and time embeddings. It processes input images through downsampling/upsampling paths, using sinusoidal time embeddings for temporal dynamics. The model handles self-conditioning, features dimensionali... | def __init__(
self,
dim,
init_dim=None,
out_dim=None,
dim_mults=(1, 2, 4, 8),
channels=3,
self_condition=False,
resnet_block_groups=4,
):
super().__init__()
# determine dimensions
self.channels =... |
def _not(self, valString, register):
""" performs a bitwise compliment on the value and stores in the register"""
val = self.parseValue(valString)
self.memory[register] = ~ val
def _and(self, lhsString, rhsString, register):
""" performs a bitwise and on lhs and rhs, storing in the register """
lhs,... | The code processes an instruction string by parsing its elements, applying corresponding operations (NOT, AND, OR, LSHIFT, RSHIFT, or INSERT) to values and registers, adjusting results to fit within a defined integer range (MAX_INT), and printing the final register value. It ensures values stay within bounds by wrappin... | def processInstruction(self, opString):
""" processes an instruction string and performs the encoded op """
elements = opString.split(' ')
if elements[0] == 'NOT':
_, valString, _, register = elements
self._not(valString, register)
elif elements[1] == 'AND':
lhs, _, rhs, _, register = ... |
def runner(_N_SLIDERS, n, files):
''' This function uses a physics object and excutes actions on an environment, using a pusher.
The first action is not recorded, and is taken to create realistic velocities to use as an input state.
The second action is recorded.
Initial positions and velocities of the sliders ... | The function `recursive_runner` generates all possible combinations of indices for nested loops defined by the array `N`, with `k` specifying the depth of nesting. It recursively iterates through each element of `N`, updating an index array `n` at each level. Once all indices are set (when `k=0`), it invokes the `runne... | def recursive_runner(N, k):
''' This function creates nested for loops and recursively calls 'runner'
Args:
N: 1D array of integers, each value determines the number of iterations in a single loop.
k: Number of nested for loops to create. On the first call, k should equal len(N).
'''
if k > 0:
for i in r... |
def simple(self,text):
r = self.colorText(text,"green")
def error(self,error):
r = self.colorText(error,"red")
def warn(self,warning):
r = self.colorText(warning,"yellow")
def special(self,text):
r = self.colorText(text,"pink") | This code defines a `log` method that routes input text to different logging functions based on the specified type. It checks the `type` parameter and calls corresponding methods like `simple`, `error`, `warn`, or `special`, allowing flexible message logging with varied handling for different message categories. | def log(self,text,type="simple"):
if(type == "simple"):
self.simple(text)
elif(type == "error"):
self.error(text)
elif(type == "warn"):
self.warn(text)
elif(type == "special"):
self.special(text) |
def get_password(self, user, realm, app, owner):
'''Get the password for a user and realm.
@return: The encrypted form of the password.
'''
q = SplunkStoredCredential.get(SplunkStoredCredential.build_id(self._build_id(user, realm), app, owner), self._sessionKey)
... | This function creates or updates a credential in Splunk's secure credential store by checking if a password already exists for the given user, realm, app, and owner. If it exists, it updates it; otherwise, it creates a new credential. The encrypted password value is returned in both cases. | def create_or_set(self, user, realm, password, app, owner):
"""Create or update a credential in Splunk's secure credential store.
@return: The encrypted password value.
"""
try:
exists = self.get_password(user, realm, app, owner)
return self.set_... |
def print_msg(self, msg, lvl):
if self.rank == 0:
if self.sim_count % self.sim_print_freq == 0 and lvl <= self.verbosity:
print(msg, flush=True)
def set_parameters(self, param):
""" Replace parameters with new parameters. """
if self.Vh[PARAMETER] is None:
raise ValueError("HippyLib par... | The function `solveFwd` computes the Quantity of Interest (QoI) by solving the forward model. It updates the model parameters using the input `x`, executes the simulation via `self.solve(out)`, and logs the current parameters and simulation count. The task involves parameter substitution, model execution, and output co... | def solveFwd(self, out, x):
"""
Takes in the specified parameter and solves the forward model and computes the QoI (model output).
"""
self.print_msg('Solve with parameters: {}, sim count: {}'.format(np.exp(x[PARAMETER].get_local()), self.sim_count+1), 1)
# replace parameter with spec... |
def check_brackets(expression):
stack = []
for char in expression:
if char == '(':
stack.append(char)
elif char == ')':
if not stack:
return False
stack.pop()
return len(stack) == 0
def replace_operators(expression):
expression = expres... | The function `evaluate_expression` evaluates a mathematical expression by substituting `x` with a given value, removing spaces, validating bracket balance, replacing operators, tokenizing the expression, and computing the result. It ensures proper syntax and structure before evaluation. Your return | def evaluate_expression(expression,x):
expression = expression.replace('x', str(x))
expression = expression.replace(' ', '') # Remove whitespace from the expression
if not check_brackets(expression):
return "Invalid expression: Brackets are not balanced"
expression = replace_operators(expressio... |
def selectchromosomes(ga,ganew50):
number=50
size=10
array = np.zeros((10,popsize))
a = np.random.randint(50, size =10)
k=0
for i in range(size):
index=a[k]
array[i]=ga[index]
k=k+1
fitness=[]
k=0
bestfifty = np.zeros((1,popsize))
sum=0
for i in range(size):
f,cost=calcula... | The code implements a genetic algorithm to solve an optimization problem, likely the Traveling Salesman Problem. It generates and iterates through populations of chromosomes, applying selection, crossover, and mutation. It evaluates fitness, tracks the best solution per generation, and returns the final optimal route w... | def main(generations):
print(customerno)
flag=0
for t in range(generations):
print("\n\ngeneration number==")
print(t)
popsize=customerno
iters=50
op=2
b=[]
b=idno
if(flag==0):
ga = np.zeros((50,popsize))
else:
ga=selectchromosomes(ga,ganew50)
for p in range(iters):
c = n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.