dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def read_points(filename):
points = []
with open(filename) as f:
input_lines = f.readlines()
for line in input_lines:
x, y = line.split()
points.append((float(x), float(y)))
return points
def read_region(filename):
with open(filename) as f:
line1 = f.r... | The code visualizes spatial data by plotting points and a region on two subplots. It reads points and region coordinates, displays all points in the first subplot with the region, preprocesses points (likely building a k-d tree), performs a range search to find points within the region, and plots only those results in ... | def init():
points = read_points("points.txt")
x_region, y_region = read_region("regions.txt")
fig, ax = plt.subplots(2)
ax[0].set_xlim([0, 9])
ax[0].set_ylim([0, 9])
ax[1].set_xlim([0, 9])
ax[1].set_ylim([0, 9])
rect = patches.Rectangle((x_region[0], y_region[0]), x_region[1] - x_regi... |
def generate_sudoku():
""" Generate a filled 16x16 Sudoku board """
board = np.zeros((16, 16), dtype=int)
# Fill the diagonal 4x4 boxes
for i in range(0, 16, 4):
fill_box(board, i, i)
# Solve the partially filled board
solve_sudoku(board)
return board
def shuffle_pixel... | The code shuffles and unshuffles an image's pixels using a Sudoku-based permutation. It generates a Sudoku grid, converts it to a zero-indexed numpy array, applies this permutation to shuffle the image, and then reverses the process to restore the original image. The main task involves using Sudoku-derived patterns for... | def sudoku(image_path):
perm = generate_sudoku()
print(perm)
perm = np.array(perm)-1
shuffle_pixels(image_path, perm)
unshuffle_pixels("shuffled_image.png", perm) |
def buildXML(data, level = 0):
node = Etree.Element(data['type'])
if 'properties' in data.keys():
for key in data['properties']:
node.set(key, toStr(data['properties'][key]))
if 'data' in data.keys():
if isSubData(data['data']):
for item in data['data']:
... | This function exports a mesh to a specified file path with a given name and type. It constructs the full file path, then writes the mesh data in either XML, JSON, or binary format depending on the fileType parameter, using corresponding helper functions for each format. | def exportMesh(mesh, filePath, fileName, fileType):
fullPath = filePath+'/'+fileName+'.'+fileType
if fileType == 'xml':
node = buildXML(mesh)
writeXML(node, fullPath, True)
elif fileType == 'json':
writeJSON(mesh, fullPath)
elif fileType == 'mesh':
writeBinaryMesh(mesh, ... |
def extractMeshBuffers(mesh, bufferMap, indexMap,
extractNormals = True,
extractUVs = True,
extractColors = False):
mesh.calc_tessface()
mesh.calc_normals()
# Get the vertex positions and normals
positions = list()
normals ... | This function writes a 3D mesh to a binary file, exporting vertex attributes (positions, normals, UVs) and optionally indices. It applies transformations, handles buffer alignment, and structures data for rendering. The output includes primitive type, sub-mesh info, attribute metadata, and vertex/index buffers, with su... | def writeBinaryMeshFile(mesh, filePath,
transform = mathutils.Matrix(),
stripMode = 'OFF',
alignBuffers = True,
exportIndices = True,
exportNormals = True,
exportUVs = True,
... |
def extractMeshBuffers(mesh, bufferMap, indexMap,
extractNormals = True,
extractUVs = True,
extractColors = False):
mesh.calc_tessface()
mesh.calc_normals()
# Get the vertex positions and normals
positions = list()
normals ... | This function converts a mesh into an XML structure by extracting and transforming vertex buffers, handling indices, and organizing submesh data. It writes buffer attributes, indices, and submesh ranges to the provided meshNode, with options to control data export (normals, UVs, etc.), alignment, and triangle stripping... | def writeMeshToXml(mesh, meshNode,
transform = mathutils.Matrix(),
stripMode = 'OFF',
alignBuffers = True,
exportIndices = True,
exportNormals = True,
exportUVs = True,
expor... |
def getObjectMaterials(obj):
materials = []
for slot in obj.material_slots:
if slot.material is not None:
materials.append(slot.material)
return materials
def buildMainFrame():
data = {'type':'Frame', 'properties':{}, 'data':[]}
data['properties']['name'] = 'MainFrame'
data['... | The main task of the code is to construct a scene data structure from Blender objects, organizing meshes, materials, models, cameras, and lights into a JSON-like format. It initializes scene properties, collects mesh/material data, and appends built components (meshes, shaders, models, etc.) to the scene's data list, w... | def buildScene(objects, name):
meshes = {}
materials = []
for obj in objects:
if obj.type == 'MESH':
meshes[obj.data.name] = obj.data
materials.extend(getObjectMaterials(obj))
data = {'type':'Scene', 'properties':{'name':name}, 'data':[]}
# TODO: Figure out how to d... |
def buildScene(objects, name):
meshes = {}
materials = []
for obj in objects:
if obj.type == 'MESH':
meshes[obj.data.name] = obj.data
materials.extend(getObjectMaterials(obj))
data = {'type':'Scene', 'properties':{'name':name}, 'data':[]}
# TODO: Figure out how to d... | The main task of the code is to export a 3D scene to a specified file format (XML/JSON) by first constructing the scene from objects, exporting associated meshes if required, and then writing the scene data to a file with the given path and type. It supports mesh export in XML/JSON/mesh formats and scene structure expo... | def exportScene(objects, filePath, fileType, sceneName, meshType):
scene = buildScene(objects, sceneName)
if meshType == 'xml' or meshType == 'json' or meshType == 'mesh':
meshes = getMeshesFromScene(scene)
exportMeshes(meshes, filePath, meshType)
fullPath = filePath+'/'+sceneName+'.'+file... |
def remove_accent(text):
return unidecode.unidecode(text)
def preprocess_doc(raw_text, start_token, stop_token):
if is_html(raw_text):
scrtext_html = BeautifulSoup(raw_text, features="lxml").body.find('td', attrs={'class': 'scrtext'})
if scrtext_html is not None:
raw_text = scrtext_h... | The main task of the code is to clean a dataset by processing text documents and question-answer pairs. It loads Parquet data, filters documents by ID, removes accents, applies regex substitutions, and preprocesses text using a helper function. Cleaned paragraphs and QA pairs are saved to specified output paths. The co... | def clean_data(dataset_name, raw_data_path, cleaned_data_path):
global count
logging.info(f"=== Cleaning {dataset_name} set and save to \'{cleaned_data_path}\'")
dataset = load_dataset('parquet', data_files=[f'{raw_data_path}/{dataset_name}.parquet'])
doc_id_set = set()
for text in dataset:
... |
def too_fast(car_speed: float, max_speed: Meters) -> bool:
return car_speed >= max_speed
def too_close_to_intersection(car: Car, intersection: Intersection) -> bool:
# If there is no next intersection, we are definitely not close it
if intersection is None:
return False
distance_to_intersection... | The function `adjust_speed` controls a car's movement by braking if it exceeds a maximum speed, is too close to an intersection, or is too near the car in front. If none of these conditions apply, it accelerates the car. The function ensures safe speed management in dynamic driving scenarios. | def adjust_speed(
car: Car,
max_speed: float,
dt: Seconds,
):
if too_fast(car.speed, max_speed):
car.brake(dt)
return
if car.target_intersection and too_close_to_intersection(
car, car.target_intersection
):
car.brake(d... |
def get_train_val_test_csv_files():
path_to_splits_folder = os.path.join(path_chest_imagenome, "silver_dataset", "splits")
return {dataset: os.path.join(path_to_splits_folder, dataset) + ".csv" for dataset in ["train", "valid", "test"]}
def get_images_to_avoid():
path_to_images_to_avoid = os.path.join(path_... | The main task of the code is to process training, validation, and test CSV files by excluding specified image IDs from a "gold standard" dataset and computing/printing statistics for the remaining data. It retrieves the CSV files, identifies images to exclude, and analyzes the filtered dataset. | def main():
csv_files_dict = get_train_val_test_csv_files()
# the "splits" directory of chest-imagenome contains a csv file called "images_to_avoid.csv",
# which contains image IDs for images in the gold standard dataset, which should all be excluded
# from model training and validation
image_ids_t... |
def get_train_val_test_csv_files():
"""Return a dict with datasets as keys and paths to the corresponding csv files in the chest-imagenome dataset as values"""
path_to_splits_folder = os.path.join(path_chest_imagenome, "silver_dataset", "splits")
return {dataset: os.path.join(path_to_splits_folder, dataset)... | The main task of the code is to generate new training/validation/test CSV files by excluding specified image IDs from the original splits. It retrieves CSV files, identifies image IDs to exclude from a dedicated file, and creates updated CSV files without those IDs to ensure they are omitted from model training and val... | def main():
csv_files_dict = get_train_val_test_csv_files()
# the "splits" directory of chest-imagenome contains a csv file called "images_to_avoid.csv",
# which contains image IDs for images in the gold standard dataset, which should all be excluded
# from model training and validation
image_ids_t... |
def verify_session(request):
return CURRENT_USER in request.session
def get_session_or_die(request):
if CURRENT_USER in request.session:
return decrypt_session_attribute(request.session[CURRENT_USER])
else:
raise Exception("No session found.")
def find_requested_users(request):
if verify... | The main task of the code is to handle the user's inbox interface by verifying session authentication, retrieving message threads, and rendering the index page with active/inactive target users, message history, and forms for creating messages or finding users. It ensures session validity, defaults to the first availab... | def index(request):
if verify_session(request):
connected_user = get_session_or_die(request)
else:
return HttpResponseRedirect('/login-app')
message_service = MessageService()
inbox_form = MessageCreationForm()
user_finder_form = UserFinderForm()
user_message_list = fin... |
def one_pitch_str_to_midi(pitch_str):
pitch_obj = one_pitch_str_to_pitch_obj(pitch_str)
return one_pitch_obj_to_midi(pitch_obj)
def one_midi_to_hz(midi_note, a4_hz):
distance = midi_note - MIDI_REF
return round(a4_hz * (ST_HZ**distance), 3)
def one_pitch_str_to_pitch_obj(pitch_str):
pitch_name_forma... | This function converts pitch strings (e.g., "C4") into musical note data, returning a dictionary with frequency (Hz), MIDI note numbers, pitch objects, original names, and A4 tuning. It handles both string and list inputs, splitting strings into lists, then maps each pitch to its MIDI equivalent and calculates correspo... | def from_pitch(pitch_strs, a4_hz=STD_A4):
if type(pitch_strs) == str:
pitch_strs = pitch_strs.split(' ')
if type(pitch_strs) != list:
raise ValueError('[error] from_pitch requires a string or list input.')
try:
midi_notes = [one_pitch_str_to_midi(pitch_str) for pitch_str in pitch_s... |
def from_midi(midi_notes, a4_hz=STD_A4):
if type(midi_notes) == str:
midi_notes = midi_notes.split(' ')
if type(midi_notes) in (float, int):
midi_notes = [float(midi_notes)]
if type(midi_notes) != list:
print('[error] from_midi requires a number, string, or list input.')
try:
... | This code converts MIDI numbers to musical pitch and frequency values using a specified A4 tuning. It repeatedly prompts the user for MIDI input, processes valid entries to display corresponding pitch names and frequencies, and exits when 'X' is entered. | def midi_to_pitch_loop(a4_hz):
print('Enter MIDI number as an integer or decimal number. Type X to quit.\n')
while(True):
midi_in = input('\n> MIDI: ')
if midi_in in ('X', 'x'):
return True
conversions = from_midi(midi_in, a4_hz)
if conversions is None:
... |
def from_hz(hzs, a4_hz=STD_A4):
if type(hzs) == str:
hzs = hzs.split(' ')
if type(hzs) in (float, int):
hzs = [float(hzs)]
if type(hzs) != list:
raise ValueError('from_hz requires a number, string, or list input.')
if any([float(hz) <= 0 for hz in hzs]):
raise ValueErr... | This code converts user-input frequencies to musical pitches and MIDI notes using a specified A4 frequency. It loops, accepting decimal Hz values, and outputs corresponding pitch names and MIDI numbers, noting microtonal discrepancies. The loop exits when the user inputs 'X', returning True. | def hz_to_pitch_loop(a4_hz):
print('Enter number as a decimal. Type X to quit.\n')
while(True):
hz_in = input('\n> Hz: ')
if hz_in in ('X', 'x'):
return True
conversions = from_hz(hz_in, a4_hz)
if conversions is None:
continue
pitches = conver... |
def from_pitch(pitch_strs, a4_hz=STD_A4):
if type(pitch_strs) == str:
pitch_strs = pitch_strs.split(' ')
if type(pitch_strs) != list:
raise ValueError('[error] from_pitch requires a string or list input.')
try:
midi_notes = [one_pitch_str_to_midi(pitch_str) for pitch_str in pitch_s... | The code converts user-inputted musical pitches (in scientific notation with accidentals and microtonal specifications) into corresponding MIDI note numbers and frequencies (Hz), using a specified A4 reference frequency. It processes lists of pitches, validates notation, and outputs results until the user quits by ente... | def pitch_to_hz_loop(a4_hz):
print('A4 = %.2f Hz' % a4_hz)
print("\nEnter a list of pitches in scientific pitch notation separated by spaces.\n\nFormat: Pitch name (A-G), then accidental (see next), then octave (an integer).")
print("\nExample inputs:\nC4\nBb8\nA2 F#4 D5")
print("Valid accidentals: d (d... |
def pull_rotated_piece(image, contour):
rectangle, box = get_min_area_box(contour)
width = int(rectangle[1][0])
height = int(rectangle[1][1])
src_pts = box.astype("float32")
dst_pts = array([[0, height - 1],
[0, 0],
[width - 1, 0],
[wi... | The main task of the code is to check if a rotated piece extracted from an image contour is sufficiently large, and if so, identify grid lines within that rotated piece. It first pulls a rotated section, validates its size, and returns detected grid lines if valid. | def check_for_rotated_grids(contour, image_contour):
warped_piece = pull_rotated_piece(image_contour, contour)
if is_properly_big(warped_piece, image_contour):
return find_grid_lines(warped_piece) |
def calccirclecenter(image_size, pts):
cp= []
ccp= []
ymin=xmin=100000
xmax=ymax=0
for landmark in pts:
pos = (np.array(image_size) * landmark[:2]).astype(np.int32)
if(len(cp)):
if(pos[0] < xmin):
xmin=pos[0]
if(pos[1] < ymin):
ymin=pos[1]
if... | The main task of the code is to process a new frame by calculating eye region centers, distances between key points, and horizontal eye alignment (strabismus detection). It updates frame counters, stores geometric parameters (landmarks, centers, distances), computes eye boundary coordinates, derives horizontal distance... | def processnewframe(image_sz, landmarks, lec, rec, ldp, rdp, lis, ris, lpts, rpts, p1, p2):
print("Frame # is:", (settings.framecount+1))
settings.framecount = settings.framecount + 1;
settings.licenter = calccirclecenter(image_sz, lpts)
settings.ricenter = calccirclecenter(image_sz, rpts)
sett... |
def isTerminal(self):
if self.terminal == None:
for i in range(3):
if self.board.board[i][0] == self.board.board[i][1] and self.board.board[i][1] == self.board.board[i][2] and self.board.board[i][1] != None:
self.terminal = True
... | The code evaluates the game state's value in a Tic-Tac-Toe-like game. It checks for terminal states by detecting row, column, or diagonal wins for "X" (return 1) or "O" (return -1). If the board is full with no winner, it returns 0. For non-terminal states, it delegates to min_value (for "O") or max_value (for "X") to ... | def value(self):
if self.isTerminal():
for i in range(3):
if self.board.board[i][0] == self.board.board[i][1] and self.board.board[i][1] == self.board.board[i][2] and self.board.board[i][1] != None:
if self.board.board[i][1] == "X":
... |
def fieldQuery(self,query):
text = re.findall(r'[b|i|t|c|r|l]:([^:]*)(?!\S)',query)
fields = re.findall(r'[b|i|t|c|r|l]:',query)
fields = [re.sub(r':',r'',field) for field in fields]
text = [i.lower() for i in text]
docDict = ddic(dict)
docFreq = ddic()
for i i... | The code processes multiple search queries by determining their type (field or normal), retrieving and ranking results, then outputting top results with titles and timing information. It iterates through queries, normalizes them, checks for specific keywords to classify the query type, executes corresponding search met... | def querying(self):
for query in self.queries:
self.queryType = 0
start = time.time()
self.num_query = self.num_query + 1
query = query.strip()
query = query.lower()
self.nResults, query = query.split(",")
query = query.strip()... |
def poses_avg(poses):
center = poses.T.mean(0)
vec2 = normalize(poses.R[:, :, 2].sum(0))
up = poses.R[:, :, 1].sum(0)
hwf = torch.cat(
(poses.image_size[0], poses.focal_length[0].unsqueeze(0)), 0
).unsqueeze(-1)
cam2world = torch.cat((viewmatrix(vec2, up, center), hwf), 1)
return ca... | The code generates camera poses for rendering by creating a spiral path around a scene. It calculates parameters like focal length, depth bounds, and radial distances from input poses. The function constructs a smooth camera trajectory using spiral_render_path, adjusts for flat paths if specified, and converts the resu... | def make_render_poses(self):
cam2world = poses_avg(self.poses)
up = normalize(self.poses.R[:, :, 1].sum(0))
close_depth, inf_depth = self.bounds.min() * 0.9, self.bounds.max() * 5
dt = 0.75
mean_dz = 1 / (((1 - dt) / close_depth + dt / inf_depth))
focal = mean_dz
... |
def load_data(path, downsample=1):
poses_ar = torch.from_numpy(np.load(os.path.join(path, "poses_bounds.npy")))
poses = poses_ar[:, :-2].reshape(-1, 3, 5)
bounds = poses_ar[:, -2:]
if downsample > 1:
imgdir = os.path.join(path, f"images_{downsample}")
else:
imgdir = os.path.join(pa... | This code initializes a 3D scene loader by loading image data, camera poses, and depth bounds, then processes them by scaling, recentering, and generating render poses. It also determines holdout indices for training/validation, either by periodic sampling or selecting the closest camera pose to an average position. | def __init__(
self,
path,
downsample,
recenter=True,
bounds_factor=0.75,
spherify=False,
path_zflat=False,
llff_hold=0,
):
self.path_zflat = path_zflat
self.images, self.poses, self.bounds = load_data(path, downsample=downsample)
... |
def is_valid_dir(parser, arg):
if not os.path.isdir(arg):
parser.error(f"Invalid directory {arg}")
return arg
def is_valid_chunk_size(parser, arg):
if int(arg) < 0:
parser.error(f"Invalid chunk size ({arg}). Inform a number greater than zero.")
return int(arg)
def debug(msg):
... | The main task of the code is to convert JSON data from andropytool into CSV files, extracting opcode, API call, and permission views from APKs in specified goodware/malware directories. It processes APK features in chunks, saving results to an output directory with validation for input paths and chunk size parameters. | def main(argv):
parser = argparse.ArgumentParser(argv, description="Extract opcode, apicall and permission views from andropytool json to csv.")
parser.add_argument("--goodware", nargs='?', default="./goodware", const="./goodware", type=lambda dir: is_valid_dir(parser, dir))
parser.add_argument("--malware... |
def _rho_SM(T): return Enrg(T,0.0,"B",gstar_enrg(T))
def _p_SM(T): return Pres(T,0.0,"B",gstar_p(T))
def _T_NR_rho(rho,Mass,Spin,Degf):
if Mass != 0: raise ValueError("do not support non-zero mass in this version")
else:
if Spin == "B": return (rho/(Degf*np.pi**2/30.))**0.25
elif Spin == "F": re... | This code initializes a class to store thermal properties and setup functions for calculating temperature, density, and pressure in a Boltzmann solver. It sets attributes for specific heat (Cp), mass, degrees of freedom, spin, and label, while defining lambda functions for Standard Model (SM) and Non-Relativistic (NR) ... | def __init__(self, Cp = None, property = [0,6,"F"], label = None):
''' results are restored in Boltzmann_solver.save variable including: thermal properties, label, solved time array,
solved density array array, solved temperature array, temperatrue relation by interpolation and initial temperat... |
def init_class(num_of_points, point_offset, is_unipolar_val=False, weight_lim_val=0.5, learning_rate_val=0.001,
error_treshold_val=0.52):
global weight_lim, learning_rate, error_treshold, w, x, y, is_unipolar
weight_lim = weight_lim_val
learning_rate = learning_rate_val
error_treshold = e... | The main task of the code is to conduct experiments on a Perceptron algorithm by testing its behavior under different configurations. It initializes a Perceptron with unipolar and bipolar activation functions, runs the learning process, and displays results. The commented-out loops suggest prior intent to vary weight l... | def conduct_tests_perceptron():
# for w_val in weight_lim_list:
# init_class(NUM_OF_POINTS, POINT_OFFSET, is_unipolar_val=True, weight_lim_val=w_val)
# perceptron_learn()
# show_results()
# print(f"End of test for weight_lim = {w_val} ***************************************\n\n")
... |
def getUser(id: str) -> User:
print('in getuser')
path = userPath(id)
print(path)
if not os.path.exists(path):
raise UserNotInDatabaseException
with open (path, 'rb') as f:
user = pickle.load(f)
return user
def newUser():
user_id = str(uuid.uuid4())
try:
putUser(U... | The main task of the code is to handle file uploads by processing PDF files, managing user authentication/session data, constructing a knowledge graph from uploaded files and a specified subject, and redirecting to a conversation page. It validates PDF files, creates or retrieves user data, builds a graph representatio... | def handleFileUpload():
print("handling upload")
id = request.cookies.get('user_id')
files = request.files.getlist('files')
subject = request.form['subject']
try:
user = getUser(id)
except UserNotInDatabaseException:
if not id:
return newUser()
else:
... |
def getUser(id: str) -> User:
print('in getuser')
path = userPath(id)
print(path)
if not os.path.exists(path):
raise UserNotInDatabaseException
with open (path, 'rb') as f:
user = pickle.load(f)
return user
def newUser():
user_id = str(uuid.uuid4())
try:
putUser(U... | The code handles user requests by retrieving or creating a user based on their session, managing conversations tied to a subject, and generating AI responses. It checks for existing conversations, builds them if valid, runs an agent chain with input text, updates user data, and emits the AI's response. If no conversati... | def response(text, subject, request):
id = request.cookies.get('user_id')
try:
user = getUser(id)
except UserNotInDatabaseException:
return newUser()
conversation = user.conversations.get(subject) #this is insanely inefficient but whatever
if not conversation:
response = "Sor... |
def Find_rgb_crops(red, green, blue, shift, metric):
if metric == 'mse':
rg = MSE_overlay(red, green, shift)
rb = MSE_overlay(red, blue, shift)
elif metric == 'cc':
rg = CC_overlay(red, green, shift)
rb = CC_overlay(red, blue, shift)
height = red.shape[0]
width = red.shap... | The code constructs a multi-scale pyramid of image crops by recursively downsampling color channels, finding crops at each level, scaling them, and combining results to detect features across different resolutions. | def Pyramid(red, green, blue, metric):
if red.shape[0] < 500:
return Find_rgb_crops(red, green, blue, SHIFT, metric)
new_size = red.shape[0] // 2
t_red = resize(red, (new_size, int(red.shape[1] * new_size / red.shape[0])), preserve_range=True)
t_green = resize(green, (new_size, int(green.shape[1... |
def Divide(image):
height = image.shape[0] // 3
red_channel = image[:height, :]
green_channel = image[height:height * 2, :]
blue_channel = image[height * 2:height * 3, :]
return [red_channel, green_channel, blue_channel]
def Crop_percents(image, percentage):
height = image.shape[0]
crop_heig... | The code aligns color channels of an image by cropping each channel (blue, green, red) using a percentage-based method, constructing a pyramid with a specified metric (e.g., cross-correlation), and recombining the cropped channels into a unified BGR image. The goal is to correct misalignment between color channels for ... | def align(bgr_image, metric = 'cc'):
bgr_image = img_as_ubyte(bgr_image)
channels = Divide(bgr_image)
for i in range(3):
channels[i] = Crop_percents(channels[i], 5)
crops = Pyramid(channels[0], channels[1], channels[2], metric)
red = Crop_pixels(channels[0], crops[0][0], crops[0][1], crops[0... |
def create_closed_set(self):
""" Creates and returns a data structure suitable to hold the set of nodes already evaluated"""
return set()
def create_open_set(self):
""" Creates and returns a data structure suitable to hold the set of currently discovered nodes
that are not evaluated yet.... | This code initializes a pathfinding algorithm (likely A*) by setting up grids, start/goal positions, and essential data structures (open/closed sets, scores, and path tracking). It conditionally creates these components only when both start and goal are provided, then computes the path via `run_search()` if all require... | def __init__(self, grid, start=None, goal=None):
self.grid = grid
self.start = start
self.goal = goal
self.closed_set = self.create_closed_set() if goal is not None and start is not None else None
self.open_set = self.create_open_set() if goal is not None and start is not None e... |
def cleanNoise(edged_image):
rows = edged_image.shape[0]
columns = edged_image.shape[1]
viewedPixelCoordinates = []
validPixelCoordinates = []
mapObjects = []
for x in range(rows):
for y in range(columns):
travelPath(x, y, viewedPixelCoordinates, validPixelCoordinates, mapOb... | The code processes an image to detect and clean edges for mesh generation. It converts the image to grayscale, thresholds dark areas, applies Canny edge detection, removes noise, and creates a mesh from the cleaned edges, displaying intermediate results. | def main():
print('Started => ')
loaded_image = cv2.imread(maskLocation)
loaded_image = cv2.cvtColor(loaded_image,cv2.COLOR_BGR2RGB)
gray_image = cv2.cvtColor(loaded_image,cv2.COLOR_BGR2GRAY)
non_black_image = [[0 if (j < 60) else j for j in i] for i in gray_image]
non_black_image = np.array(no... |
def togglePen():
if(penServo.value == 0):
penServo.value = 1
else:
penServo.value = 0
sleep(sleepVal+0.3)
def straightMove(x, y):
increment = 0.05 # How much we move each iteration
newX = currentX
newY = currentY
angle = math.atan2((y - newY), (x - newX))
while True:
... | This function reads coordinates from a text file to control a drawing mechanism. It processes each line: lines starting with "t" toggle the pen state, while other lines extract x/y coordinates. If the pen is down, it draws straight lines; if up, it moves without drawing. After processing all lines, it ensures the pen i... | def drawTxtFile():
file = open("positions.txt", "r")
line = file.readline()
global penDown
while line:
if line[0] == "t":
togglePen()
penDown = not penDown # Flip boolean value
else:
x = line.partition(",")[0]
y = line.partition(",")[2]
... |
def get_base_min(self, base, item):
return self.min_roq_df.loc[(self.min_roq_df['TXN - Item ID'] == item) & (self.min_roq_df['Base'] == base)]['base_min'].item()
def base_transfer(self, base, item, qty, date, item_event_list):
# instantaneous base transfer
if self.current_qoh_dict[item]['CS004'... | This code processes inventory events by updating stock levels and triggering replenishment orders. It adjusts quantities on hand (QOH) for items, ensures non-negative stock, and initiates base or central replenishment when thresholds are breached. The function checks item-specific minimums, handles transfers between ba... | def process_item_event(self, item, item_event, item_event_list):
self.current_qoh_dict[item][item_event['Base']] += item_event['Qty']
# Check for stockouts, check for reorders
# Also check for base replenishment
if self.current_qoh_dict[item][item_event['Base']] < 0:
self.cu... |
def build_chart(self, single_user_data):
for num_of_years in range(0, int(single_user_data["years_to_grow"])):
# Set the year
self.set_year_and_age(num_of_years, single_user_data["age"])
# Set annual contribution
annual_contribution = self.set_annual_contribution... | The code initializes a financial simulation class to process user data, calculate compound interest contributions, track annual and total contributions, interest earned, and end balances. It iterates through users, builds and prints charts for each, aggregates results into a combined table, and resets counters for each... | def __init__(self, *arg):
self.user_data = arg
self.compounded_table = []
self.annual_contribution = 0.0
self.total_contribution = 0.0
self.interest_earned_per_year = 0.0
self.total_interest_earned = 0.0
self.total_end_balance = 0.0
self.year = 0
s... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def train(args, model, tokenizer):
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter()
... | This code defines a training and evaluation script for a DualEncoderBert model, handling parameters like data paths, model configurations, training settings (epochs, batch sizes, learning rates), and evaluation options. It supports distributed training, resume-from-checkpoint functionality, and tasks involving entity l... | def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--data_dir",
default=None,
type=str,
required=True,
help="The input data dir. Should contain the .tsv files (or other data files) for the task.",
)
parser.add_argument(... |
def solve_isa(subject, context):
# this assumes a object|context relationship (is gold metal, is a dog a animal, etc)
# this does not work for attributes (is a ball round)
relate = vague_relation(subject, context)
if not relate:
return None
if relate.other in relate.common:
return "... | This code processes an input statement by checking a cache for pre-defined queries. If found, it generates a response using type-specific functions (e.g., 'is a', 'what is', 'examples'), sets confidence to 1.0, and returns the result. If not in the cache, it returns a default "I have no idea" response with 0.9 confiden... | def process(self, statement, additional_response_selection_parameters=None):
result = Statement("I have no idea.")
result.confidence = 0.9
if statement.text not in self.cache: # this should never happen?
return result
query = self.cache[statement.text]
self.cache = ... |
def compute_ratios(self):
'''
This function takes in cleaned data and performs some row operations to
compute intermediate values
Inputs:
cleaned_data : takes in cleaned data
Returns:
extended_data : processed data in the form of a pandas dataframe
... | The function extends the dataset by combining computed ratios, normalized values, gap metrics, and a weighted deprivation index to prepare data for visualization. It scales the 'g1_sum' column using min-max normalization and saves the final extended dataset to a CSV file. | def extend_data(self):
'''
This function extends the processed dataset with the dimensions needed
to produce our visualizations.
'''
data_extended = (
self.compute_ratios()
.join(self.raw_normalized_viz().add_suffix('_norm'))
.join(self.normali... |
def get_input():
with open("input.txt") as f:
raw_data = f.read().splitlines()
return raw_data
def parse(data):
seeds = {}
sections = {}
pointer = ""
for line in data:
if not re.match("^\d", line.split(":")[0]):
pointer = line.split(":")[0]
if pointer == "... | The main task of the code is to retrieve raw input data, parse it into structured components (seeds and parsed_data), and determine the optimal solution using the get_best function with the parsed information. | def main():
raw_data = get_input()
seeds, parsed_data = parse(raw_data)
get_best(seeds, parsed_data) |
def load_data(tag, data_dir = './data'):
with open('time_series_quarterly.pickle', 'rb') as f:
data = pickle.load(f)
training_set = pd.DataFrame(data).loc[:, [tag]].values
with open(data_dir + '/training_set', 'wb') as f:
pickle.dump(training_set, f)
return training_set
def train... | The code's main task is to train a neural network model on time-series data using specified configurations, generate projections of the model's outputs, and visualize the results. It loads data, trains a model with given hyperparameters (e.g., sequence length, hidden size, learning rate), creates 12-step projections, a... | def main(tag):
data_dir = os.path.abspath("./data")
load_data(tag, data_dir)
config = {
'seq_length' : 10,
'train_proportion' : 0.88,
'num_layers' : 1,
'num_classes' : 1,
'input_size' : 1,
'hidden_size' : 2,
'learning_rate' : 0.1,
'num_epoch... |
def objective_dir(objective, theta):
"""
Compute a unit vector of objective function sensitivities, dS/dtheta.
Parameters
----------
obj: callable
Objective function.
theta: array-like
Parameter vector at which dS/dtheta is evaluated.
... | The main task of the code is to implement a gradient descent algorithm with line search to iteratively minimize an objective function. It initializes parameters and search directions, performs line search to determine the step size, updates the parameter vector, and saves each iteration's values for tracking. The proce... | def gradient_descent(theta0):
theta_all = [theta0]
s0 = objective_dir(objective, theta0)
s_all = [s0]
# iteration control
N_max = 500
N_it = 0
# begin steepest descent iterations
# exit when max iterations exceeded
while N_it < N_max:
# uncomment line below to impl... |
def get_plurality(entries):
"""
Get the majority classification from the entries.
:param entries: the list of entries
:return: the classification
"""
value = None
weight = -1
nums = num_entries(entries)
# find the plurality entry type with the maximum weight
for e in entries:
... | The main task of the code is to recursively construct a decision tree using the Node class. It splits training data based on the feature with maximum information gain, creating internal nodes for features and leaf nodes for class labels or majority votes. Base cases handle empty data, uniform targets, or exhausted feat... | def make_tree(entries, features, parent, depth):
"""
To make the tree with Node class.
:param entries: the training data
:param features: the features list
:param parent: the parent of this (sub)tree
:param depth: the current depth
:return: the tree
"""
if not entries:
return... |
def get_ip_address():
wlan_info = netifaces.ifaddresses('wlan0')
return wlan_info[2][0]['addr']
def get_last_temp_humidity():
filename = '/home/pi/Documents/raspberry_pi/sensors/dht11/data.csv'
return get_last_dht11_reading(filename)
def get_last_soil_moisture():
filename = '/home/pi/Documents/raspb... | The main task of the code is to collect and aggregate sensor data (temperature, humidity, soil moisture, CPU temperature) along with timestamps and device information (IP address) into a structured JSON format. The function combines data from multiple sources, formats it into a dictionary, and returns it as a pretty-pr... | def get_last_data():
name = 'raspberry pi' + " (" + get_ip_address() + ")"
temp_sensor_time, humidity, temp = get_last_temp_humidity()
moisture_time, moisture = get_last_soil_moisture()
sensor_data = {
'title' : 'Time and temp!',
'time': get_time(),
'name': name,
'temp_se... |
def kappa_bf(P,T,X,Y):
Z = 1.0 - X - Y
c1 = 1.85776232
c2 = 0.3396116
c3 = -2.38950921
c4 = 3.34729929
c5 = 6.61111851
return c1*(Z/0.02)*(1.0+X)*(rho(P,T,X,Y)/1.E+4)**c2*(T/2.E+6)**c3 \
*(1.0+c4*np.exp(-(T/10**c5)**2))
def kappa_ff(P,T,X,Y):
return 4.0E+18*(X+Y)*(1+X)*rho(P,T,X,Y)*T*... | The function `kappa` calculates a total value by summing three components: `kappa_bf`, `kappa_ff`, and `kappa_es(X)`, which likely represent different physical or mathematical contributions (e.g., binary, fluid, and excess terms). It aggregates these terms to return a combined result based on inputs `P`, `T`, `X`, and ... | def kappa(P,T,X,Y):
return kappa_bf(P,T,X,Y) + kappa_ff(P,T,X,Y) + kappa_es(X) |
def kappa_bf(P,T,X,Y):
Z = 1.0 - X - Y
c1 = 1.85776232
c2 = 0.3396116
c3 = -2.38950921
c4 = 3.34729929
c5 = 6.61111851
return c1*(Z/0.02)*(1.0+X)*(rho(P,T,X,Y)/1.E+4)**c2*(T/2.E+6)**c3 \
*(1.0+c4*np.exp(-(T/10**c5)**2))
def kappa_ff(P,T,X,Y):
return 4.0E+18*(X+Y)*(1+X)*rho(P,T,X,Y)*T*... | The function `kappa` computes the total value by summing three components: `kappa_bf`, `kappa_ff`, and `kappa_es(X)`, which likely represent binary, fusion, and excess contributions, respectively, based on input parameters `P`, `T`, `X`, and `Y`.) | def kappa(P,T,X,Y):
return kappa_bf(P,T,X,Y) + kappa_ff(P,T,X,Y) + kappa_es(X) |
def rho(P,T,X,Y):
return P*mu(X,Y)*mH/(bk*T)
def eps(P,T,X,Y,XC):
return eps_cno(P,T,X,Y,XC) + eps_pp(P,T,X,Y)
def nabla(P,T,L,m,X,Y):
n_rad = nabla_RE(P,T,L,m,X,Y)
n_adb = nabla_AD(P,T)
return min(n_rad,n_adb) | This code defines a system of ordinary differential equations (ODEs) to model the radial structure of a star, computing derivatives of mass (m), pressure (P), luminosity (L), and temperature (T) with respect to radius (r). The derivatives depend on density (rho), energy generation (eps), and gradient (nabla) functions,... | def Euler(r,state):
m, P, L, T = state
dmdr = 4.0*pi*r**2*rho(P,T,X,Y)
dPdr = -(grav*m/r**2)*rho(P,T,X,Y)
dLdr = 4.0*pi*r**2*rho(P,T,X,Y)*eps(P,T,X,Y,XC)
dTdr = -(T/P)*grav*m/r**2*rho(P,T,X,Y)*nabla(P,T,L,m,X,Y)
return [dmdr, dPdr, dLdr, dTdr] |
def rho(P,T,X,Y):
return P*mu(X,Y)*mH/(bk*T)
def eps(P,T,X,Y,XC):
return eps_cno(P,T,X,Y,XC) + eps_pp(P,T,X,Y)
def nabla(P,T,L,m,X,Y):
n_rad = nabla_RE(P,T,L,m,X,Y)
n_adb = nabla_AD(P,T)
return min(n_rad,n_adb) | The code computes the derivatives of radius (r), luminosity (L), pressure (P), and temperature (T) with respect to mass (m) in a stellar model. These derivatives, using physical parameters like density (ρ), energy generation (ε), and temperature gradient (nabla), are essential for solving systems of equations governing... | def Lagrange(m,state):
r, L, P, T = state
drdm = 1.0/(4.0 * pi * r**2 * rho(P,T,X,Y))
dPdm = -(grav * m) / (4.0 * pi * r**4)
dLdm = eps(P,T,X,Y,XC)
dTdm = -(grav * m) / (4.0 * pi * r**4) * T / P * nabla(P,T,L,m,X,Y)
return [drdm, dLdm, dPdm, dTdm] |
def get_src_store(src_store=None):
if src_store is None:
return get_simfin_src_store()
else:
return src_store
def get_dfs(dfs, z=None):
"""dfs: iterable of dataframes or names of files for them (found in z)"""
if z is None:
z = get_src_store(z)
if not isinstance(next(iter(dfs... | The function `merge_group` merges multiple dataframes (`dfs`) by first retrieving them using helper functions `get_dfs` and `get_src_store`, then concatenating them while removing duplicates via `concat_with_dup_removal`. Its main task is to combine dataframes from a storage system, ensuring no duplicate entries in the... | def merge_group(dfs, keys=None, z=None):
z = get_src_store(z)
dfs = get_dfs(dfs, z)
return concat_with_dup_removal(*dfs) |
def extend_argument(model, argument):
# Dynamically find extension combinations that cannot be modularized
unmodularizable_extensions = defaultdict(set)
for endpoint in get_endpoints(argument):
# Add default extension
unmodularizable_extensions[endpoint].add(None)
# Find adjacent factors in the fact... | The code generates a scoring table evaluating argument importance in a probabilistic model. It explores argumentative trees, filters those exceeding a threshold (th=0.2), and ranks them by score magnitude. The table includes instantiated arguments, their explanations, scores, and observations, with a baseline entry for... | def generate_scoring_table(model,
target,
evidence_nodes,
th=0.2):
# Retrieve baseline logodds
baseline_p = model.baselines[target[0]].get_value(**{target[0]:target[1]})
baseline_logodds = np.log(baseline_p / (1.-baseline_p))
#... |
def sentence_iterator(in_lines):
sentence = []
for line in in_lines:
if line == None:
yield sentence
sentence = []
else:
sentence.append(line)
if sentence:
yield sentence
def file_iterator(in_file):
line = in_file.readline()
while line:
... | The code processes input text by iterating through sentences, applying the Viterbi algorithm with given counters and states to assign tags, then writes each word-tag pair to an output file, separating sentences with newlines. | def write(in_file, out_file, counter, ngram_counter, tag_counter, word_counter, states):
iterator = sentence_iterator(file_iterator(in_file))
for sentence in iterator:
tag_sequence = viterbi(sentence, counter, ngram_counter, tag_counter, word_counter, states)
for i in range(len(sentence)):
... |
def get_window_nums():
'''Get current windows numbers of all workspaces'''
ws_num = {}
for ws in i3.get_tree().workspaces():
ws_num.update({ws.name: get_workspace_window_num(ws)})
return ws_num
def diff_state(state_a, state_b):
'''Compare two window num dict, return the changed workspaces'''... | This function monitors window count changes in an i3 window manager. It compares current window numbers with a global state, identifies differences, updates the global state, and triggers change handlers for each workspace with altered window counts. | def on_window_move(i3, event):
current_state = get_window_nums()
global global_state
changed = diff_state(global_state, current_state)
global_state = current_state
for ws in changed:
on_window_num_change(ws) |
def all_genre_set(data):
data = clean_data(data)
movie_genre = data['Genre']
genre = set()
genre_set = set()
for item in movie_genre:
genre.update(str(item).strip().split(','))
for item in genre:
genre_set.add(str(item).strip())
genre_set.remove('nan')
return genre_set... | The main task of the code is to calculate the average box office profit per movie genre for a specified year, then visualize the results as a bar chart. It processes the input dataframe to clean data, aggregate genre-specific box office revenues, compute average profits by dividing each genre's total revenue by its mov... | def genre_profit_visual(dataframe,year:str):
genre_set = all_genre_set(dataframe)
data = clean_data(dataframe)
profit_by_genre = pd.Series(index = genre_set)
genre_df = movie_genre_df(dataframe)
genre_df['Box Office'] = data['Box Office']
genre_sum = genre_df.sum().sort_values(ascending = False)... |
def _findVallies(_mp, _l, _sigma):
vallies = []
N = len(_mp)
rough_detect = _mp < _sigma
indices = np.where(np.diff(rough_detect))[0]
if (len(indices) == 0):
indices = [0,N]
if (indices[0] > 0):
indices = np.insert(indices, 0, 0)
if (indices[len(indices)-1] < N):
ind... | This function identifies significant structural patterns (SSPs) in multivariate time series data by analyzing normalized RCMP values, constructing a graph of potential valleys, and applying the Maximum Weight Independent Set (MWIS) algorithm on subgraphs to detect SSPs. It processes input dimensions, computes pattern d... | def mSIMPAD(data, L, m_factor, omega=1.0):
'''
:param data: d x n real-valued array - Input Time Series
:param L: List of int - Target pattern lengths
:param m_factor: int - A factor of target pattern length to determine the maximum displacement between patterns
:param dimensions: int (OPTIONAL) - T... |
def remove_users(tweet):
"""Takes a string and removes retweet and @user information"""
tweet = re.sub('(RT\\s@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove re-tweet
tweet = re.sub('(@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove tweeted at
return tweet
def remove_has... | This function preprocesses tweets by removing users, hashtags, and avatars, converting text to lowercase, stripping punctuation and numbers, normalizing spacing, and tokenizing with lemmatization to clean and standardize text for analysis. | def preprocess_tweet(tweet):
"""Main master function to clean tweets, stripping noisy characters, and tokenizing use lemmatization"""
tweet = remove_users(tweet)
tweet = remove_hashtags(tweet)
tweet = remove_av(tweet)
tweet = tweet.lower() # lower case
... |
def get_random_state(states_list):
"""Return a random value from the list of states."""
return random.choice(states_list)
def get_random_state_property():
"""Return a random state property."""
return random.choice(state_properties())
def get_question(counter, attr, item):
"""Return response text for... | The function `ask_question` generates a quiz question by selecting a random U.S. state and a random attribute (e.g., capital, population). It stores these values in session attributes, increments a question counter, and returns a formatted question using the selected state and property. The core task is to dynamically ... | def ask_question(handler_input):
# (HandlerInput) -> None
"""Get a random state and property, return question about it."""
random_state = get_random_state(data.STATES_LIST)
random_property = get_random_state_property()
attr = handler_input.attributes_manager.session_attributes
attr["quiz_item"... |
def relative_to_assets(path: str) -> Path:
return ASSETS_PATH / Path(path)
def goAhead(self, name):
self.login.destroy()
self.layout(name)
# the thread to receive messages
rcv = threading.Thread(target=self.receive)
rcv.start()
def sendMessage(self):
self.tex... | The code creates a login interface using Tkinter, setting up a window with a background image, name entry field, and a "Continue" button. It initializes an RSA object and triggers the `goAhead` method with the entered name upon button click, while running the main application loop to display the login window. | def __init__(self):
self.x = Rsa()
# chat window which is currently hidden
self.Window = Tk()
self.Window.withdraw()
# login window
self.login = Toplevel()
# set the title
self.login.title("Login")
self.login.geometry("441x437")
s... |
def add_profile_items(self):
items = user_profile_db.get_user_profile_info()
for item in items:
item = item.to_dict()
year, month, day = item["Entry_Date"].year, item["Entry_Date"].month, item["Entry_Date"].day
item_date = datetime(day=day, month=month, year=year).str... | This code initializes an object by calling the parent class constructor, adding profile items, checking BMI, creating a label for profile info dialog content, and generating a dialog for adding profile information. | def __init__(self, **kw):
super().__init__(**kw)
self.add_profile_items()
self.check_BMI()
self.profile_info_dialog_content = MDLabel()
self.create_add_profile_info_dialog() |
def handle_error(e, error_response_str):
"""
Gets an error response and prints out an error message using the print_error function
"""
error_output = e.decode(encoding='UTF-8')
print_error(error_response_str)
print_error(error_output)
def append_content_to_file(line, file_path, overide=False):
... | The main task of the code is to modify the syslog-ng configuration file by commenting out non-s_net sources, ensuring the s_net source is present, and saving the changes. It reads the existing configuration, processes lines to add comments where necessary, replaces the original file with the modified version, and appen... | def set_syslog_ng_configuration():
'''
syslog-ng has a default configuration, which enables the incoming ports and defines that
the source pipe to the daemon will verify it is configured correctly.
'''
comment_line = False
snet_found = False
with open(syslog_ng_conf_path, "rt") as fin:
... |
def is_rsyslog_new_configuration():
"""
Checks if Rsyslog is running the new or old config format
"""
with open(rsyslog_conf_path, "rt") as fin:
for line in fin:
if "module(load=" in line:
return True
fin.close()
return False
def set_rsyslog_new_configurat... | This function configures rsyslog settings for versions 7 and above, determining whether to apply new or old configuration methods based on the result of is_rsyslog_new_configuration(), ensuring compatibility with different rsyslog versions through conditional setup. | def set_rsyslog_configuration():
'''
Set the configuration for rsyslog
we support from version 7 and above
'''
if is_rsyslog_new_configuration():
set_rsyslog_new_configuration()
else:
set_rsyslog_old_configuration() |
def is_rsyslog():
'''
Returns True if the daemon is 'Rsyslog'
'''
# Meaning ps -ef | grep "daemon name" has returned more then the grep result
return process_check(rsyslog_daemon_name) > 0
def set_rsyslog_configuration():
'''
Set the configuration for rsyslog
we support from version 7 an... | The main task of the code is to detect and configure the running Syslog daemon (rsyslog or syslog-ng) on a machine, apply necessary configurations, restart the service, check for full disk space, and confirm installation completion. If no Syslog daemon is detected, it aborts the installation with an error message. | def main():
if is_rsyslog():
print("Located rsyslog daemon running on the machine")
set_rsyslog_configuration()
restart_rsyslog()
elif is_syslog_ng():
print("Located syslog-ng daemon running on the machine")
set_syslog_ng_configuration()
restart_syslog_ng()
el... |
def certificate_generate(certs_name, tiller_namespace):
cert_path = clear_cert_path()
resources_path = SCRIPT_PATH / "resources"
script_file = resources_path / "helm-cert-gen.sh"
subprocess.run([str(script_file), str(cert_path)])
namespace_path = cert_path / "namespace.txt"
with namespace_path.... | The main task of the code is to handle Helm-related operations based on the provided command. It executes actions like certificate generation, installation, or removal by routing the command to corresponding functions. If an invalid command is given, it prints an error message and displays the help text. | def main(args, parser):
command = args.command
print("Will perform '{}' operation for helm".format(command))
if command == "cert-gen":
certificate_generate(args.certs_name, args.tiller_namespace)
elif command == "install":
helm_init(args.archive_file, args.service_account)
elif comm... |
def get_config():
appdata_path = os.path.join(os.getenv('APPDATA'),'valorant-rpc')
if not os.path.exists(appdata_path):
os.makedirs(appdata_path)
try:
with open(get_resource_path(os.path.join(appdata_path, 'config.json'))) as f:
data = json.loads(f.read())
return... | The function creates a new configuration file for 'valorant-rpc' by renaming the existing config.json to old_config.json (deleting any prior backup), then generating a fresh blank config. It ensures configuration updates by replacing the old file with a new, empty template, prompting users to adjust settings. | def create_new_config():
appdata_path = os.path.join(os.getenv('APPDATA'),'valorant-rpc')
old_config = get_config()
# rename old config, replace old config if there was already one
if os.path.exists(get_resource_path(os.path.join(appdata_path, 'old_config.json'))):
os.remove(get_resource_path(o... |
def get_out_edges(self, node):
edges = []
for e in self.get_edges():
if e[0] == node and e not in edges:
edges.append(e)
if self.t == "undirected" and e[1] == node and e not in edges:
edges.append(e)
return edges
def get_min_edges(... | This function checks if a given edge is part of the Minimum Spanning Tree (MST) by recursively verifying if there exists a path from the edge's node to the destination node using minimum-weight edges, avoiding cycles. It returns `True` if the edge is in the MST or no alternative path exists, and `False` if the destinat... | def edge_in_mst_aux(self, edge, dest, weight, visited=None):
if visited is None:
visited = set()
node = edge[1]
if node in visited:
return True
visited.add(node)
if len(self.get_out_edges(node)) == 0:
return True
node_min_edges = self.g... |
def train_crf_model(gold_stan_sentences):
"""Returns [0] a CRF model trained to recognize toponyms and ethnonyms in Herodotus' Histories
and [1] the features and [2] labels used for training it."""
features = [sent2features(s) for s in gold_stan_sentences]
labels = [sent2labels(s) for s in gold_stan_sen... | The main task of the code is to train a CRF model on Greek sentences for sequence labeling, using preloaded gold-standard annotations. It loads Greek sentences and gold labels from pickle files, trains the CRF, saves the model and features, generates predictions on new sentences, and evaluates performance. The pipeline... | def run_and_pickle():
print(f'\n{datetime.datetime.now()}: getting Greek sentences...')
# uncomment next line to get sentences from XML
# sentences = get_grk_sentences()
# change date in file name accordingly
sentences = unpickle_obj('pickle_files/grk_sentences_2020-12-03.pickle')
# uncomment ne... |
def train_crf_model(gold_stan_sentences):
"""Returns [0] a CRF model trained to recognize toponyms and ethnonyms in Herodotus' Histories
and [1] the features and [2] labels used for training it."""
features = [sent2features(s) for s in gold_stan_sentences]
labels = [sent2labels(s) for s in gold_stan_sen... | The code's main task is to unpickle Greek and gold sentences, train a CRF model using the gold data, make predictions on the Greek sentences, save the predictions, and measure the model's performance. It loads preprocessed data from pickle files, trains the CRF, applies it to unseen sentences, and evaluates accuracy, w... | def run_from_pickle():
print(f'\n{datetime.datetime.now()}: unpickling Greek sentences...')
# change date in file name accordingly
sentences_unpickled = unpickle_obj('pickle_files/grk_sentences_2020-12-03.pickle')
print(f'\n{datetime.datetime.now()}: unpickling gold sentences...')
# change date in ... |
def discard_snippet(self, res_name):
"""
Given a resource name, check to see if this snippet is known to the
system currently, and if so remove it from all of the internal lists.
"""
snippet = self._res_list.get(res_name, None)
self._discard_snippet_list([] if snippet is ... | The main task of the code is to remove an existing snippet resource, load a new or updated version, and regenerate the commands file to reflect changes. It handles both adding new snippets and updating existing ones by discarding old data, reloading the snippet, and ensuring external visibility of updates through comma... | def reload_snippet(self, res_name):
"""
Given a snippet resource file, drop any version of that snippet that
we might have, then check to see if that is an enhanced snippet and
if so update the lists.
This can be used to both add a brand new snippet as well as to update
... |
def discard_all(self, quiet=False):
"""
Completely discard all known snippets from all of the internal lists;
this puts everything into a completely clean state.
"""
if not quiet:
debug(f'discarding all snippets')
# These lists are all dictionaries wherein th... | This code initializes a singleton SnippetManager instance, sets up enhancements, clears existing data, registers a listener for settings changes to trigger snippet updates, and scans all packages for enhanced snippets. | def __init__(self, listener, enhancements):
if SnippetManager.instance is not None:
return
SnippetManager.instance = self
self.enhancements = enhancements
# Start with our data structures empty.
self.discard_all(quiet=True)
# Listen for settings changing, s... |
def add_movie_gui(listbox_movies):
top = tk.Toplevel()
top.title("Add Movie")
label_movie_name = tk.Label(top, text="Movie Name:")
entry_movie_name = tk.Entry(top)
label_genre = tk.Label(top, text="Genre (comma-separated):")
entry_genre = tk.Entry(top)
label_runtime = tk.Label(top, text="Ru... | The code creates a GUI for managing movies using Tkinter. It initializes a window with a listbox to display movie names and ratings, an "Add Movie" button to input new movies, and a double-click event to show movie details. The `display_movie_names_ratings` function populates the listbox with data, enabling user intera... | def main_gui():
root = tk.Tk()
root.title("Movie Management GUI")
listbox_movies = tk.Listbox(root, height=15, width=60)
listbox_movies.pack()
add_button = tk.Button(root, text="Add Movie", command=lambda: add_movie_gui(listbox_movies))
add_button.pack()
listbox_movies.bind("<Double-Butto... |
def _split_intercept(w):
return w[0], w[1:]
def _l1_l2_prox(w, l1_reg, group_reg, groups):
return _group_l2_prox(_l1_prox(w, l1_reg), group_reg, groups)
def _join_intercept(b, w):
m, n = w.shape
return np.concatenate([np.array(b).reshape(1, n), w], axis=0) | This function applies L1 and group L2 proximal operations to weights in a regularized model, separately handling the intercept term. It splits the input weights into intercept and coefficients, applies the specified regularization via _l1_l2_prox, then recombines them. The task involves optimizing model parameters with... | def prox(w):
b, w_ = _split_intercept(w)
w_ = _l1_l2_prox(
w_, self.l1_reg, self.group_reg_vector, self.groups_
)
return _join_intercept(b, w_) |
def updateLoader(app):
def func(value):
app.loadingPercent = value
return func
def findTonicRow(app):
bestRow = 0
bestCount = 0
for row in range(len(app.L)):
count = 0
for num in app.L[row]:
if num:
count += 1
if count > bestCount:
... | The main task of the code is to process an image by extracting musical elements (edges, tonal data, tempo, chords), configure application settings for visual display (margins, dimensions), generate MIDI files from pixel data, calculate music timing parameters, and finalize the music piece's structure and playback setti... | def doImageProc(app, name):
data = getImageData(name, updateLoader(app))
app.L = data['edges']
app.sideMargin = int((app.width - len(app.L[0])) / 2)
app.tonic = data['tonic']
app.tonality = "Major" if data['major'] else "Minor"
app.tempo = data['tempo']
app.chordProgression = data['chords']
... |
def init_Table(c, A, b):
matrix = [row[:] + [x] for row, x in zip(A, b)]
matrix.append([ci for ci in c] + [0])
return matrix
def Improve(matrix):
lastRow = matrix[-1]
return any(x > 0 for x in lastRow[:-1])
def pivot_index(matrix):
column = min(((i, x) for (i, x) in enumerate(matrix[-1][:-1]) if... | The code implements the Simplex algorithm to solve linear programming problems. It initializes a tableau with coefficients and constraints, iteratively improves the solution by selecting pivot elements, performs row operations to update the tableau, and repeats until no further improvements are possible. The function r... | def simplex_algo(c, A, b):
matrix = init_Table(c, A, b)
print("Initial matrix:")
for row in matrix:
print(row)
print()
while Improve(matrix):
pivot = pivot_index(matrix)
print("Next pivot index is=%d,%d \n" % pivot)
Abt_pivot(matrix, pivot)
print("Matrix afte... |
def ndc_rays(H, W, focal, near, rays_o, rays_d):
# UNTESTED, but fairly sure.
# Shift rays origins to near plane
t = -(near + rays_o[..., 2]) / rays_d[..., 2]
rays_o = rays_o + t[..., None] * rays_d
# Projection
o0 = -1.0 / (W / (2.0 * focal)) * rays_o[..., 0] / rays_o[..., 2]
o1 = -1.0 / ... | The function `run_one_iter_of_nerf` processes ray data to synthesize images using a NeRF model. It extracts ray origins, directions, and view directions (if enabled), prepares rays with near/far planes, and applies NDC transformations if specified. Rays are split into batches, rendered using coarse and fine networks, a... | def run_one_iter_of_nerf(model_coarse, model_fine, data_dict, options, mode="train",
encode_position_fn=None, encode_direction_fn=None):
height = data_dict['height']
width = data_dict['width']
focal_length = data_dict['focal_length']
ray_origins = data_dict['ray_origins']
ra... |
def rnn_forward(x, a0, parameters):
"""
x -- Input data for every time-step, of shape (n_x, m, T_x).
a0 -- Initial hidden state, of shape (n_a, m)
Returns:
a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
y_pred -- Predictions for every time-step, numpy array of shape (... | This code trains a recurrent neural network (RNN) by iterating through epochs, performing forward propagation to compute predictions, backpropagation to calculate gradients, and updating model parameters using gradient descent. It adjusts weights (Wax, Waa, Wya) and biases (ba, by) iteratively to minimize loss, returni... | def RNN(X, Y, parameters, epochs, lr, a0):
for i in range(epochs):
a, y_pred, caches = rnn_forward(X, a0, parameters)
gradients = backprop(caches, y_pred, Y)
#updating the weights
print("running epoch....",i+1)
print("cost is :")
cost(y_pred, Y)
parameters['Wax'] ... |
def get_edge_list(dataset_path):
data_file = open(dataset_path)
edge_list = map(lambda x: tuple(map(int, x.split())), data_file.read().split("\n")[:-1])
data_file.close()
return edge_list
def local_methods(edge_list, method):
train_list, test_list = split_data(edge_list)
train_graph = Graph(trai... | The code performs link prediction on a graph dataset using specified similarity measures. It loads an edge list from "data/fb-pages-food.csv", defaults to the 'adamic_adar' method, and applies the chosen algorithm (e.g., common neighbors, Jaccard, preferential attachment, Katz, or friendtns) to predict missing links. T... | def main():
# # default-case/ help if len(sys.argv) < 3 : print( "python link_prediction.py
# <common_neighbors/jaccard/adamic_adar/preferential_attachment/katz/friendtns> data_file_path") exit(1)
#
# # Command line argument parsing
# method = sys.argv[1].strip()
# dataset_path = sys.argv[2].str... |
def select_action(self, state: np.ndarray) -> int:
'''Select an action from the input state.'''
# epsilon greedy policy (only for training)
if self.epsilon > np.random.random() and not self.is_test:
selected_action = self.envs['train'].action_space.sample()
else:
... | This code trains a reinforcement learning agent by iterating through episodes, collecting experiences, updating the model using stored transitions, decaying exploration rate (epsilon), and periodically testing, logging results, and saving checkpoints to monitor and improve the agent's performance. | def train(self, max_episodes: int, log_freq: int, test_freq: int, save_freq: int, img_dir: str) -> None:
'''Train the agent.'''
self.is_test = False
max_steps = self.envs['train'].max_episode_steps
update_cnt = 0
start = datetime.now()
for episode in range(self.init_epi... |
def verify_course_ids(self):
# whether all course ids are valid ids
invalid_course_id_list = []
logger.debug("in checking course")
# loop through multiple course ids
for course_id in Course.objects.get_supported_courses():
if not course_id.isdigit():
... | The main task of the code is to execute a scheduled cron job that updates dashboard data by validating course IDs, then sequentially updating term, user, file, assignment, submission, and informational data from sources like UDW and BQ. It logs start/end times, errors, and status updates for monitoring. | def do(self):
logger.info("************ dashboard cron tab")
status = ""
status += "Start cron at: " + str(datetime.datetime.now()) + "\n"
invalid_course_id_list = self.verify_course_ids()
logger.debug(f"invalid id {invalid_course_id_list}")
if len(invalid_course_id_l... |
def df_default_display_settings():
pd.set_option('display.max_column', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.max_seq_items', None)
pd.set_option('display.max_colwidth', 500)
pd.set_option('expand_frame_repr', True)
def get_course_assignments(course_id):
sql=f"""se... | The code processes course assignments and user submissions, filters data based on percentage selection, calculates scores, and structures the information into a JSON response for a planning view, grouping assignments by week and due date while handling user roles and data transformations. | def assignments(request, course_id=0):
logger.info(assignments.__name__)
current_user = request.user.get_username()
df_default_display_settings()
percent_selection = float(request.GET.get('percent', '0.0'))
# json for eventlog
data = {
"course_id": course_id,
"percent_selectio... |
def process_set_command(parts):
exec("global " + parts[1] + ";" + parts[1] + " = " + parts[2])
def process_get_command(parts):
full_url = get_cur_url()
if (len(parts) > 1):
# A url has been specified
full_url = urlparse.urljoin(full_url, parts[1])
r = requests.get(full_url, verify=False... | The code defines a function `parse_input(cmd)` that parses user commands and executes corresponding actions. It splits the input into parts, checks the first part against predefined commands (e.g., `set`, `get`, `cd`, etc.), and routes the command to specific processing functions (e.g., `process_set_command`, `process_... | def parse_input(cmd):
"""
Parse the command input and execute the appropriate action
"""
parts = cmd.split(' ') # Split on spaces
args = {"set" : "variable value", "get" : "[url]", "cd" : "rel_url",
"post" : "data", "delete" : "[url]", "create" : "(vehicle | experiment | algorithm)",
... |
def log(msg):
cur_datetime = datetime.utcnow()
unix_ts = calendar.timegm(cur_datetime.utctimetuple())
print("[" + str(unix_ts) + "] " + str(msg))
def get_registered_veh_data():
r = requests.get(urlparse.urljoin(base_url, vehicles_url), verify=False)
print_response(r)
return r.json()
def get_acti... | The code automatically assigns newly registered vehicles to an active experiment and a default algorithm if they are not already assigned. It continuously monitors for new vehicles, creates experiments/algorithms as needed, and logs the configuration process, repeating this task at regular intervals. | def main():
log("Speed Harmonization Auto Configurator " + version_id + ".")
log("Connecting to " + base_url + "...")
while True:
for veh in get_registered_veh_data():
if not "expId" in veh:
# Vehicle isn't yet assigned to an experiment, assume it's also not assigned to a... |
def is_openai_model(self):
return self.model_url.lower().startswith('openai')
def download_model(
cls,
model_url: str = DEFAULT_MODEL_URL,
model_download_path: Optional[str] = None,
confirm: bool = True,
ssl_verify: bool = True,
):
"""
Download an LLM ... | The code initializes a customizable LLM (Large Language Model) with options for local or external model usage, GPU configuration, context settings, and RAG (Retrieval-Augmented Generation) parameters. It handles model download, embedding setup, and initializes components for text generation and retrieval. Key tasks inc... | def __init__(
self,
model_url=DEFAULT_MODEL_URL,
use_larger: bool = False,
n_gpu_layers: Optional[int] = None,
prompt_template: Optional[str] = None,
model_download_path: Optional[str] = None,
vectordb_path: Optional[str] = None,
max_tokens: int = 512,
... |
def read_config():
"""
Read config file. Returns a dictionary of the configuration and a boolean indicating whether or not a new config was created.
"""
exists = os.path.exists(DEFAULT_YAML_FPATH)
if not exists:
write_default_yaml()
with open(DEFAULT_YAML_FPATH, "r") as stream:
... | The code sets up a Streamlit app for interacting with a language model (LLM) via two modes: (1) **RAG-based Q&A**—users input questions, the LLM generates answers using document sources, and relevant documents are displayed with similarity scores to verify accuracy; (2) **Prompt-based problem-solving**—users submit dir... | def main():
# Page setup
cfg, cfg_was_created = read_config()
TITLE = cfg.get("ui", {}).get("title", "OnPrem.LLM")
RAG_TITLE = cfg.get("ui", {}).get("rag_title", None)
APPEND_TO_PROMPT = cfg.get("prompt", {}).get("append_to_prompt", "")
RAG_TEXT = None
RAG_TEXT_PATH = cfg.get("ui", {}).get(... |
def linear_search(my_list: list, target):
'''
# NOTE: Linear search works on sorted and unsorted lists
# NOTE: O(n) runtime; effective for small lists and unsorted lists
'''
for i in range(len(my_list)):
if target == my_list[i]:
return i
return None
def binary_search(my_list:... | The code tests and compares the performance of linear search and binary search on a large sorted list, while demonstrating various sorting algorithms (selection, bubble, heap, merge sort) on small example lists. It measures runtime for searches and outputs sorted results for each sorting method, illustrating algorithm ... | def main():
NUM = 10000000
sortedList = []
for i in range(NUM):
sortedList.append(i)
# linear search
start_time = time.time()
result = linear_search(sortedList, 100000)
end_time = time.time()
runtime = end_time - start_time
print(f"Linear Search: target found in index {res... |
def eye(n, a):
r = [[0] * n for i in range(n)]
for i in range(n):
r[i][i] = a
return r
def lcm(a, b):
return a * b / gcd(a, b)
def lcm_list(a):
mult = a[0]
for x in a[1:]:
if x != 0:
mult = lcm(mult, x)
return mult | This function computes the inverse of a square matrix using Gauss-Jordan elimination with integer arithmetic. It handles 1x1 and 2x2 matrices directly, then applies row operations with LCM-based scaling to avoid fractions. The matrix is augmented with an identity matrix, transformed via row swaps and eliminations, and ... | def matrixInvScaled(a):
m = len(a)
inv = []
if m == 1:
inv = [1]
if m == 2:
inv = [[a[1][1], -a[0][1]], [-a[1][0], a[0][0]]]
# gauss-jordan reduction
else:
a.extend(eye(m, 1))
n = len(a)
# change from col,row to row, col notation
c = [list(row) for row in zip(*a)]
for p in range(m): # select ... |
def lcm_list(a):
mult = a[0]
for x in a[1:]:
if x != 0:
mult = lcm(mult, x)
return mult
def matrixMult(a, b):
zip_a = list(zip(*a))
return [[sum(el_a*el_b for el_a, el_b in zip(row_a, col_b)) for row_a in zip_a] for col_b in b]
def matrixInvScaled(a):
m = len(a)
inv = []
if m == 1:
inv = [1]
if m == ... | The code computes the first column of the product of matrix $ B $ and the inverse of $ (\sigma I - A) $, where $ A $ and $ B $ are submatrices derived from the input matrix. It first scales rows to align their sums with the LCM of row sums ($ \sigma $), constructs $ A $ and $ B $, and then performs matrix inversion and... | def answer(matrix):
n = len(matrix)
sums = [sum(matrix[i]) for i in range(n)]
sigma = lcm_list(sums)
# dimensions of submatrix A
nA = len([x for x in sums if x != 0])
# scales each nonzero col up
for i in range(nA):
multiplier = sigma / sums[i]
for j in range(n):
matrix[i][j] *= multiplier
A = [matri... |
def parse_arguments():
parser = argparse.ArgumentParser(description="Calculate some statistics about DNA sequences.")
parser.add_argument('--input', nargs='+', required=True, help='Input file names (space-separated)')
parser.add_argument('--output', action='store_true')
parser.add_argument('--basecount'... | The code processes input DNA sequence files to perform specified analyses (base count, reverse complement, GC content, GC islands) based on command-line arguments, collects results, and outputs them to a file or console, with an error check for more than three input files. | def main():
args = parse_arguments()
files = args.input
results = []
for file in files:
if len(files) > 3:
print("error")
else:
with open(file, 'r') as f:
sequence = f.read()
sequence = sequence.lower()
if args.baseco... |
def _load_inter_feat(self, token, dataset_path):
"""Load interaction features.
If ``config['benchmark_filename']`` is not set, load interaction features from ``.inter``.
Otherwise, load interaction features from a file list, named ``dataset_name.xxx.inter``,
where ``xxx`` if from ``con... | The main task of the code is to load dataset features in a structured sequence: first interaction features, then optional user/item features, and finally additional features if configured. It uses the dataset name (token) and path to retrieve and store these features as instance variables for further processing. | def _load_data(self, token, dataset_path):
"""Load features.
Firstly load interaction features, then user/item features optionally,
finally load additional features if ``config['additional_feat_suffix']`` is set.
Args:
token (str): dataset name.
dataset_path (st... |
def _build_feat_list(self):
"""Feat list building.
Any feat loaded by Dataset can be found in ``feat_list``
Returns:
builded feature list.
Note:
Subclasses can inherit this method to add new feat.
"""
feat_list = [feat for feat in [self.inter_fe... | The main task of the code is to preprocess data through K-core filtering, value-based filtering, ID remapping, missing value imputation, normalization, and preloading weight matrix initialization. It builds feature lists, prepares user-item features, fills NaN values, sets labels via thresholds, and ensures data is str... | def _data_processing(self):
"""Data preprocessing, including:
- K-core data filtering
- Value-based data filtering
- Remap ID
- Missing value imputation
- Normalization
- Preloading weights initialization
"""
self.feat_list = self._build_feat_list... |
def _get_preset(self):
"""Initialization useful inside attributes.
"""
self.dataset_path = self.config['data_path']
self._fill_nan_flag = self.config['fill_nan']
self.field2type = {}
self.field2source = {}
self.field2id_token = {}
self.field2seqlen = self... | The main task of the code is to load a dataset from scratch by first initializing attributes, then loading data from atomic files, and finally preprocessing the dataset. The method logs the process, retrieves presets and field configurations, loads data using the dataset name and path, and applies data processing steps... | def _from_scratch(self):
"""Load dataset from scratch.
Initialize attributes firstly, then load data from atomic files, pre-process the dataset lastly.
"""
self.logger.debug('Loading {} from scratch'.format(self.__class__))
self._get_preset()
self._get_field_from_config(... |
def readable_date_format(date):
# convert datetime object to desired string format
date_obj = datetime.strptime(date, "%Y-%m-%d")
return date_obj.strftime("%Y-%m-%d %H:%M:%S")
def date_formated_timestamp():
"""
This function get the current datetime
"""
now = datetime.now()
year = now.ye... | The code extracts a job's posted date from a webpage using BeautifulSoup, formats it, compares it with the current date, and uses either `get_reed_jobs` or `get_reed_jobs_different_format` to process job data based on successful parsing, handling exceptions to ensure data retrieval. | def grab_jobs_fields(url):
html_text = requests.get(url).text
soup = BeautifulSoup(html_text, 'lxml')
# get the posted date of a Job
meta_tag = soup.find("meta", itemprop="datePosted")
posted_date = meta_tag.get("content")
# print(posted_date)
posted_formated_date = readable_date_format(pos... |
def provider_data_merging(cat,table_names,table_name,prov_tables_list,o_merging=False,para_match=False):
"""
Merges the data from the different providers.
:para cat:
:type cat: list(astropy.table.table.Table)
:para table_names:
:type table_names: list(str)
:para str table_name:
:p... | The function integrates multiple astronomical data sources into a unified database by merging, cleaning, and structuring tables. It combines provider data, assigns unique identifiers, handles empty columns, and joins tables using object IDs. Specific processing includes parameter merging for stars/planets, replacing nu... | def building(prov_tables_list,table_names,list_of_tables):
"""
This function builds the tables for the LIFE database.
:param prov_tables_list: Containing simbad, grant kennedy, exomercat, gaia
and wds data.
:type prov_tables_list: list(astropy.table.table.Table)
:param table_names: Obj... |
def sptype_string_to_class(temp,ref):
"""
Extracts stellar parameters from spectral type string one.
This function extracts the temperature class, temperature class number
and luminocity class information from the spectral type string (e.g.
M5V to M, 5 and V). It stores that information in the for... | The function `provider_life` processes SIMBAD data to generate provider metadata, stellar parameters (temperature, radius, mass) using Eric E. Mamajek's model, and a sources table. It transforms coordinates, calculates distances, handles null values, adds references, and populates output tables with derived data. The r... | def provider_life(table_names,life_list_of_tables):
"""
Loads SIMBAD data and postprocesses it.
Postprocessing enables to provide more useful information. It uses a model
from Eric E. Mamajek to predict temperature, mass and radius from the simbad
spectral type data.
:param table_nam... |
def get_forward_rate(self, tenor):
tenor_year = tenorstring_to_year(tenor)
spot_rate = np.interp(tenor_year, self.parameters['FORWARDRATES'][:,0], self.parameters['FORWARDRATES'][:,1])
return spot_rate
def get_zcb_rate(self, tenor):
zcb_price = self.get_zcb_price(tenor)
... | The code plots financial rates (forward, ZCB rates/prices) over a specified time range by generating time points, fetching model outputs based on `rate_type`, and visualizing them with appropriate titles. If `rate_type` is invalid, it returns an error. | def plot_model(self, start_time, end_time, rate_type = 'FORWARDRATES', points = 100):
#plot forward rates
time_points = np.linspace(start_time, end_time,points)
if rate_type.upper() == 'FORWARDRATES':
model_output = [self.get_forward_rate(x) for x in time_points]
... |
def get_train_tfdataset(self) -> tf.data.Dataset:
"""
Returns the training :class:`~tf.data.Dataset`.
"""
if self.train_dataset is None:
raise ValueError("Trainer: training requires a train_dataset.")
self.num_train_examples = self.train_dataset.reduce(tf.constant(0)... | This code trains a machine learning model using TensorFlow, configuring optimizers, gradient accumulation, and checkpoint management. It initializes training parameters, loads pre-trained checkpoints if available, logs training metrics, and performs iterative training over epochs/steps. The method handles mixed-precisi... | def train(self) -> None:
"""
Train method to train the model.
"""
train_ds = self.get_train_tfdataset()
if self.args.debug:
tf.summary.trace_on(graph=True, profiler=True)
self.gradient_accumulator.reset()
if self.args.max_steps > 0:
t_to... |
def get_input_spaces(self):
for i in range(self.number_of_input_spaces):
self.spaces.append(Space(self.sizes[0], self.sizes[0], index=i,
num_channels=self.num_channels,
prunable=False, is_input=True,
... | The main task of the code is to construct input spaces, configure them via `set_spaces()`, build classifiers if specified by `number_of_classes`, and generate a graph using `get_graph()`. This method orchestrates space initialization, classifier setup, and graph creation for a machine learning or graph-based system. | def build_spaces(self):
self.get_input_spaces()
self.set_spaces()
if self.number_of_classes is not None:
self.build_classifiers()
self.graph = get_graph(self) |
def _terminalSymbolsGenerator(self):
"""Generator of unique terminal symbols used for building the Generalized Suffix Tree.
Unicode Private Use Area U+E000..U+F8FF is used to ensure that terminal symbols
are not part of the input string.
"""
UPPAs = list(list(range(0xE000, 0xF8FF... | The function constructs a Generalized Suffix Tree (GST) from an array of strings by concatenating them with unique terminal symbols, then builds the tree structure and labels nodes to represent the generalized suffixes of all input strings. | def _build_generalized(self, xs):
"""Builds a Generalized Suffix Tree (GST) from the array of strings provided.
"""
terminal_gen = self._terminalSymbolsGenerator()
_xs = ''.join([x + next(terminal_gen) for x in xs])
self.word = _xs
self._generalized_word_starts(xs)
... |
def _check_input(self, input):
"""Checks the validity of the input.
In case of an invalid input throws ValueError.
"""
if isinstance(input, str):
return 'st'
elif isinstance(input, list):
if all(isinstance(item, str) for item in input):
re... | This code constructs a Suffix Tree (ST) or Generalized Suffix Tree (GST) based on input type. For single strings, it appends a terminal symbol and builds an ST. For lists of strings, it builds a GST. The `_check_input` method determines the input type, triggering either `_build` (for ST) or `_build_generalized` (for GS... | def build(self, x):
"""Builds the Suffix tree on the given input.
If the input is of type List of Strings:
Generalized Suffix Tree is built.
:param x: String or List of Strings
"""
type = self._check_input(x)
if type == 'st':
x += next(self._terminal... |
def get_rss_data(self):
'''Retrieve RSS Content'''
try:
data = feedparser.parse(self.rss_url)
self.validate_rss_data(data)
except Exception as exception:
sys.exit('Error getting RSS data - {}'.format(exception))
self.data = data
def build_inc(self):
... | The code's main task is to automate torrent downloading via RSS feeds by fetching RSS data, processing incoming torrent entries (cleaning and saving them as JSON), and initiating downloads. It sequentially retrieves RSS content, filters/cleans incoming torrents, stores processed data, and executes torrent downloads. | def start(self):
'''Loop over RSS config to download .torrents files'''
# ----------------------- #
# --- get RSS content --- #
# ----------------------- #
self.get_rss_data()
# --------------------------- #
# --- Determine Incomming --- #
# -------------... |
def getNextPos(self, p, a):
if a not in self.getValidActions(p): return p
x, y = self.actions[a]
pos = (p[0]+x, p[1]+y)
val = self.state[(p[0]+x, p[1]+y)]
return (self.pos[0]+(x*val), self.pos[1]+(y*val))
def getScore(self):
return np.count_nonzero(self.state==0) / (self... | The code extracts features from a game state for machine learning, including a bias term, current score, normalized adjacent tile values, highest adjacent value, and valid action count. Features are scaled by dividing all values by 10.0 to normalize input ranges, aiding models in learning effective decision patterns. | def getFeatures(self, a):
features = util.Counter()
features['bias'] = 1.0
next_pos = self.getNextPos(self.pos, a)
features['score'] = self.getScore()
# sum of surrounding values
features['adjacent'] = np.sum(self.getAdjacent(next_pos))/5
# highest value move ... |
def getValidActions(self, pos):
idx = 0
valid = ['q', 'w', 'e', 'a', 'd', 'z', 's', 'c']
for i in range(-1, 2, 1):
for j in range(-1, 2, 1):
if i == 0 and j == 0:
pass
else:
if not self.isValid(i, j, pos):
... | The code calculates a reward value for a given action in a grid-based environment. It returns 0 for invalid actions, -10 if the next position has only one valid action (a dead end), and otherwise combines the distance from the center and the number of available actions at the next position into a normalized reward valu... | def getReward(self, a):
if a not in self.getValidActions(self.pos): return 0
next_pos = self.getNextPos(self.pos, a)
if len(self.getValidActions(next_pos)) <= 1:
return -10
return (self.distance_from_center(next_pos) * 2 + len(self.getValidActions(next_pos))) / 3 |
def alpha_min_max(model_dat):
"""estimate minimal alpha ensuring positive-definite Hessian
and give maximal alpha to search over
starting at regularization tikh (= alpha * directnorm)
being a certain fraction of observed y variance."""
# alpha_max_tmp
fraction = 0.002 # ToDo: define gl... | The function estimates parameters of a linearized structural model by optimizing alpha and degrees of freedom (dof), computes direct, total, and mediation effects with standard errors, and validates Hessian matrix consistency using algebraic, automatic, and numeric methods, returning all results in a structured diction... | def estimate_effects(model_dat):
"""nonlinear estimation of linearized structural model
using theoretical direct effects as starting values""" # ToDo: reintroduce # yyyy
if model_dat["alpha"] is None:
if model_dat["dof"] is not None:
raise ValueError("dof is determined together with... |
def adjacency(model_dat):
"""numeric function for model and direct effects, identification matrics"""
define_equations = model_dat["define_equations"]
xvars = model_dat["xvars"]
yvars = model_dat["yvars"]
ndim = len(yvars)
mdim = len(xvars)
def equations_alg(xvars, bias=0, bias_ind=0):
... | The main task of the code is to specify a model structure, compute direct, total, and mediation effects using numerical and symbolic methods, and prepare data for analysis. It calculates theoretical effects, demeaned variables, identification matrices, and updates the model with computed statistics, ensuring consistenc... | def create_model(model_dat):
"""specify model and compute effects"""
# dimensions
ndim = len(model_dat["yvars"])
mdim = len(model_dat["xvars"])
pdim = len(model_dat["ymvars"])
selvec = zeros(ndim)
selvec[[list(model_dat["yvars"]).index(el) for el in model_dat["ymvars"]]] = 1
selmat = di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.