dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def moveDir(self, dire):
#print(dire)
#print(self.y)
if dire == '<':
if self.x-1 >= 0 and not self.didCol(self.x-1, 0):
self.x -= 1
elif dire == '>':
if self.x+self.w <= 6 and not self.didCol(self.x+1, 0):
#print("e", self.x)
... | This code moves an object by updating its position using get_next_move(), checks for downward collision, and updates a grid's height array by setting bits corresponding to the object's shape. It adjusts currentH to track the maximum height occupied after placing the object. | def move(self):
self.x = 2
global currentH
#print("H", currentH)
self.y = currentH + 4
#print("Y", self.y)
#print(self.y)
global get_next_move
while True:
self.moveDir(get_next_move())
if self.moveDown() == False:
... |
def moveDir(self, dire):
#print(dire)
#print(self.y)
if dire == '<':
if self.x-1 >= 0 and not self.didCol(self.x-1, 0):
self.x -= 1
elif dire == '>':
if self.x+self.w <= 6 and not self.didCol(self.x+1, 0):
#print("e", self.x)
... | The code moves a block by updating its position using get_next_move(), checks for downward collisions, and updates the game grid's height values based on the block's shape, ensuring currentH tracks the maximum height affected by the block's placement. | def move(self):
self.x = 2
global currentH
#print("H", currentH)
self.y = currentH + 4
#print("Y", self.y)
#print(self.y)
global get_next_move
while True:
self.moveDir(get_next_move())
if self.moveDown() == False:
... |
def _is_str(candidate):
"""Returns whether a value is a string."""
return isinstance(candidate, StrType)
def _decode(hashid, salt, alphabet, separators, guards):
"""Helper method that restores the values encoded in a hashid without
argument checks."""
parts = tuple(_split(hashid, guards))
hashid... | The function `decode` restores a tuple of numbers from a given `hashid` string using the instance's salt, alphabet, and other parameters. It validates the input, decodes the hashid into numbers, and verifies the result by re-encoding. If validation fails or errors occur, it returns an empty tuple. The task is to revers... | def decode(self, hashid):
"""Restore a tuple of numbers from the passed `hashid`.
:param hashid The hashid to decode
>>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456')
>>> hashids.decode('1d6216i30h53elk3')
(1, 23, 456)
"""
if not hashid or not _... |
def generate_prologue(release_type, bundle_name, database_name):
if database_name: yield f"USE {database_name}\nGO\n"
yield f"DECLARE @v_release_bundle VARCHAR(60) = '{bundle_name}';"
yield f"DECLARE @v_released_at DATETIME = release.fn_released_at('{release_type}', '{bundle_name}');"
yield """IF @v_rel... | The code generates a release bundle file at a specified path by writing a prologue, including files from a repository that match a given pattern, and appending an epilogue. It logs used/skipped files, writes file contents with separators, and structures the bundle with headers/footers based on release type and database... | def create_release_bundle(bundle_filepath, database_name, release_type, bundle_name, repo, rel_filepaths, code_pattern):
logger.info("Generate a release file at %s from repo %r using files matching '%s'", bundle_filepath, repo, code_pattern)
with open(bundle_filepath, "w") as f:
#
# Write the bu... |
def parse_dburi_ex(dburi):
"""Break out a URI-style database connection into its component parts
The most common string will be simply <server>/<database> (eg SVR09/TDI)
In addition, as username/password can be included following the URI
convention, eg tim:secret@SVR09/TDI
If needed, the scheme can... | The main task of the code is to generate a release bundle (SQL script) from a repository's changes between two commits, either specified by the user or determined from the database's last commit and the repo's current HEAD. It creates a temporary repo clone, identifies modified files, constructs the bundle with the spe... | def main(
repo_dirpath,
release_tag,
dburi,
from_commit=None,
to_commit=None,
files_filepath=None,
code_pattern=CODE_PATTERN,
releases_relpath=RELEASES_RELPATH,
release_type=RELEASE_TYPE
):
"""Produce a release bundle from a repo destined for a target database and then
tag th... |
def prepare_args():
parser = argparse.ArgumentParser(
description='Extract data from facebook newsfeed')
parser.add_argument('--chrome-path', type=str, metavar='PATH',
default='./chromedriver', help='Specify chromedriver path')
parser.add_argument('-k', '--keyword',
t... | (The code automates Facebook login via Selenium, scrapes posts/videos, extracts metadata (clicks, media URLs, engagement metrics) using BeautifulSoup/requests, and stores results in a JSON file. It handles shortened URLs, parses content, and optionally saves data to a database.) | def main():
args = prepare_args()
print('Starting selenium...')
driver = prepare_driver(executable_path=args.chrome_path)
# Login into facebook
print('Login into facebook...')
login(driver, args.username, args.password)
# pdb.set_trace()
kwargs = kwargs_from_cmd(args)
results = {
... |
def get_Ha_map(MaNGA_ID, snr_cutoff = 3):
#Returns the Ha flux map and the Ha noise flux map, with the required S/N ratio
#inputs: MaNGA_ID, Ha line S/N cutoff (by default taken to be 3)
#H alpha map
hdul = get_fits_hdul(MaNGA_ID)
emline_maps = np.copy(hdul[3].data)
ha = np.copy(emlin... | The function computes dust-corrected star formation rate (SFR) maps and their uncertainties (in solar masses/yr and solar masses/yr/kpc²) for a given MaNGA galaxy ID. It uses Ha luminosity, applies dust correction, converts to SFR via the Kennicutt 1998 formula, and calculates surface density by dividing by spaxel area... | def get_SFR_map(MaNGA_ID, snr_cutoff = 3):
#returns the dust corrected SFR map (solar masses/yr) and the sigma SFR map (solar masses/yr/kpc^2) and the respective error maps. No dust correction is applied to the error maps.
#input: MaNGA_ID, S/N cutoff on the 4 BPT emission lines (by default taken to be 3)
... |
def get_Ha_map(MaNGA_ID, snr_cutoff = 3):
#Returns the Ha flux map and the Ha noise flux map, with the required S/N ratio
#inputs: MaNGA_ID, Ha line S/N cutoff (by default taken to be 3)
#H alpha map
hdul = get_fits_hdul(MaNGA_ID)
emline_maps = np.copy(hdul[3].data)
ha = np.copy(emlin... | This function computes the dust-corrected H-alpha (Ha) luminosity map and its corresponding error map for a given MaNGA galaxy ID. It applies dust correction to the Ha flux map using extinction values, scales the corrected flux by the square of the luminosity distance, and converts it to luminosity units (erg/s). The e... | def get_Ha_lum_map(MaNGA_ID, snr_cutoff = 3):
#input: MaNGA_ID, S/N cutoff on the 4 BPT lines (by default taken to be 3)
#returns: dust corrected Ha luminosity and its error map. No dust correction is applied to the error map.
Ha, Ha_noise = get_Ha_map(MaNGA_ID, snr_cutoff)
A_Ha = get_A_Ha_map(MaNG... |
def get_gas_metallicity_map(MaNGA_ID, snr_cutoff = 3):
#returns the gas metallicity map for the given object and the corresponding error map
#Inputs: MaNGA_ID, and S/N cutoff for all the BPT lines (by default taken to be 3)
oiii, oiii_noise, nii, nii_noise, ha, ha_noise, hb, hb_noise = get_bpt_lines_ma... | The function processes MaNGA galaxy IDs to combine and clean spaxel data, returning flattened arrays of stellar mass (SMD), gas metallicity (Z), and their errors. It filters non-star-forming/compounding regions, removes NaNs and invalid values, ensuring outputs contain only valid, positive data for further analysis. | def get_Z_M_arrays(MaNGA_IDs, snr_cutoff = 3):
#Inputs: an array of MaNGA_IDs of galaxies whose combined resolved GMMS is to be plotted. S/N cutoff on the 4 BPT lines
#Returns: the combined flattened arrays of stellar mass and gas metallicity of the spaxels of the galaxies provided. For gas metallicity, the cor... |
def get_fits_hdul(MaNGA_ID):
#retrieves the hdul of the fits file of our object
#input: MaNGA ID of the galaxy, as a string of the form "aaaa-aaaa"
hdul = fits.open('address5') #address5 should be a function of MaNGA_ID - the actual location where the datacube is stored
return hdul
def get_reds... | The function `get_trimmed_Z_M_arrays` processes galaxy data from MaNGA surveys by excluding spaxels (pixels) in specified spatial regions and non-star-forming/composite regions. It calculates gas metallicity (Z), stellar mass density (M), and their uncertainties, masks out invalid regions (based on distance from the ga... | def get_trimmed_Z_M_arrays(MaNGA_IDs, snr_cutoff = 3, distance_range = np.array([0,2])):
#In the GMMS, exclude spaxels of a certain spatial region in the galaxies. The spatial region is described by distance_range = np.array([a,b]). a and b are in units of kpc. Spaxels which reside in this distance range from the c... |
def get_fits_hdul(MaNGA_ID):
#retrieves the hdul of the fits file of our object
#input: MaNGA ID of the galaxy, as a string of the form "aaaa-aaaa"
hdul = fits.open('address5') #address5 should be a function of MaNGA_ID - the actual location where the datacube is stored
return hdul
def get_phot... | The function calculates the central stellar velocity dispersion (sigma) within a specified aperture (default: 1 kpc) for a given MaNGA galaxy, using photometric parameters and FITS data. It converts the aperture size to spaxels, extracts sigma and error maps, computes the radial profile with the chosen statistic (e.g.,... | def get_central_sigma(MaNGA_ID, binsize = 1, stat = "mean"):
#Returns the mean (stat = "mean", "median", "quad" (RMS), "sum") stellar velocity dispersion over a 1 kpc (binsize) central aperture of the galaxy
hdul = get_fits_hdul(MaNGA_ID)
center, FWHM, pos_angle, Re_spaxels, ellipticity, inclination = ... |
def get_SFR_map(MaNGA_ID, snr_cutoff = 3):
#returns the dust corrected SFR map (solar masses/yr) and the sigma SFR map (solar masses/yr/kpc^2) and the respective error maps. No dust correction is applied to the error maps.
#input: MaNGA_ID, S/N cutoff on the 4 BPT emission lines (by default taken to be 3)
... | The code processes multiple galaxies' MaNGA IDs to compile combined arrays of stellar mass (smd) and SFR surface density (sigma_sfr) with their errors. For each galaxy, it filters spaxels using BPT diagrams, masks non-star-forming regions, flattens valid data, and aggregates results. The output includes three flattened... | def get_SFR_M_arrays(MaNGA_IDs, snr_cutoff = 3): #Star-formation Main Sequence (SFMS)
#Inputs: an array of MaNGA_IDs of galaxies whose combined resolved SFMS is to be plotted. S/N cutoff on the 4 BPT lines
#Returns: the combined flattened arrays of stellar mass and SFR surface density of the spaxels of the gala... |
def get_fits_hdul(MaNGA_ID):
#retrieves the hdul of the fits file of our object
#input: MaNGA ID of the galaxy, as a string of the form "aaaa-aaaa"
hdul = fits.open('address5') #address5 should be a function of MaNGA_ID - the actual location where the datacube is stored
return hdul
def get_reds... | The main task of the code is to process galaxy data from MaNGA IDs by excluding spaxels in specified spatial regions (defined by distance_range) and non-star-forming regions (via BPT classification). It computes trimmed arrays of surface mass density (SMD), star formation rate (SFR), and their errors, removing NaNs, ne... | def get_trimmed_SFR_M_arrays(MaNGA_IDs, snr_cutoff = 3, distance_range = np.array([0,2])):
#In the SFMS, exclude spaxels of a certain spatial region in the galaxies. The spatial region is described by distance_range = np.array([a,b]). a and b are in units of kpc. Spaxels which reside in this distance range from the... |
def get_coordinates(MaNGA_ID):
'''
Gets the equitorial coordinates of the given galaxy from the primary header of the datacube.
input: MaNGA_ID of the galaxy, as a string of the form "aaaa-aaaa"
returns: 2-tuple (ra,dec) of the galaxy, extracted from the primary header of the datacube
'''
hdul ... | The function computes radial profiles for stellar mass density (sigma_star), star formation rate (sigma_sfr), and specific star formation rate (ssfr) for a list of galaxies. It bins data by galaxy effective radius (Re) or kpc, applies BPT classification filters, and calculates statistical values (mean, median, etc.) pe... | def get_radial_profile_catalog(MaNGA_IDs, method = "Re", binsize = 0.2, stat = "mean", snr_cutoff = 3, BPT_cut = True, deproject = True):
#Inputs: list of galaxies (MaNGA_IDs) whose radial profiles are needed, method (if "Re" then radial profiles are binned with respect to Re, if "kpc" then radial profiles are binn... |
def add_event(event_data: dict) -> dict:
event = event_collection.insert_one(event_data)
new_event = event_collection.find_one({"_id": event.inserted_id})
return event_helper(new_event)
def add_repeat_event(event: dict, user: dict, user_id: str) -> dict:
if event['repeat'] == 'weekly':
repeat_co... | This function adds an event to a user's data, updating participants, invites, and handling recurring events. It retrieves the user, validates the creator, adds the event, manages repeats, invites participants, updates user data, and handles exceptions by deleting the event if a user is not found. | def add_event_to_users(user_id: str, event_data: dict) -> dict:
try:
user = retrieve_user(_id=ObjectId(user_id))
if user["email"] not in event_data["participants"]:
event_data['participants'].append(user["email"])
retrieve_user(email= event_data['creator'])
new_event = ad... |
def get_license_bin_crop(img):
"""
@brief detects parking/license bin contour in an image and returns img cropped to that contour
@param img , cv2 image
@return cropped cv image
"""
def most_frequent_clr(img):
colors, count = np.unique(img.reshape(-1,img.shape[-1]), axis=0, return_coun... | The main task of the code is to process images to detect and recognize license plates and their associated ID characters. It crops license plates, applies OCR to identify characters, calculates confidence scores, and publishes the highest-confidence ID and license plate information. The code handles image preprocessing... | def process_loop(self):
if(self.empty):
return
else:
crop = get_license_bin_crop(self.latest_img)
self.empty = True
if(crop is None):
return
cnts = None
try:
cnts,_ = find_license_plate_contours(cro... |
def analyse_cm_position(board: chess.Board, chessmove, chessengine: chess.engine, rcobject: RC):
for limit in [SHORTTIME, LONGTIME]:
# engine score
search_limit = chess.engine.Limit(time=limit)
infos_engine = chessengine.analyse(board, search_limit, multipv=1)
# best_move = infos_... | The main task of the code is to analyze chess games from a PGN file by processing each move sequence, generating position hashes, and evaluating positions using a chess engine for specific problem types (e.g., "ChooseMove" and "Realchess"). It extracts move strings, tracks board states, and writes analysis results to f... | def main():
global simple_engine
# global maxblindmoves
# 1. variables
maxblindmoves = 24
simple_engine = chess.engine.SimpleEngine.popen_uci(ENGINENAME)
myengine = chess.engine.SimpleEngine.popen_uci(ENGINENAME)
myengine.configure({"SyzygyPath": TBPATH})
# 2. read pgn, pgn to game
... |
def copy_snapshot(self, t, state):
sto = {'t': t, 'state': deepcopy(state)}
return sto
def get_snapshots(self):
for snapshot in self.snapshots:
yield snapshot
def apply_change(self, step):
# isForward
if self.current_state['t'] <= step:
for change in self.... | The function computes a system state at time `t` by retrieving an existing snapshot if available, or generating a new one by applying deltas from the closest existing snapshot. It updates the current state, saves the computed snapshot, and optionally exports it as a PNG image, ensuring efficient state transitions throu... | def compute_snapshot(self, t, png=False):
# snapshot already exists
if t in self.snapshots:
self.current_state = self.copy_snapshot(t, self.snapshots[t])
return
# searches for the closest snapshot O(n) TODO improve to optimized search
closest_snapshot = -1
... |
def get_type_of_score(name_of_file):
## Gets type of score
d = {
'pca_eucl': 'pca_euclideian',
'fst': 'Fst',
'pca_manh': 'pca_manhattan',
'pca_bray':'pca_braycurtis',
'tsne_bray':'tsne_braycurtis',
'tsne_eucl':'tsne_euclideian',
'tsne_manh':'tsne_manhatta... | The main task of the code is to determine the type of data (e.g., PCA, t-SNE, Fst) and plotting parameters from a filename and file header, then generate 2D or 3D visualizations using appropriate functions based on the data type and complexity. It reads input data, identifies the plot type, and delegates rendering to s... | def create_plot(filename):
## Distinquises type of file that is about to be plotted and type of plot that will be used
with open(filename,'r') as f:
# if 'pca_eucl' in filename:
# type_of_score = 'pca_euclideian'
# elif 'pca_manh' in filename:
# type_of_sco... |
def make_distance(dist_el):
maximum = 0
for i in dist_el:
numbers = i.split('=')[0].split(',')
numbers = [int(x) for x in numbers]
max_num = max(numbers)
if max_num > maximum:
maximum = max_num
number_of_pops = maximum
Distance = np.zeros((number_of_p... | The main task of the code is to prepare and configure parameters for a population genetics simulation using msprime. It processes input data (DE, migration matrices, population sizes, etc.), validates the number of populations, constructs a configuration dictionary, and initiates a simulation with specified demographic... | def main():
de_list = []
for i in DE:
de = i.split(' ')
de_list.append(de)
de_list = [de_list]
Samples = simvar.samples
N = [simvar.N]
R = [simvar.R]
Length = [simvar.length]
mutation_rate = [simvar.mutation_rate]
recombination_rate = [simvar... |
def Hierarchical_Preperation(data):
new_data=[]
for i in range(len(data)):
new_data.append([np.array([i]),data[i]])
return new_data
def biggest_norm(data):
n=len(data)
norms=np.zeros(n)
for i in range(n):
norms[i]=np.linalg.norm(data[i][1])
return np.argmax(norms)
def get_met... | The code performs hierarchical clustering on a set of points, grouping them into a specified number of clusters. It initializes by selecting a reference point, computes pairwise distances, iteratively merges the closest clusters until the desired number of clusters is reached, and finally assigns each point to its corr... | def Hierarchical_Clustering(points,clusters_amount,metric):
data=Hierarchical_Preperation(points)
tmp_points=points.copy()
c = biggest_norm(data)
c_point = data[c]
data.pop(c)
tmp_points.pop(c)
#D=get_metric_matrix(tmp_points,Centroid_Distance,c_point)
D=get_metric_matrix(tmp_points,Euli... |
def _populate_from_globals(param_name: str, value: any, param_type: str, gbls: Dict[str, Dict[str, Dict[str, Any]]]):
if value is None and gbls is not None:
if 'parameters' in gbls:
if param_type in gbls['parameters']:
if param_name in gbls['parameters'][param_type]:
... | The function `get_query_params` processes a dataclass's fields to generate query parameters based on metadata annotations. It extracts field values, applies serialization rules (e.g., form, deepObject), and constructs a dictionary of parameters with lists of values. It handles global variables for fallback values and s... | def get_query_params(clazz: type, query_params: dataclass, gbls: Dict[str, Dict[str, Dict[str, Any]]] = None) -> Dict[
str, List[str]]:
params: Dict[str, List[str]] = {}
param_fields: Tuple[Field, ...] = fields(clazz)
for field in param_fields:
request_metadata = field.metadata.get('request... |
def marshal_json(val, typ, encoder=None):
if not is_optional_type(typ) and val is None:
raise ValueError(f"Could not marshal None into non-optional type: {typ}")
marshal = make_dataclass('Marshal', [('res', typ)],
bases=(DataClassJsonMixin,))
marshaller = marshal(res=va... | This function serializes request data based on the specified media type. It checks if the media type is JSON, multipart, or URL-encoded, then uses corresponding serialization methods (marshal_json, serialize_multipart_form, serialize_form_data). If the request is bytes/str, it returns directly. Otherwise, it raises an ... | def serialize_content_type(field_name: str, request_type: any, media_type: str, request: dataclass, encoder=None) -> Tuple[str, any, List[List[any]]]:
if re.match(r'(application|text)\/.*?\+*json.*', media_type) is not None:
return media_type, marshal_json(request, request_type, encoder), None
if re.mat... |
def writeFile(info,type):
if type == "question":
with open('question.json', 'w') as f:
json.dump(info,f, indent = 4)
elif type == "moreInfo":
with open('moreInfo.json', 'w') as f:
json.dump(info, f, indent = 4)
elif type == "answers":
with open('answers.json',... | The function `searchQuestion` searches a database for questions matching a given title using MySQL full-text search in Boolean mode, filters by `PostTypeId = 1` (questions), and retrieves results ordered by view count. It prints the top `PRINT_LIMIT` results, stores details in a dictionary, and writes them to a JSON fi... | def searchQuestion(question = 0):
try:
question = "+" + (str(question).strip().replace(" "," +"))
cursor.execute("SELECT * FROM Questions WHERE MATCH (Title) AGAINST ('{}' IN BOOLEAN MODE) AND PostTypeId = 1 ORDER BY ViewCount DESC".format(question))
collection = {}
result = cursor.f... |
def searchQuestion(question = 0):
try:
question = "+" + (str(question).strip().replace(" "," +"))
cursor.execute("SELECT * FROM Questions WHERE MATCH (Title) AGAINST ('{}' IN BOOLEAN MODE) AND PostTypeId = 1 ORDER BY ViewCount DESC".format(question))
collection = {}
result = cursor.f... | The code defines a function `choose` that processes user input to select a search operation (1-4). Based on the selected option, it prompts for a query, executes the corresponding search function (e.g., `searchQuestion`, `searchAnswers`), prints results, and saves them to a file. It validates input and handles invalid ... | def choose(argument):
if argument not in ["1","2","3","4"]:
print("\nFilter {} not available.\n".format(argument))
else:
print("Please enter the request..")
question = sys.stdin.readline().strip('\n')
if argument == '1':
searchQuestion(question)
elif ... |
def detokenize(tokens):
return TreebankWordDetokenizer().detokenize(tokens)
def check_child(tree):
check = False
count = 0
total_count = 0
for subtree in tree:
total_count += 1
if type(subtree) == nltk.tree.Tree:
if subtree.label() == '_':
count += 1
i... | The code collects and detokenizes leaf nodes from a parsed tree structure, appending them to a list. It checks if each tree node has a label '_', or if a helper function `check_child` returns true, detokenizing and adding the leaves directly. Otherwise, it recursively processes child trees. The main task is to extract ... | def collect_leaves(self, parsed_tree):
leaves = []
for tree in parsed_tree:
if type(parsed_tree) != nltk.tree.Tree: continue
if tree.label() == '_':
leaves.append(detokenize(tree.leaves()))
continue
if check_child(tree):
... |
def detokenize(tokens):
return TreebankWordDetokenizer().detokenize(tokens)
def get_phrase_lookup(self, base_candidate):
if self.level == 'phrase':
phrase_lookup = {p: phrase for p, phrase in enumerate(self.get_phrases(base_candidate))}
elif self.level == 'word':
words = word... | This code performs iterative optimization of a text candidate by applying edit operations (delete/add) to improve a score. It tracks edits, evaluates candidates, and updates the best-performing variant. If no improvement occurs within a patience threshold, it halts. The process uses phrase-based edits, manages a deleti... | def tune(self):
operations_tracker = []
base_candidate = detokenize(word_tokenize(self.init_prompt))
assert word_tokenize(base_candidate) == word_tokenize(self.init_prompt)
original_candidate = base_candidate
base_score = self.score_func(base_candidate)
delete_tracker =... |
def __dataAnalysis(self):
if self.text.isnumeric():
self.encodingMode = 'numeric'
elif all(character in aVs for character in self.text):
self.encodingMode = 'alphanumeric'
else:
self.encodingMode = 'byte'
def __dataEncoding(self):
# Step 2.1: Choose the Error Correction Level ✔️
# ... | The code's main task is to generate a QR code by performing key steps: analyzing input data, encoding it, applying error correction, structuring the final message, placing modules, masking data to avoid patterns, and embedding version/format information for proper decoding and size specification. | def create(self):
self.__dataAnalysis()
self.__dataEncoding()
self.__errorCorrectionCoding()
self.__structureFinalMessage()
self.__modulePlacement()
self.__dataMasking()
self.__formatVersionInformation() |
def isWumpusAt(self, coords):
if(self.wumpusLocation is None):
return False
elif(self.wumpusLocation.x == coords.x and self.wumpusLocation.y == coords.y):
return True
else:
return False
def isPitAt(self, coords):
for item in self.pitLocations:
... | The code applies a given action to an agent in a Wumpus world environment, updating the agent's state and environment based on the action. It handles movement, turning, grabbing gold, climbing, and shooting, returning a new environment and percept (sensory feedback) with details like stench, breeze, bump, and reward va... | def applyAction(self, action):
if (self.isTerminated):
return self, Percept(False, False, False, False, False, True, 0)
else:
if action.name is Action.Forward.name:
movedAgent = self.agent.forward(
self.gridWidth, self.gridHeigh... |
def quiz_logo():
"""
Quiz logo
"""
print(" ***** 🇿🇦 🌎Cape Town Quiz ! 📣☀ ***** ")
print()
print(" As a current resident of Cape Town. ")
print()
print(" I have built a simple multiple choice quiz ")
print()
... | The start function initializes a quiz by displaying a logo, providing instructions, and executing the quiz. It sequentially calls quiz_logo() to show branding, instructions() to explain rules, and run_quiz() to begin the interactive assessment, ensuring users are prepared before starting the quiz. | def start():
"""
start function, shows the main image, instructions then runs the quiz.
"""
quiz_logo()
instructions()
run_quiz() |
def predict_crop(self, img, debug_id=None):
start_time = time.time()
orig_shape = img.shape[:2]
resized_img = self.resizer.augment(img)
scale = np.sqrt(
resized_img.shape[0] * 1.0 / img.shape[0] * resized_img.shape[1] / img.shape[1])
boxes, probs, labels, *masks = sel... | The code processes an image to crop and rotate document pages, refining object locations, estimating rotation angles, and adjusting bounding boxes. It handles associated objects, applies rotations (fine and coarse), and returns rotated pages with polygons, confidence scores, and specific field data like face and MRZ in... | def crop_and_rotate(self, image, debug_id=None):
start_time = time.time()
cropped_results = self.predict_crop(image, debug_id=debug_id)
if self.debug:
cropped_result, debug_path = cropped_results
else:
cropped_result = cropped_results
all_pages_result = [(... |
def is_squatting(landmarks, prev_nose, prev_r_hip, prev_l_hip):
mpPose = mp.solutions.pose
nose = landmarks[mpPose.PoseLandmark.NOSE]
left_hip = landmarks[mpPose.PoseLandmark.LEFT_HIP]
right_hip = landmarks[mpPose.PoseLandmark.RIGHT_HIP]
# check if the person is lowering their hips by comparing th... | The code processes an image to detect human pose landmarks using a pre-trained model, identifies squatting movements by analyzing landmark positions (nose, hips), tracks the user's state (squatting/standing), counts repetitions, and overlays results on the image. It returns the processed image, movement label, repetiti... | def image_processing(image_to_analyze: np.ndarray, model, mpPose, pose, mpDraw, counter, state, nose, r_hip, l_hip,
flag):
# model = tf.keras.models.load_model('medium_squat_cnn_model6.h5')
lm_list = []
label = None
# mpPose = mp.solutions.pose
# pose = mpPose.Pose()
# mpDr... |
def file_exists(filename):
conn = get_file_client()
return conn.fs.exists(filename)
def delete_document(filename, tenant):
conn = get_file_client()
conn.fs.rm(filename)
delete_document_db(filename, tenant)
def write_file(filename, raw):
conn = get_file_client()
conn.fs.pipe(filename, raw)
de... | The code processes a file by deleting an existing document (if it exists) and writing new content, then splits the file into text chunks using a specified strategy and stores these chunks in a database with a generated document ID. | def process_file(filename, raw, tenant):
if file_exists(filename):
delete_document(filename, tenant)
write_file(filename, raw)
doc_uuid = write_doc_db(filename, tenant)
chunks = partition(
filename,
chunking_strategy="by_title",
new_after_n_chars=SOFT_MAX_CHUNK,
... |
def create_dataloader(
dataset: Dataset,
pretrained_model_name_or_path: str,
image_column: str = "image",
caption_column: str = "text",
max_train_samples: int = 1,
resolution: int = 512,
center_crop: int = True,
random_flip: int = True,
seed: Optional[int] = None,
train_batch_siz... | The function trains a UNet model for one step using a preloaded Pokémon dataset, initializes a train state with an optimizer, builds an IREE module with CUDA backend, executes a single training step, and returns the UNet's optimizer state and parameters. | def iree_train(pretrained_model_name_or_path: str, rng_seed: int):
# Train for 1 step and return Unet train state
set_seed(rng_seed)
# Downloading and loading a dataset from the hub.
dataset = load_dataset(path="lambdalabs/pokemon-blip-captions")
dataloader = create_dataloader(
dataset,
... |
def iree_train(pretrained_model_name_or_path: str, rng_seed: int):
# Train for 1 step and return Unet train state
set_seed(rng_seed)
# Downloading and loading a dataset from the hub.
dataset = load_dataset(path="lambdalabs/pokemon-blip-captions")
dataloader = create_dataloader(
dataset,
... | The code's main task is to test and compare IREE and JAX training results for a UNet model. It initializes a random seed and pretrained model, runs IREE training to obtain optimizer states and parameters, and attempts to run JAX training (commented out by an early return). The incomplete test aims to verify if IREE's o... | def test_training_with_iree_jax():
rng_seed = 12345
pretrained_model_name_or_path = "duongna/stable-diffusion-v1-4-flax"
iree_unet_optimizer_state, iree_unet_params = iree_train(
pretrained_model_name_or_path=pretrained_model_name_or_path,
rng_seed=rng_seed)
return
jax_unet_optimiz... |
def compute_sliding_mean(signal, sampling_freq,
T=500e-3):
""" just a gaussian smoothing """
return gaussian_filter1d(signal, int(T*sampling_freq))
def compute_freq_envelope(signal, sampling_freq, freqs):
"""
compute the frequency power using wavelet transform
1. performs w... | The function computes the Neural Signal Index (NSI) by calculating a sliding mean and low-frequency envelope of the input signal, then applying the NSI formula. If enabled, it returns intermediate quantities alongside the NSI value. | def compute_NSI(signal, sampling_freq,
p0=0,
low_freqs = np.linspace(2,5,5),
T_sliding_mean=500e-3,
alpha=2.87,
with_subquantities=False):
"""
1. compute sliding-mean and low-freq envelope
2. apply NSI formula
"""
sl... |
def get_this_tag(document, tag):
tags = set()
for token in document.find_all(tag):
tag = nltk.word_tokenize(token.text.lower())
for t in tag:
if len(cleanThisToken(t)) >= 2:
tags.add(cleanThisToken(t))
return tags
def addToMap(id, posting):
global id_map
... | This function reads a document file, parses its content to extract title, bold text, and headings, tokenizes the text, assigns weights to tokens based on their context (title, bold, headings, stopwords), and stores these weighted tokens in a frequency map and token bank for indexing purposes. | def read_file(filepath):
global collection_size, tokens_bank
with open(filepath, 'r') as file:
collection_size += 1
count = 0
title = []
tokens_freq = defaultdict(int)
json_file = json.load(file)
document = BeautifulSoup(json_file["content"], 'lxml')
bol... |
def print_error(error_message):
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
msg.setText("Opps")
msg.setInformativeText(error_message)
msg.setWindowTitle("Error")
msg.exec_()
def find_shortest_route( start_location, end_location):
ors_key = API_KEYS.OPEN_ROUTE
client = ors.Clien... | The main task of the code is to parse user-provided location coordinates, compute the shortest route between them using a dedicated function, and visualize the route on a map. It handles invalid input by catching ValueErrors and returning -1, ensuring valid numerical coordinates are processed for route calculation and ... | def find_route_between_points(start_location, end_location):
# parse data from user
try:
start_location_split = start_location.split(',')
start_location = (float(start_location_split[0]), float(start_location_split[1]))
end_location_split = end_location.split(',')
end_location =... |
def get(index, recv=True):
io.sendlineafter(b'> ', b'1')
io.sendlineafter(b': ', str(index).encode())
if recv:
io.recvline()
return io.recvline()[:-1]
def printf(address, recv=True):
set(p64(address))
return get(-16, recv)
def fsb(string, recv=True):
set("%AAAAAAAA" + string)
... | This code performs a format string exploit to overwrite memory addresses by calculating the base addresses of the ELF binary and libc, then using format string attacks (fsb) to manipulate the stack and memory. It constructs specific format strings to write controlled values into memory locations, aiming to achieve arbi... | def main():
elf.address = u64(get(-19).ljust(8, b'\x00')) - 0x4008
libc.address = u64(printf(elf.got.puts).ljust(8, b'\x00')) - libc.sym.puts
stack = u64(printf(libc.sym.environ).ljust(8, b'\x00'))
fsb(f"%{(stack - 0x10)&0xffff}c%10$hn")
fsb('%40$n')
fsb(f"%{(stack - 0x220)&0xffff}c%10$hn")
... |
def is_matrix_linearly_dependent(a):
return numpy.linalg.matrix_rank(a) != a.shape[0]
def __projection(self, a: np.array, b: np.array) -> np.array:
return (self.inner_product(a, b) / self.inner_product(b, b)) * b
def __normalize_vec(self, a: np.array) -> np.array:
vec_normal = self.__get_vec_no... | This code performs Gram-Schmidt orthogonalization on a matrix, checking for linear dependence first. If dependent, it returns None. Otherwise, it iteratively subtracts projections of vectors onto preceding ones, normalizes each orthogonalized vector, and returns the transformed matrix. | def calc(self, matrix: np.ndarray) -> Optional[np.ndarray]:
if self.is_matrix_linearly_dependent(matrix):
print("Error: Matrix is linearly dependent")
return None
res: np.ndarray = matrix.copy()[:].astype(numpy.float32)
for i in range(0, res.shape[0] - 1):
for... |
def get_scale_names() -> [str]:
"""Open file containing name of scales returns its contents."""
names = []
with open('ScaleNames.txt') as file:
scale_names = file.readlines()
file.close()
for name in scale_names:
names.append(name.strip())
return names
def get_progressions() ->... | The function `generate_keys` generates all possible musical scales starting from each chromatic note (C to B), creating a dictionary mapping each root note to its corresponding scale. It uses a two-octave chromatic scale, translates steps into notes, and compiles scale names and progressions from helper functions. The ... | def generate_keys() -> [str]: # remove root note will get passed in other function
"""generates notes based on given steps"""
# Two octaves to allow full cycle - without doing any math to manipulate the scale
scales = []
names = get_scale_names()
progressions = get_progressions()
chromatic_sca... |
def invSNC(self,want_ld=1):
alpha = 1/(1-self.rho)
Fi = alpha * csr_matrix(np.diag(np.power(self.tau,-2)), dtype=np.float64)
ti = 1 / self.tau
# TS 5/27/19 outer product!
Di = Fi - (float(self.rho*alpha**2) * np.outer(ti,ti) ) / (1 + (self.rho*self.n_vox*alpha))
DiW = Di... | The code decodes single-trial estimates and uncertainty from neural data using likelihood optimization. It processes each trial's voxel activity to compute orientation estimates (est), uncertainty (unc), orientation likelihoods (posterior), and initial guesses (estInit) via numerical integration and minimization. Input... | def decode(self,test_samples):
""" Decode best estimate and uncertainty on each trial
Parameters
----------
test_samples: array
Testing data (trials x voxels)
Returns
-------
est: array
single trial estimates (trials)
... |
def get_residuals(self,samples,ori):
""" Get residules from linear encoding model
Parameters
----------
samples: array
Training data (trials x voxels)
ori: array
Orientation presented in degrees [0,180] (trials)
"""
assert (~np.any... | The function performs cross-validated model fitting by grouping trials using variable G. For each group (excluding G=-1), it splits data into training (all other groups) and test sets, estimates noise parameters, and decodes test data via two methods (decode and decodeIEM). Results are aggregated into a dictionary cont... | def fit_CV(self,samples,ori,G):
""" Perform cross-validated fits using grouping variable G
Parameters
----------
samples: array
data (trials x voxels)
ori: array
Orientation presented in degrees [0,180] (trials)
G: array
Groupi... |
def get_setting(self, key):
"""Gets a setting from the project settings.
:param key: The key of the project setting.
:type key: string
"""
# proj = QgsProject.instance()
val, _ = self.proj.readEntry("Eodms", key, "")
# self.post_message(f"Getting setting {key}... | The main task of the code is to execute a search using EODMS credentials by collecting user-defined filters, date ranges, and other parameters from a dialog. It validates credentials, disables the search action during processing, constructs search parameters, runs a background search task via RAPI, waits for completion... | def open_search(self):
"""Run method that performs all the real work"""
self.username = self.get_setting('username')
self.password = self.get_setting('password')
if self.username is None or self.username == '' or \
self.password is None or self.password == '':
... |
def import_config(self):
"""
Gets the configuration information from the config file.
:return: The information extracted from the config file.
:rtype: configparser.ConfigParser
"""
if not os.path.exists(self.config_fn):
# Get the path of the eodms_cli folder... | The code's main task is to prompt the user for configuration parameters in a CLI tool. It handles three scenarios: displaying help text (`-h`), configuring all parameters (`all`), or updating specific sections/parameters. It validates section existence, processes input, and updates the configuration dictionary. For non... | def ask_user(self, in_sect='all'):
"""
Asks the user for all the configuration values.
:return: n/a
"""
self.import_config()
sections = '\n'.join([f' {k}\t\t\tAsks user for parameters under '
f'section {k}.'
... |
def load_images(self):
size = (256, 256)
src_list, tar_list = list(), list()
# enumerate filenames in directory, assume all are images
for filename in listdir(self.source_path):
# load and resize the image
pixels = load_img(os.path.join(self.source_path, filename)... | The main task of the code is to execute a GAN training process by loading image datasets, defining a discriminator and generator model, constructing a GAN model, and training it. Key steps include loading data, determining input shapes, model initialization, and training, with progress summaries printed at each stage. | def execute_training(self):
# load images to dataset
self.load_images()
# load image data
filename = 'set_256.npz'
dataset = self.load_real_samples(os.path.join(self.folder_model, filename))
self.printSummary(('Loaded', dataset[0].shape, dataset[1].shape))
# defin... |
def vehicles(board):
#find '-' on board and add to list obstacles and visited
obstacles = []
visitedNode = []
for i in range(6):
currentRow = board[i]
for j in range(6):
if(currentRow[j] != '-'):
if(currentRow[j] not in obstacles):
obstacle... | The code generates possible states from a board configuration by identifying vertical and horizontal obstacles, creating new states through vertical and horizontal movement functions, and formatting them into A* search nodes with heuristic and cost values for pathfinding algorithms. | def generateStates(board,heurisitic, g):
newStates = []
vStates = []
hStates = []
obstacleCoord = vehicles(board.board)
for i in range(len(obstacleCoord)):
x = obstacleCoord[i][1][0]
y = obstacleCoord[i][2][0]
#vertical
if (x == y):
vStatesTemp = v... |
def load_window_param_file(fn):
values = load_yaml(fn)
params = parse_param_yaml(values)
return params
def select_windows_asdf(obs_ds, obs_tag, syn_ds, syn_tag, params):
obs_stations = obs_ds.waveforms.list()
print("Number of stations in observed: {}".format(len(obs_stations)))
# earthquake eve... | The main task of the code is to process seismic data by loading observed and synthetic ASDF files for a specific event and frequency band, applying window selection parameters from a YAML file, generating seismic windows, and saving the results as a JSON file. It involves data loading, parameter configuration, window s... | def main():
eventname = "C200501011908A"
period_band = "17_40"
obs_tag = f"proc_obsd_{period_band}"
# load observed asdf file
obs_file = f"data/{eventname}.{obs_tag}.h5"
print(f"obsd filename: {obs_file}")
obs_ds = ASDFDataSet(obs_file, mpi=False, mode='r')
print("obs asdf: ", obs_ds)
... |
def valid_copies_of_input(obj_fun, init_basic_feas_sol, bas_var, non_bas_var, A_eq, b_eq):
"""
This function
1) creates the copies of all input structures
(to keep original input object protected against changes that happen while the itterations of simplex method).
2) It ensures that all the st... | The code implements the **simplex method** for solving linear programming problems. It iteratively updates the basis and non-basis variables by selecting entering (most negative coefficient in the objective row) and leaving variables (via ratio test) to improve the objective function. The loop continues until all coeff... | def simplex_method(obj_fun, init_basic_feas_sol, bas_var, non_bas_var, A_eq, b_eq):
c, x, A, b, basis, non_basis, F_value = valid_copies_of_input(obj_fun, init_basic_feas_sol, bas_var, non_bas_var, A_eq, b_eq)
A, b, diagonal_elements = express_A_via_nonbasic(A, b, basis)
c, x, A, b, basis, non_basis, F_valu... |
def setup():
pygame.init()
window_width = 700
window_height = 750
gameDisplay = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Wordle")
clock = pygame.time.Clock()
def draw_rectangles(k,size):
for i in range(6):
for j in range(k):
pyga... | This code defines a game loop for a word guessing game, handling user input, drawing game elements, and managing game states. It initializes game variables, processes keyboard and mouse events for letter selection, validates guesses, updates the display, and triggers win/loss conditions. The loop continues until the pl... | def game_loop():
setup()
global zop
global rounds
global size
global fsize
global increment
gameDisplay.fill(white)
gameExit = False
draw_rectangles(zop,size)
for letter in letters:
letter.draw(blue)
enter.draw(grey, 15)
delete.draw(grey, 13)
word = guessing_w... |
def linear(x):
W = tf.Variable(tf.zeros([48 * 48, 7]))
b = tf.Variable(tf.zeros([7]))
pred = tf.nn.softmax(tf.matmul(x, W) + b, name='probability')
return pred
def cnn_net(x, weights, bias, keep_prob):
x = tf.reshape(x, [-1, 48, 48, 1])
# layer-1
h_conv1_1 = tf.nn.relu(conv2d(x, weights['co... | The code trains a neural network (linear or CNN) on facial emotion recognition using TensorFlow, reading data, defining placeholders, and optimizing via backpropagation. It iterates over epochs, trains on batches, evaluates accuracy/loss, tests on validation data, and saves the trained model. | def train(mode):
x_test, y_test, x_train, y_train = facial_data.read()
x = tf.placeholder(tf.float32, [None, 48 * 48], name='data')
y_ = tf.placeholder(tf.float32, [None, 7], name='label')
keep_prob = tf.placeholder(tf.float32, name='keep_prob')
if mode == 0:
y = linear(x)
if mode == 1:
... |
def linear(x):
W = tf.Variable(tf.zeros([48 * 48, 7]))
b = tf.Variable(tf.zeros([7]))
pred = tf.nn.softmax(tf.matmul(x, W) + b, name='probability')
return pred
def cnn_net(x, weights, bias, keep_prob):
x = tf.reshape(x, [-1, 48, 48, 1])
# layer-1
h_conv1 = tf.nn.relu(conv2d(x, weights['conv... | The code trains a neural network (linear or CNN) for facial emotion classification using TensorFlow. It loads facial data, defines placeholders, and trains the model for 100 epochs with batch processing. It computes loss/accuracy during training, evaluates on test data, and saves the trained model. The CNN mode uses dr... | def train(mode):
x_test, y_test, x_train, y_train = facial_data.read()
x = tf.placeholder(tf.float32, [None, 48 * 48], name='data')
y_ = tf.placeholder(tf.float32, [None, 7], name='label')
keep_prob = tf.placeholder(tf.float32, name='keep_prob')
if mode == 0:
y = linear(x)
if mode == 1:
... |
def create_new_dir(manta_name, attributes, database_folder, drive):
alfredi_dir, birostris_dir = get_folders_for_all_mantas(drive)
highest_id = -1
for file in alfredi_dir:
current_manta_id = get_manta_id(file["title"])
if current_manta_id > highest_id:
highest_id = current_manta_id
for file in birostris_dir:... | The code organizes and saves manta ray images into structured folders based on attributes like color (Black/White) and gender (Female/Male/Unknown), while also storing them in a "MASTER" folder and local database. It creates a new directory, applies conditional logic to categorize files, and ensures multi-level storage... | def save_new_manta(manta_name, attributes, database_folder, file, drive, processed_image):
folder_id, folder_name = create_new_dir(manta_name, attributes, database_folder, drive)
#safed in new folder
save_image_in_match_folder(file, drive, folder_name, database_folder, attributes, manta_name)
#safe in color folde... |
def log_likelihoods(mus, Sigmas, data, mask=None):
if mask is not None and np.any(~mask) and not isinstance(mus, np.ndarray):
raise Exception("Current implementation of multivariate_normal_logpdf for masked data"
"does not work with autograd because it writes to an array. "
... | The code's main task is to predict the most likely sequence of hidden states using the Viterbi algorithm, given a trained model, input features, and scaled data. It processes the input data, computes log-likelihoods of observations under the model's parameters (means, covariances), and applies Viterbi to find the optim... | def predict(model, feats, scaler, data):
# Here we're going to force data to be an array since
# C++ doesn't have numpy data types
obs = dr.feature_projection(dr.scale_data(np.array(data),scaler),feats)
# model.filter is erroring on assert np.abs(np.sum(pz_tp1t[t]) - 1.0) < 1e-8
# (line 94 of messa... |
def init_spatial_tessellation(self, spatial_tessellation):
if type(spatial_tessellation) == pandas.DataFrame:
if len(spatial_tessellation)<2:
raise ValueError("Argument `spatial_tessellation` must contain at least 2 tiles.")
self.n_locations = len(spatial_tessellat... | The main task of the code is to simulate synthetic agent trajectories over a specified time period using spatial tessellation and social graph dynamics. Agents perform exploration/return actions influenced by social interactions, with movement updates governed by parameters like independence window and social graph upd... | def generate(self, start_date, end_date, spatial_tessellation, social_graph='random',
n_agents=500, dt_update_mobSim = 24*7, indipendency_window = 0.5, random_state=None, log_file=None, verbose=0, show_progress=False):
"""
Start the simulation of a set of agents at t... |
def obtain_orientation_index(self, theta):
# Limit orientation between 0 to 360
if theta >= 2 * np.pi:
n = int(theta / (2 * np.pi))
theta = theta - n * 2 * np.pi
elif theta < 0:
# Convert negative angle into positive and maintain the orientation between 0 to 3... | The main task of the code is to generate a valid child node in a grid-based pathfinding algorithm by simulating the robot's movement from a parent node using given left and right wheel velocities. It calculates intermediate positions, checks for obstacle validity, accumulates path costs, updates parent pointers, and re... | def fetch_child_node(self, parent_node, left_velocity, right_velocity):
# An empty list to store intermediate nodes
intermediate_nodes = []
valid_path = True
# Define grey
yellow = [255, 255, 0]
# Get coordinates and orientation of parent node
parent_node_data = ... |
def _reset(self) -> NoReturn:
"""
Reset internal state.
:return:
"""
self.relations = set()
self.senses = {}
self.__seen_components = set()
def _get_relations_and_senses(self, lf: LogicalForm):
"""
Navigate a given logicalForm tree to obtain:
... | The function `resolve` generates valid semantic interpretations of a sentence up to a specified count, using either strict or fuzzy resolution. It parses the sentence into a logical form, extracts relations and their senses, checks constraints against selectional restrictions, and filters valid interpretations. It retu... | def resolve(self, sentence: str, mode: ResolveType, count: int = None):
"""
Given a sentence, produce all valid semantic interpretations up to 'count'
:param sentence: The sentence to resolve.
:param mode: STRICT or FUZZY resolution.
:param count: The number of interpretations to... |
def print_board(self):
black_square = "⬛"
white_square = "⬜"
queen = "👑"
#print(" ♚ ♛ ♜ ♝ ♞ ♟️ ♔ ♕ ♖ ♗ ♘ ♙")
print("➖➖➖➖Board➖➖➖➖\n")
for i in range(self.n):
print(f" {chr(65 + i)} ", end="")
for j in range(self.n):
if (i + j) %... | The code implements a greedy search algorithm to solve a puzzle (likely the 8-puzzle), using a heuristic to determine the next move. It tracks the number of moves, avoids revisiting states via a hash set, and returns True upon reaching the goal state, printing the board and move count. | def greedy_search(self):
self.print_board()
counter = 0 # counter for number of moves
while True:
self.update_positive_diagonal() # update the positive diagonal list
a, b = self.heuristic() # next move by heuristic function
counter += 1
self.swa... |
def get_element_text(driver, xpath, more=False):
if exist_element(driver, xpath):
if more:
see_more(driver.find_element_by_xpath(xpath))
return driver.find_element_by_xpath(xpath).text
else:
return None
def preprocessing(text):
try:
text = text.split('\n')
... | The main task of the code is to scrape and compile detailed information from a LinkedIn profile page into a structured dictionary. It extracts data such as name, short description, about section, experience, education, skills, and more, while handling dynamic elements and edge cases. The function also records the crawl... | def crawl_profile_1(driver, url):
profile = {}
# Name
profile['fullname'] = get_element_text(driver, xpath='//h1[contains(@class, "text-heading-xlarge")]')
# Short description
profile['short_description'] = get_element_text(driver, xpath= '//div[@class="text-body-medium break-words"]')
#... |
def get_element_text(driver, xpath, more=False):
if exist_element(driver, xpath):
if more:
see_more(driver.find_element_by_xpath(xpath))
return driver.find_element_by_xpath(xpath).text
else:
return None
def get_experience_2(driver, id):
xpath = f'//section[contains(@id, "... | This function scrapes LinkedIn profile data using a browser driver, extracting fields like name, description, about section, experience, education, skills, and avatar. It uses XPath and BeautifulSoup to parse HTML, stores structured data in a dictionary, and includes metadata like crawl time and raw HTML. | def crawl_profile_2(driver, url):
profile = {}
# Name
profile['fullname'] = get_element_text(driver, xpath='//h1[contains(@class, "text-heading-xlarge")]')
# Short description
profile['short_description'] = get_element_text(driver, xpath= '//div[@class="text-body-medium break-words"]')
#... |
def check_move(self, x, y, piece=None):
""" Determines whether a piece is able to move"""
can_move = True
if piece is None:
piece = self.piece
stone = piece.get_piece()
for i in range(len(stone)):
for j in range(len(stone[0])):
pos = stone... | This code updates a game state by handling piece movement, collision checks, and game over conditions. It increments time counters, triggers piece drops every 500ms, checks for valid moves, applies pieces when blocked, spawns new pieces, clears completed rows, and returns the current game image and status. The function... | def update(self, dt):
"""Updates the game by {fps} times a second"""
if self.total_time >= self.time_limit > -1:
self.game_over = True
# if self.frames_elapsed >= self.fps / 2 and not self.game_over:
if self.time_elapsed >= 500 and not self.game_over:
self.time_... |
def simulate_step(self, state):
# Select action and send it to the game
start = time.time()
old_stack = np.stack(state, axis=-1)
action = self.select_action(old_stack)
next_state, reward, done, _ = self.env.step(action)
state.appendleft(next_state)
new_stack = np... | The code runs an episode of the environment, collecting experiences, training a DQN model using experience replay, updating the target network, and logging performance metrics like reward and loss. It tracks simulation, training, and buffer update timings, iteratively improving the agent's policy through interaction an... | def step_episode(self, episode):
# Reset environment and initialize state_queue
start_time = time.time()
last_time = time.time()
state_queue = deque([np.zeros((22, 10)) for _ in range(3)] + [self.env.reset()], 4)
done = False
r_total = 0
l_total = 0
iterat... |
def __get_filename_handler(self, video_type, index):
if video_type == 'stockvideo':
return self.filename_handler(index)
else:
return None
def __debt_collector(self):
self.debt['text'].append(self.text)
self.debt['duration_to_trim'].append(self.duration_to_trim)
... | This function handles video debt by locating a stock video at the current index, generating text-based video clips from debt data, concatenating them, and saving the result. It repeatedly searches for the video, uses a debt collector to resolve missing files, creates text videos, combines them into a final clip, and cl... | def __inner_video_debt_handler(self):
"""
debt video are stored as object and be consolidated.
"""
print(f'Looking for video in the next index at {self.current_index}')
next_videofilename = self.__get_filename_handler('stockvideo', self.current_index)
... |
def __check_video_log(self,logs):
if (('too short' in logs) or ('no good' in logs) or (logs == "")):
return True
def __debt_collector(self):
self.debt['text'].append(self.text)
self.debt['duration_to_trim'].append(self.duration_to_trim)
self.debt['index'].append(self.current_... | This function handles video debt processing by checking video logs. If valid, it triggers debt collection and internal handling; if not, it generates a new video clip from a stock file, resizes it, overlays text, and saves the result. The task involves conditional video creation or debt resolution based on log validati... | def __video_debt_handler(self):
print(f"current index in {self.current_index}")
if self.__check_video_log(self.logs) == True:
self.__debt_collector()
self.__inner_video_debt_handler()
print(f"current index is set to {self.current_index}")
#fringe case w... |
def get_distinfo_dist(path, pkg_name=None):
# type: (S, Optional[S]) -> Optional[DistInfoDistribution]
import pkg_resources
dist_dir = next(iter(find_distinfo(path, pkg_name=pkg_name)), None)
if dist_dir is not None:
metadata_dir = dist_dir.path
base_dir = os.path.dirname(metadata_dir)
... | The function retrieves metadata from a package distribution (wheel or egg) at the specified path. It attempts to load metadata using either `get_distinfo_dist` (for wheels) or `get_egginfo_dist` (for eggs), depending on `metadata_type`. If successful, it returns metadata from the distribution; otherwise, returns an emp... | def get_metadata(path, pkg_name=None, metadata_type=None):
# type: (S, Optional[S], Optional[S]) -> Dict[S, Union[S, List[RequirementType], Dict[S, RequirementType]]]
wheel_allowed = metadata_type == "wheel" or metadata_type is None
egg_allowed = metadata_type == "egg" or metadata_type is None
dist = No... |
def run_setup(script_path, egg_base=None):
# type: (str, Optional[str]) -> Distribution
"""Run a `setup.py` script with a target **egg_base** if provided.
:param S script_path: The path to the `setup.py` script to run
:param Optional[S] egg_base: The metadata directory to build in
:raises FileNotFo... | This function parses a Python package's setup.py file to extract metadata, dependencies, and version information, updating the instance's attributes with these details for package configuration or analysis purposes. | def run_setup(self):
# type: () -> "SetupInfo"
if self.setup_py is not None and self.setup_py.exists():
dist = run_setup(self.setup_py.as_posix(), egg_base=self.egg_base)
target_cwd = self.setup_py.parent.as_posix()
with temp_path(), cd(target_cwd):
if... |
def CatchModel(Inputs,InStates,Pars,NRes): # Runs the Catchment Model for One Time Step
# Get Input Values for Time Step
PP = Inputs[0];
PE = Inputs[1];
# Get State Values at Begining of Time Step
XX1in = InStates[0];
XX2in = InStates[1];
XX3in = np.zeros(NRes);
ResIdx = np... | The main task of the code is to simulate a hydrological model using input parameters and observed data (precipitation, evaporation, discharge), compute performance metrics (MSE, NSE, KGE), and return the inverse of the KGE score as an objective function for optimization. The code initializes model states, runs a time-l... | def obj_func(Pars,PPobs,PEobs,QQobs,NRes):
NTime = len(PPobs); # Get length of Time vector
Time = np.arange(0,NTime,1); # Set up Time vector (of integer values)
# Pack Parameter Values into Par Array
# Npar = 6; Pars = np.zeros(Npar);
Theta_C1 = Pars[0]; Theta_P1 = Pars[1];... |
def CatchModel(Inputs, InStates, Pars, NRes):
# Get input values for time step
PP = Inputs[0]
PE = Inputs[1]
# Get state values at beginning of time step
XX1in = InStates[0]
XX2in = InStates[1]
XX3in = np.zeros(NRes)
ResIdx = np.arange(0, NRes, 1)
for i in ResIdx:
XX3in[... | The code simulates a catchment hydrological model using parameters and observed inputs (precipitation, evaporation, and discharge) to generate simulated discharge (QQsim) and internal fluxes. It evaluates model performance by removing a spin-up period, calculating metrics like MSE, NSE, NSEL, and KGE, and returns simul... | def MainCatchModel(Pars, PPobs, PEobs, QQobs, NRes):
# def MainCatchModel(PPobs, PEobs, Theta_C1,
# Theta_P1, Theta_K12, Theta_K13,
# Theta_K2Q, Theta_K3Q, NRes):
NTime = len(PPobs) # Get length of time vector
Time = np.arange(0, NTime, 1) # Set up time ... |
def receive_all(sock: socket.socket, n: int) -> bytearray:
"""
recv n bytes of strings; return None on EOF
"""
data = bytearray()
while len(data) < n:
to_read = n - len(data)
packet = sock.recv(
4194304 if to_read > 4194304 else to_read)
data.extend(packet)
... | This function handles user connections by receiving and broadcasting messages (text or files) to all connected clients. It continuously listens for incoming data, decodes messages, and sends them to other users. If a connection ends, it notifies others, removes the user, and manages errors by disconnecting and updating... | def handle_user_connection(connection: _Session, address: str) -> None:
'''
Get user connection in order to keep receiving their messages and
sent to others users/connections.
'''
while True:
try:
# If no message is received, there is a chance that connection has ended
... |
def is_taken(new_user: str) -> bool:
# check username and return true if found
for user in connections:
if new_user == user.username:
return True
break
return False
def pad_message(msg: str, msg_type="str") -> bytes:
"""
Pack strings for transfer (>QI == 12 bytes)... | The code defines a server function that listens on port 12000, accepts client connections, checks username availability, manages concurrent users, and spawns threads to handle each client. It sends status updates, enforces unique usernames, and ensures proper connection cleanup during errors or shutdown. | def server() -> None:
'''
Main process that receive client's connections and start a new thread
to handle their messages
'''
LISTENING_PORT = 12000
# SERVER = socket.gethostbyname(socket.gethostname())
try:
# Create server instance
socket_instance = socket.socket(so... |
def new_session():
session = requests.Session()
session.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/106.0',
'Accept-Language': 'en-US,en;q=0.5', 'Referer': 'https://google.com', 'DNT': '1'}
creds = str(random.randint(10_000, 0x7fffffff)) + "... | The main task of the code is to extract detailed YouTube video data from a subscription channel source, including video metadata (title, views, likes, engagement, duration), formatted dates, thumbnails, URLs, and recommended videos. It processes up to 5 videos, compiles structured dictionaries with scraped information,... | def youtube_subscription_data(channel_source: str) -> []:
channel_name = re.compile(r'","title":"([^"]*)"').findall(channel_source)[0]
channel_id = re.compile(r'\{"key":"browse_id","value":"([^"]*)"').findall(channel_source)[0]
video_container_start = 'Renderer":{"videoId":"'
data_from_videos = []
s... |
def init_population(points, population_size):
population = []
for i in range(population_size):
population.append(random.sample(points, len(points)))
return population
def evolve(population):
population.sort(key=lambda x: fitness(x))
population = population[:50]
while len(population) < 10... | The code implements a genetic algorithm to optimize a route through given points. It initializes a population of 100 potential solutions, iteratively evolves them over 20 generations through selection, crossover, and mutation, then returns the best route from the final population. | def solve(points):
population = init_population(points, 100)
for i in range(20):
population = evolve(population)
return best_route(population) |
def get_output_file_paths(output_path_prefix):
# Check if a file with the same name as a given output file path does not exist.
out_traj_path = output_path_prefix+'.traj.txt'
out_summ_path = output_path_prefix+'.summary.txt'
if os.path.isfile(out_traj_path):
raise FileExistsError(out_traj_path)... | The function `fsim_genetic_drift` simulates genetic drift and selection in a population, tracking allele frequency trajectories for mutations over generations. It accepts parameters like population size, selection coefficient, initial mutant count, and simulation duration. Depending on input flags (e.g., `total_site_nu... | def fsim_genetic_drift(
pop_size: int,
ns: Union[float, int],
init_mut_num: int,
generation_num: int,
output_path_prefix: str,
output_only_fixation: bool = False,
implementation: str = 'binomial',
total_site_num = 0,
var_site_num = 0,
... |
def _get_info(self):
"""
Return the current info
Returns:
- dict: The current info:
- delta (int): The increase in score from the last step
- optimal_ad (int): The optimal achievable additional score
"""
return {
"delta": (... | The code defines the `step` method of an environment, which processes an action by updating the environment state, calculating rewards, and returning observation, reward, termination status, and info. It increments the step count, determines the agent's and opponent's moves, updates scores, computes the reward, and che... | def step(self, action: int):
"""
Take a step in the environment
Args:
- action (int): The action to take
Returns:
- tuple: step information:
- observation (np.ndarray): The new observation
- reward (int): The reward for the step
... |
def generateRandomGameBoard():
# Generate a list of every shape and color combo
icons = []
for color in ICON_COLORS:
for shape in ICON_SHAPES:
icons.append( (shape, color) )
# randomize the icon order
random.shuffle(icons)
# determine how many icons we need
numberOfUniqu... | This code implements a simple matching card game using Pygame. It initializes the game window, generates a randomized board, and handles mouse clicks to reveal card pairs. If the selected cards don't match, they are hidden again after a delay. The game checks for win conditions and resets when all pairs are matched. Th... | def run():
pygame.event.clear() # workaround to clear event queue to prevent click event from bleeding over from menu program
pygame.init() # framework call, initialize all imported pygame modules
pygame.display.set_caption('Simple Matching Game') # set the caption of our display window
gameBoard = gen... |
def parse_args() -> Config:
parser = argparse.ArgumentParser(description='Create a manifest table for the unpartitioned dataset.')
parser.add_argument(
'--local',
type=int,
help='Spark App name',
default=0)
parser.add_argument(
'--hdfs_input_root',
ty... | The main task of the code is to parse configuration arguments, initialize a Spark session, execute dataset augmentation using the `augment_dataset` function, and ensure the Spark session is properly stopped afterward, regardless of whether the augmentation completes successfully or encounters an error. | def main():
config: Config = parse_args()
spark = spark_session(config.spark_name, config.spark_local)
try:
augment_dataset(config, spark)
finally:
spark.stop() |
def isCheckMate(turn):
all_moves = []
for move, piece in get_moves(turn):
all_moves.append(move)
king = pieces[f"{turn}_king"]
if all_moves == [] and isAttacked(king.color, king.coordinates):
return True
return False
def gameover(text):
global game_over, got
game_over = True
got = text
def isDraw(turn):
... | The main task of the code is to determine if a chess game has ended in checkmate or a draw. It checks `isCheckMate(turn)` to declare checkmate and the winner (white/black), then uses `isDraw(turn)` to announce a draw. The function triggers `gameover()` with appropriate messages based on game state, ensuring proper outc... | def check_game_over():
if isCheckMate(turn):
gameover(f"Checkmate! {'white' if turn == 'black' else 'black'} Wins!")
elif isDraw(turn):
gameover("It's A Draw!") |
def isCheckMate(turn):
all_moves = []
for move, piece in get_moves(turn):
all_moves.append(move)
king = pieces[f"{turn}_king"]
if all_moves == [] and isAttacked(king.color, king.coordinates):
return True
return False
def isDraw(turn):
all_moves = []
for move, piece in get_moves(turn):
all_moves.append(m... | This function evaluates a chess game state using a minimax algorithm with alpha-beta pruning. It checks for checkmate or draw conditions, calculates material value and positional scores for pieces, and recursively explores possible captures to determine the optimal move outcome, updating alpha/beta bounds to optimize s... | def evaluate(isMaximizing):
global alpha, beta
if isCheckMate("white" if isMaximizing else "black"):
if isMaximizing:
return -infinity
else:
return infinity
elif isDraw("black" if isMaximizing else "white"):
return 0
piece_points = {
"pawn":100,
"knight":320,
"bishop":330,
"rook":500,
"queen... |
def evaluate(isMaximizing):
global alpha, beta
if isCheckMate("white" if isMaximizing else "black"):
if isMaximizing:
return -infinity
else:
return infinity
elif isDraw("black" if isMaximizing else "white"):
return 0
piece_points = {
"pawn":100,
"knight":320,
"bishop":330,
"rook":500,
"queen... | The code implements a minimax algorithm with alpha-beta pruning to determine the optimal move in a two-player game. It recursively evaluates possible moves for "white" (maximizing player) and "black" (minimizing player), updating scores and pruning branches where the current path cannot influence the final decision. Th... | def minmax(isMaximizing, depth, alpha, beta):
if depth == 0:
return evaluate(isMaximizing)
elif isMaximizing:
bestscore = -infinity
for move, piece in get_moves("white"):
makeMove(piece, move)
score = minmax(False, depth-1, alpha, beta)
undoMove()
bestscore = max(score, bestscore)
alpha = max... |
def get_moves(color):
moves = []
for piece in pieces_in_play:
if piece.color == color:
for move in get_legal_moves(piece):
if not move in moves:
if move == "O-O":
moves.append([move, piece])
continue
elif move == "O-O-O":
moves.append([move, piece])
continue
elif game... | The function determines the best move for the computer player ("black") using the minimax algorithm with alpha-beta pruning. It evaluates all possible moves, selects the one with the lowest score, executes it, updates the game state, and switches to the next player's turn. | def play_computer_move():
bestscore = infinity
bestmove = None
bestpiece = None
for move, piece in get_moves("black"):
makeMove(piece, move)
score = minmax(True, DEPTH-1, -infinity, infinity)
undoMove()
if score < bestscore:
bestmove = move
bestscore = score
bestpiece = piece
if bestmove:
m... |
def regExTanggal(inputString):
#Return match object or none
return re.search(r"([0-3][0-9](/|-)[0-1][0-9](/|-)([0-9]{4}|[0-9]{2}))|(([0-3][0-9]|[0-9])\s*(january|jan|february|feb|march|mar|april|apr|may|june|jun|july|jul|august|aug|september|sep|october|oct|november|nov|december|dec)\s*([0-9]{4}|[0-9]{2}))", inputStr... | The function processes user input to determine if the request is for all tasks or a specific time period (dates, weeks, days, or today). It identifies task types and retrieves relevant deadlines from the database, returning formatted task lists or error messages if no data matches the criteria. | def lihatDaftarTask(input, user_id):
keywordSemuaTask = ["sejauh ini", "semua", "all", "so far"]
##Flags for all
semuaTask = False
for i in keywordSemuaTask:
if kmp(i, input.lower()):
semuaTask = True
##Flags for time period
#Between 2 dates
date1 = regExTanggal(input)
date2 = None
if (date1):
slice... |
def opsi(string):
keywordsHelp = ["opsi","help","dilakukan", "lakukan"]
isHelp = False
for i in keywordsHelp:
if (kmp(i,string.lower())):
isHelp = True
break
if (isHelp):
fitur = "[Fitur]\n"
fitur = fitur+"1. Menambahkan task baru\n"
fitur = fitur+"2. Melihat daftar task yang harus dikerjakan\n"
... | The function processes a user message and user ID to determine the appropriate bot response by sequentially checking predefined task handlers. It returns specific task results if conditions are met, otherwise defaults to an error message. | def get_bot_message(message, user_id):
msgOpsi = opsi(message)
if msgOpsi: return msgOpsi
doneTask = taskDone(message, user_id)
if doneTask: return doneTask
undurTask = regex_undur(message, user_id)
if undurTask: return undurTask
find = findTask(message, user_id)
if find: return find
msgDaftar = lihatDaftarTas... |
def assets_mint(self, acronym:str, name:str, description:str, supply:int, file_path:str):
url = "api/currencies/mint/"
if file_path:
with open(file_path,'rb') as f:
picture_orig = f.read()
else:
picture_orig = None
data = {
... | This function mints a digital asset, waits for its minting transaction to complete, and returns the finalized asset. It takes metadata (acronym, name, description, supply) and a file path, initiates minting, retrieves the asset by ID, monitors the transaction status until it's marked 'minted', then returns the asset da... | def assets_mint_wait_finished(self, acronym:str, name:str, description:str, supply:int, file_path:str):
asset = self.assets_mint(acronym, name, description, supply, file_path)
asset = self.asset(asset['id'])
minting_transaction = self.transactions_wait_status(transaction_id=asset['minti... |
def _add_placeholders(self):
"""Add placeholders to the graph. These are entry points for any input data."""
hps = self._hps
# encoder part
self._enc_batch = tf.placeholder(tf.int32, [hps.batch_size, None], name='enc_batch')
self._enc_lens = tf.placeholder(tf.int32, [hps.batch_size], name='enc_lens... | The code constructs a TensorFlow graph for a sequence-to-sequence model by adding placeholders, building the model on a GPU, initializing a global step counter, and merging summaries. If in training mode, it also adds the training operation. The process is logged with timing information. | def build_graph(self):
"""Add the placeholders, model, global step, train_op and summaries to the graph"""
tf.logging.info('Building graph...')
t0 = time.time()
self._add_placeholders()
with tf.device("/gpu:0"):
self._add_seq2seq()
self.global_step = tf.Variable(0, name='global_step', trai... |
def has_outstanding_pages(self, site):
results_iter = self.r.table("pages").between(
[site.id, 0, self.r.minval, self.r.minval],
[site.id, 0, self.r.maxval, self.r.maxval],
index="priority_by_site").limit(1).run()
return len(list(results_iter)) > 0
def fin... | This function unclaims a site (and optionally a page), updates their statuses, and checks if the site is finished. It sets 'claimed' to False, records the last disclaim time, and triggers 'FINISHED' if no pages remain. If a page is provided, it unclaims and updates it. | def disclaim_site(self, site, page=None):
self.logger.info("disclaiming %s", site)
site.claimed = False
site.last_disclaimed = rethinkstuff.utcnow()
if not page and not self.has_outstanding_pages(site):
self.finished(site, "FINISHED")
else:
self.update_sit... |
def get_worms_mrgids(self, aphiaid: int) -> list:
res = pyworms.aphiaDistributionsByAphiaID(id=aphiaid)
distribution = [{"mrgid": re.search("\\d+", entry["locationID"])[0], "establishmentMeans": entry["establishmentMeans"]} for entry in res]
return distribution
def read_indexed_mrgid(self, mrgid... | The function retrieves and compiles marine species distribution data from WoRMS using an AphiaID. It fetches MRGIDs, attempts to load pre-indexed data, creates it if missing, and aggregates results into a DataFrame with MRGID and establishment means metadata. | def get_worms_distribution(self, aphiaid: int) -> pd.DataFrame:
logging.debug(f"Generating WoRMS distribution for https://www.marinespecies.org/aphia.php?p=taxdetails&id={aphiaid}")
shapes = self.get_worms_mrgids(aphiaid)
frames = []
for shape in shapes:
mrgid = shape["mrgid"... |
def read_distribution_grid(self, aphiaid: int) -> geopandas.GeoDataFrame:
logging.debug(f"Reading distribution data for https://www.marinespecies.org/aphia.php?p=taxdetails&id={aphiaid}")
filters = [("AphiaID", "==", aphiaid)]
gdf = geopandas.read_parquet("data/h3_7/", filters=filters)
r... | The code merges OBIS/GBIF distribution data with WoRMS taxonomic records, enriching them with establishment status flags (native/introduced/uncertain). It combines datasets, aggregates H3 grid data using DuckDB, adjusts resolution if needed, and returns a consolidated summary of species distribution with ecological con... | def create_summary(self, aphiaid: int, resolution: int = 7):
# get OBIS/GBIF data
distribution_grid = self.read_distribution_grid(aphiaid).filter(["h3_07", "source_obis", "source_gbif", "min_year", "max_year", "records"]).rename({"h3_07": "h3"}, axis=1)
distribution_grid["records"] = distribut... |
def _retrieve_ids(self, html_element_to_look_for_ids, soup) -> list:
"""
Retrieve ids
@:param html_element_to_look_for_ids:
@:param soup: A bs4 object
:return: list with ids
"""
id_list = []
for el in html_element_to_look_for_ids:
tags = soup.... | This function identifies and generates web element locators (IDs and XPaths) from the current webpage's HTML structure, filtering by specified element types (default: input/button). It optionally saves the locators to a Python file, organizing them as single entries or lists based on parameters. | def find_locators(self, check_ids: bool = True, html_element_types: list = None, save_path: str = "",
return_single: bool = False):
"""
Main entry point to find locators
@:param check_ids: Check IDs or not. Usually False is used for debug purposes
@:param html_elem... |
def genetic_step(models: list[Model]):
parentModels, ratio = createTournament(models, skipRounds=math.floor(math.log2(SIZE_PARENTS_POOL)))
newGeneration = crossover(parentModels)
newGeneration = mutate(newGeneration)
return ([Model(torchga.model_weights_as_dict(Net(),newGeneration[i])) for i in range(len(newGenera... | The code implements a genetic algorithm to evolve neural network models. It initializes a population of models, iteratively applies selection and evolution steps, tracks the best-performing models based on a fitness ratio, and periodically evaluates them in tournaments. Progress is logged, and model checkpoints are sav... | def evolution(weights = None):
models = [Model(weights, index=i) for i in range(SIZE_TOURNAMENT)]
bestScore = -1
bestModels = []
for i in range(EPOCHS):
models, ratio = genetic_step(models)
if(ratio > bestScore):
bestScore = ratio
bestModels = models
if(i % 10 == 0):
print(str(i) + ": " + str(ratio))... |
def speak(text):
engine.say(text)
engine.runAndWait()
def takeCommand():
r = sr.Recognizer()
with sr.Microphone(device_index=0) as source:
print('\n\nListening..say something: \n')
speak('Recognizing...please speak')
# use the default microphone as the audio source
... | This code automates YouTube controls via voice commands, using keyboard presses to pause/resume, mute/unmute, skip, adjust volume, switch tabs/windows, and activate fullscreen/film modes. It listens for user input in a loop, executing predefined actions based on spoken commands until the user requests to stop or exit. | def youtube_automate():
speak('do you want to give me any command for the automation of youtube!')
c=takeCommand()
b=['yes','sure','you search','i want','please','hnn','ok','yes i want']
while c.lower() in b:
speak("what's your command,sir?")
a=takeCommand()
com=a.lower()
... |
def speak(text):
engine.say(text)
engine.runAndWait()
def takeCommand():
r = sr.Recognizer()
with sr.Microphone(device_index=0) as source:
print('\n\nListening..say something: \n')
speak('Recognizing...please speak')
# use the default microphone as the audio source
... | This function automates browser tasks via voice commands, executing keyboard shortcuts for navigation, zoom, bookmarks, data clearing, and other actions. It listens for user input, processes commands like "back page" or "zoom in," and performs corresponding operations using the keyboard module. The loop continues until... | def google_automate():
speak('do you want to give me any command for the automation of your browser!')
c=takeCommand()
b=['yes','sure','you search','i want','please','hnn','ok','yes i want']
while c.lower() in b:
speak("what's your command,sir?")
a=takeCommand()
com=a.lower()... |
def takeCommand():
r = sr.Recognizer()
with sr.Microphone(device_index=0) as source:
print('\n\nListening..say something: \n')
speak('Recognizing...please speak')
# use the default microphone as the audio source
r.adjust_for_ambient_noise(source, duration=1) #wait for 10 se... | The main task of the code is to create a voice-controlled desktop assistant that processes user commands to perform various tasks such as searching Wikipedia, activating face mask detection, controlling applications (opening/closing programs, managing windows), handling text input/output, executing speed tests, setting... | def task_gui():
while True:
query=takeCommand()
if 'wikipedia' in query.lower():
print('\nSearching wikipedia...'+MASTER+' \n')
speak('Searching wikipedia...'+MASTER)
query = query.replace('wikipedia', '')
results = wikipedia.summary(query, sentences=3... |
def update_toolbar(self):
# Disable the navigation when Forever is selected.
next_prev = self.period != FOREVER
self.prevperiodbtn.set_sensitive(next_prev)
self.thisperiodbtn.set_sensitive(next_prev)
self.nextperiodbtn.set_sensitive(next_prev)
# This is a HACK to transla... | This function handles a period change event by updating the period value, refreshing the toolbar, setting the start of the current period, and rebuilding the screen to reflect the new period settings. | def __period_changed_cb(self, widget, value):
self.period = int(value)
self.update_toolbar()
# Jump to 'this period'.
self.period_start = self.get_this_period()
self.build_screen() |
def create_transaction(self, name='', type='debit', amount=0,
category='', date=datetime.date.today()):
id = self.data['next_id']
self.data['next_id'] += 1
t = {
'id': id,
'name': name,
'type': type,
'amount': amount,
... | The main task of the code is to generate a set of sample financial transactions for testing purposes. It creates a series of categorized transactions (e.g., rent, food, pets) with specific dates, amounts, and types (credit/debit), starting from the first day of the current month. The function systematically adds recurr... | def create_test_data(self):
cur_date = datetime.date.today()
cur_date = datetime.date(cur_date.year, cur_date.month, 1)
self.create_transaction('Initial Balance', type='credit', amount=632,
category='Initial Balance', date=cur_date)
cur_date += datetime.t... |
def _set_internal_panel(self, widget):
if self.screenbox.get_children():
self.screenbox.remove(self.screenbox.get_children()[0])
self.screenbox.pack_start(widget, True, True, 0)
widget.show_all()
self._active_panel = widget
self.build_screen()
def show_header_controls... | The main task of the code is to read a plain text JSON file, parse its content into a structured data format, and initialize UI components by setting internal panels, header controls, and building transaction maps and names based on the parsed data. | def read_file(self, file_path):
if self.metadata['mime_type'] != 'text/plain':
return
fd = open(file_path, 'r')
try:
text = fd.read()
self.data = json.loads(text)
finally:
fd.close()
if self.data['transactions']:
self.... |
def get_this_period(self):
today = datetime.date.today()
if self.period == DAY:
return today
elif self.period == WEEK:
while today.weekday() != 0:
today -= datetime.timedelta(days=1)
return today
elif self.period == MONTH:
... | This code initializes a financial management application with features for tracking transactions, budgets, and visualizing financial data. It sets up data structures to store transactions and budgets, creates UI components like a register, chart, and budget screens, and configures a summary view displaying key financia... | def __init__(self, handle):
activity.Activity.__init__(self, handle)
self.set_title(_("Finance"))
self.max_participants = 1
# Initialize database.
# data
# next_id
# transactions
# id, name, type, amount, date, category
# budgets
... |
def new_delta(self):
delta = 0
while 0 == delta:
delta = np.random.randint(-5, 6)
return delta
def new_row_col(self):
row = np.random.randint(0, self.grid_size)
col = np.random.randint(0, self.grid_size)
return row, col
def make_step(self, row, col, delta):
... | The code selects a grid position (row, col) using either biased probability distribution (via self.idx_cost) or random selection, then returns a step generated by self.make_step with the chosen position and a newly computed delta value. | def iteration(self):
delta = self.new_delta()
if self.biased_costs:
idx = np.random.choice(self.h.size, 1, p=self.idx_cost)[0]
row = idx // self.grid_size
col = idx % self.grid_size
else:
row, col = self.new_row_col()
return self.make_step(... |
def calc_constrains(self):
for i in range(self.grid_size):
self.u[:, i + 1] = self.u[:, i] + self.S * (self.pics[1][:, i] - self.pics[0][:, i])
self.u += (self.S * self.pics[0][:, 0])[:, np.newaxis]
eq3_constrains = self.S * (-self.pics[0][:self.grid_size - 1, :] + self.pics[0][1:, :... | The main task of the code is to generate a mesh by calculating constraints, exporting them into a mesh structure, and saving the resulting mesh to an output. This process likely involves computational geometry or 3D modeling, where constraints define the mesh's parameters, which are then transformed into a mesh format ... | def produce_pix(self):
self.calc_constrains()
self.export_constrains_to_mesh()
self.save_mesh_to_output() |
def create_schema(schemaName: str):
"""Creates a schema in the database."""
sql = get_sql_from_script("./scripts/sql/create_schema.sql")
sql_formatted = SQL(sql).format(Identifier(schemaName))
execute_query(sql_formatted)
def execute_query_from_script(sql_filepath: str, vars=None):
"""Executes a SQL... | The main task of the code is to load API data into a PostgreSQL database by creating a landing table, inserting JSON-formatted data, executing stored procedures for data transformation (e.g., expanding JSON, processing tracks, albums, artists, and snapshots), and truncating staging tables to prepare for new data. The p... | def main(data_to_load: dict):
"""Loads API data into Postgres database.
Parameters:
data_to_load: The data to be loaded into the database
"""
# Create the landing table if it doesn't exist
create_schema("import")
execute_query_from_script("./scripts/sql/ct_import_playlist_snapshot.sql")
... |
def get_ticker_info(self):
self.nonce_up()
try:
url = BASE_URL + TICKER_INFO_ENDPOINT + self.ticker
response = requests.get(url)
data = response.json()
return float(data["last"]), float(data["ask"]), float(data["bid"])
except Exception as e:
... | The code implements a trading strategy that alternates between placing buy and sell orders based on predefined conditions, monitoring order status, and adjusting positions. It uses margin thresholds to trigger order cancellations if market movements oppose the trade, updating the bot's state and remaining amounts accor... | def strategy1(self):
#BTC SPREAD IS ~ .0002 * price
print("")
print("---"*10)
print("Getting ticker info for {}".format(self.ticker))
print(self.amountToBuy, self.amountToBuy)
if self.amountToSell <= 0 and self.amountToBuy <= 0:
self.end_condition_met = True
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.