dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_cdxj_path(warc_cdxj, cdxj_dir):
"""Take the WARC CDXJ, replace the extension, and return the path/filename of the CDXJ."""
w_cdxj = os.path.basename(warc_cdxj)
cdxj_file = re.sub(r'\.cdxj$', '_merged.cdxj', w_cdxj)
logging.info('Creating CDXJ %s', cdxj_file)
return os.path.join(cdxj_dir, ... | The code merges two CDXJ files by matching SURT URLs and timestamps, combining fields from a metadata CDXJ with an original WARC CDXJ. It writes the merged records into a new CDXJ file, logs the process, and outputs statistics like merged records and elapsed time. | def merge_cdxjs(metadata_cdxj, warc_cdxj, cdxj_dir):
"""Merge fields from a sidecar CDXJ with an original WARC CDXJ.
Finding the matching key (SURT URL and timestamp) of the CDXJ's,
collect the wanted fields from the sidecar CDXJ, combine them
with the original WARC CDXJ and write the combined records ... |
def get_marked_and_images_ordered(soup, image_xpaths):
ordered_lists = []
current_list = []
for tag in soup.descendants:
if type(tag) is NavigableString and tag.parent.has_attr('x-boilerpipe-marker'):
current_list.append(tag.parent)
if type(tag) is Tag and get_xpath(tag) in image... | The code extracts textual content from an image's HTML by iterating through tags, yielding sentences from 'img' alt attributes and inline tag strings, converting them into sentence-level outputs for further processing. | def extract_content(image):
for tag in get_marked_and_images_ordered(get_marked_soup(image), image.page.xpath):
if tag.name == 'img' and tag.has_attr('alt'):
yield from to_sentences(tag['alt'])
if tag.string:
yield from to_sentences(tag.string) |
def compose(*funcs):
"""Compose arbitrarily many functions, evaluated left to right.
Reference: https://mathieularose.com/function-composition-in-python/
Used to compose layers, analogous to tf.keras.Sequential
"""
# return lambda x: reduce(lambda v, f: f(v), funcs, x)
if funcs:
return ... | This function creates a neural network block combining a bottleneck structure with two additional convolutional layers. It processes input features through a bottleneck_block (reducing dimensions), followed by a 1x1 convolution and a 3x3 convolution with batch normalization and Leaky ReLU, enhancing feature extraction ... | def bottleneck_x2_block(outer_filters, bottleneck_filters):
"""Bottleneck block of 3x3, 1x1, 3x3, 1x1, 3x3 convolutions."""
return compose(
bottleneck_block(outer_filters, bottleneck_filters),
DarknetConv2D_BN_Leaky(bottleneck_filters, (1, 1)),
DarknetConv2D_BN_Leaky(outer_filters, (3, 3... |
def usage():
parser = argparse.ArgumentParser(description="Gene Neighborhood Visualization")
parser.add_argument("--seed", help="list of gff files with locus of interest")
parser.add_argument("--prefix", help="specify the output prefix")
parser.add_argument(
"--window_size",
help="Size ... | The code generates a visual diagram of gene neighborhoods from multiple GFF files. It processes each GFF to extract features, assigns distinct colors to operons, and assembles them into a linear GenomeDiagram. The output is a PDF with tracks representing each genome, highlighting gene locations and relationships, using... | def main():
args = usage()
gff_list = args["seed"]
prefix = args["prefix"]
window_size = args["window_size"] # 20000
operon_size = args["operon_size"] # 3
diagram = GenomeDiagram.Diagram(f"{prefix}")
num_genomes = 0
# the random color generator generate operon_size 'distinct' colors
... |
def clear_screen(self):
# clear screen for specific operating system
sleep(1)
_ = call('clear' if os.name == 'posix' else 'clear')
def print_centre(self, s, animation=False):
print(s.center(shutil.get_terminal_size().columns))
def set_initial_hand(self):
self.shuffle_deck()
... | This code implements a Blackjack game loop, handling player and dealer turns, scoring, and game outcomes. It allows the player to hit/stand, checks for busts or Blackjack wins, and compares scores with the dealer. The game resets and replays based on user input, with screen clearing and animations for interactive gamep... | def play_blackjack(self):
# clears screen before starting game
self.clear_screen()
# handles gameplay replay
end_game = False
# main game loop
while end_game == False:
# clear screen and print welcome message
self.clear_screen()
sel... |
def clear_screen(self):
# clear screen for specific operating system
sleep(1)
_ = call('clear' if os.name == 'posix' else 'clear')
def print_welcome_and_get_name(self):
# self.load_animation('~Welcome to Blackjack!~', 40)
self.print_centre('~Welcome to Blackjack!~')
sleep... | The code initializes a Blackjack game by setting constants (MAX_HIT_SCORE, DEALER_STAND_SCORE), clearing the screen, creating a deck, initializing player and dealer objects (with player name input), and triggering the game loop via play_blackjack(). The main task is to set up game components and initiate gameplay. | def __init__(self):
# assign member variables
self.MAX_HIT_SCORE = 21
self.DEALER_STAND_SCORE = 17
# get and set game info
self.clear_screen()
self.deck = Deck.Deck()
self.player = Player.Player(
self.print_welcome_and_get_name(), self.MAX_HIT_SCORE)... |
def getWidth(node):
if node.trueSubtree == None and node.falseSubtree == None:
return 1
else:
return getWidth(node.trueSubtree) + getWidth(node.falseSubtree)
def getHeight(node):
if node.trueSubtree == None and node.falseSubtree == None:
return 0
else:
return 1 + max(getHeight(node.trueSubtree),... | The main task of the code is to generate a visual representation of a tree structure as an image file. It calculates the image dimensions based on the tree's width and height, creates a white canvas, draws tree nodes recursively starting from the root at the top center, and saves the resulting image as a JPEG file name... | def drawTree(tree, file='tree.jpg'):
w = getWidth(tree) * 100
h = getHeight(tree) * 100 + 120
img = Image.new('RGB', (w, h), (255, 255, 255))
draw = ImageDraw.Draw(img)
drawNode(draw, tree, w / 2, 20)
img.save(file, 'JPEG') |
def get_height(cluster):
if cluster.left == None and cluster.right == None:
return 1
return get_height(cluster.left) + get_height(cluster.right)
def get_depth(cluster):
if cluster.left == None and cluster.right == None:
return 0
return max(get_depth(cluster.left), get_depth(cluster.right)) + cluster.dis... | This code generates a dendrogram visualization from a cluster hierarchy, saving it as a JPEG image. It calculates dimensions based on cluster depth, creates a white canvas, draws horizontal lines for cluster nodes, and recursively plots each node's position using scaling. The result is a graphical representation of hie... | def draw_dendrogram(cluster, labels, jpeg='clusters.jpg'):
h = get_height(cluster) * 20
w = 1200
depth = get_depth(cluster)
scaling = float(w - 300) / depth
img = Image.new('RGB', (w, h), (255, 255, 255))
draw = ImageDraw.Draw(img)
draw.line((0, h / 2, 10, h / 2), fill = (255, 0, 0))
draw_node(draw, clu... |
def buildTree(rows, scoref = entropy):
if len(rows) == 0:
return DecisionNode()
currentScore = scoref(rows)
bestGain = 0.0
bestCriterion = None
bestSets = None
columnCount = len(rows[0]) - 1
for column in range(0, columnCount):
columnValues = {}
for row in rows:
columnValues[row[column]]... | The main task of the code is to load car dataset, construct a decision tree using the data, and visualize the tree structure by printing and drawing it. The commented-out test case suggests the tree is intended for classification, but the active lines focus on tree generation and representation. | def main():
# data = sample
data = util.loadCarData()
# tree = buildTree(sample)
tree = buildTree(data)
# testSample = ['digg', 'USA', 'yes', 19]
# result = classify(testSample, tree)
# print(result)
printTree(tree)
drawTree(tree) |
def read_file(filename):
with open(filename) as f:
lines = f.readlines()
colnames = lines[0].strip().split('\t')[1:]
rownames = []
data = []
for line in lines[1:]:
parts = line.strip().split('\t')
rownames.append(parts[0])
data.append([float(x) for x in parts[1:]])
return colnames, rownames,... | The code reads data from 'blogdata.txt', performs hierarchical clustering on the data using `hcluster`, and visualizes the resulting clusters with a dendrogram via `draw_dendrogram`, using row names as labels. | def main():
colnames, rownames, data = read_file('blogdata.txt')
# print(colnames[:3])
# print(rownames[:3])
# print(data[1][3:9])
root = hcluster(data)
# print_cluster(root, labels=rownames)
draw_dendrogram(root, labels=rownames) |
def seed_torch(seed):
seed = int(seed)
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = Fals... | The main task of the code is to train and test a PFSSA model for hyperspectral image abundance mapping. It initializes the model, loads data, trains using a custom loss function with learning rate scheduling, saves checkpoints, evaluates on test data, and outputs metrics and abundance maps. The process includes data au... | def main():
seed = 42
seed_torch(seed)
opt = get_args();
epochs = opt.epochs
batch_size = opt.batch_size
lr =opt.lr
train_set_ratio = opt.train_set_ratio
valid_set_ratio = opt.valid_set_ratio
aug_times = opt.aug_times
gamma = opt.gamma
patch_size = opt.patch_size
weight =... |
def reset_bank():
strategy['bank'] = 1000
def roulette():
# plays the game of Roulette with a globally defined strategy
# Returns bank
from random import randint
bank = strategy['bank']
stake = strategy['stake']
target = strategy['target']
stoploss = strategy['stoploss']
bet_incre... | This function tests a strategy's performance over up to 100 iterations by simulating roulette outcomes. It tracks the 'bank' balance in 'test_a', stopping if the bank becomes negative or after 100 iterations. If the final balance is ≥ the initial balance, it calls test_further_b(); otherwise, it breaks. The goal is to ... | def test_further_a():
iterations = 0
test_a = []
# print("Testing to 100")
reset_bank()
while iterations <= 100 and strategy['bank'] >= 0:
iterations += 1
# Produce a result using the current strategy
roulette()
# ad... |
def reset_strategy():
strategy = {
"bank" : 1000,
"stake" : 2,
"target" : 1.5, # defines when to stop playing should the bank * this amount is reached
"stoploss" : 0.5, # defines the size of the bet (* bank) which should make the machine step away from the table.
"bet_increase_lose" : 2, #define... | The roulette_player function tests strategies in a roulette game. It iterates up to 10 times, appending results to first_test. If the 10th result is a loss, it randomizes a new strategy. If the 10th result is a win, it tests the strategy further with test_further_a, then proceeds to test_further_b and test_further_c. T... | def roulette_player():
"""
Roulette player manages the roulette function.
If the strategy isn't producing money, it generates a random strategy.
If it works after 10 iterations, it is tested via test_further_a, then test_further_b, then test_further_c.
"""
iterations = 0
strategy... |
def Write_Mpu6050_REG(self,reg,dat):
buf=bytearray(1)
buf[0]=dat
self.i2c.writeto_mem(MPU_ADDR,reg,buf)
def MPU_Set_Gyro_Fsr(self,fsr):
return self.Write_Mpu6050_REG(MPU_GYRO_CFG_REG,fsr<<3)
def MPU_Set_Accel_Fsr(self,fsr):
return self.Write_Mpu6050_REG(MPU_ACCEL_CFG_REG,fsr... | The main task of the code is to initialize the MPU6050 sensor by configuring power management, sensor ranges (gyro/accel), data rate, and verifying the device ID. It resets the sensor, disables interrupts/FIFO, checks for correct device ID (0x68), and returns 0 on success or 1 if the ID mismatch occurs. | def MPU_Init(self):
self.Write_Mpu6050_REG(MPU_PWR_MGMT1_REG,0x80)
time.sleep_ms(100)
self.Write_Mpu6050_REG(MPU_PWR_MGMT1_REG,0x00)
self.MPU_Set_Gyro_Fsr(3)
self.MPU_Set_Accel_Fsr(0)
self.MPU_Set_Rate(50)
self.Write_Mpu6050_REG(MPU_INT_EN_REG,0x00)
self.W... |
def get_factory_servers(waveid, token, UserHOST):
try:
linux_exist = False
windows_exist = False
auth = {"Authorization": token}
# Get all Apps and servers from migration factory
getservers = json.loads(requests.get(UserHOST + serverendpoint, headers=auth).text)
#prin... | The main task of the code is to validate prerequisites for migrating Windows and Linux servers using AWS Migration Hub. It parses command-line arguments, authenticates to the migration factory, retrieves server lists, checks system-specific requirements (e.g., credentials, configurations), and reports results. The scri... | def main(arguments):
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--Waveid', required=True)
parser.add_argument('--ReplicationServerIP', required=True)
parser.add_argument('--WindowsUser', default="")
... |
def execute_cmd(host, username, key, cmd, using_key):
output = ''
error = ''
ssh = None
try:
ssh = open_ssh(host, username, key, using_key)
if ssh is None:
error = "Not able to get the SSH connection for the host " + host
print(error)
else:
std... | The main task of the code is to install the AWS Application Migration Service Agent on a Linux host. It downloads the installation script, ensures dependencies like wget and Python are present, executes the installer with provided AWS credentials and region, and returns success/failure status based on the installation ... | def install_mgn(agent_linux_download_url, region, host, username, key_pwd, using_key, AccessKeyId, SecretAccessKey):
print("")
print("--------------------------------------------------------------------")
print("- Installing Application Migration Service Agent for: "+ host + " -")
print("--------------... |
def _createGameboard(self, gameWidth):
gameBoard = list()
positionSpot = itertools.count(1)
for widthPosition in range(gameWidth):
gameRow = list()
for horizontalPosition in range(gameWidth):
gameRow.append(str(next(positionSpot)))
... | The main task of the code is to initialize and play a Tic Tac Toe game by creating a 3x3 gameboard and input array, handling player turns through the `takeTurns` function, and prompting the user to play again via `PlayAgain`. It prints a welcome message and orchestrates the game flow. | def PlayTicTacToe(self):
print("Welcome to Tic Tac Toe!")
takeTurns(self._createGameboard(3), self._createInputArray(3))
self.PlayAgain() |
def main():
email, password = config_login()
choice = config_module()
start, end = config_process_list_items()
return email, password, choice, start, end
def driver_start():
global driver
if driver is None:
path = 'selenium/chromedriver.exe'
url_login = 'https://learning-ind.refo... | The code automates logging into a web application using provided credentials, navigates through interfaces, and executes a module selection task with specified parameters. It handles errors during the process, ensuring the script continues or terminates based on login success and task execution. | def micro_run():
print('''
██╗ ███████████╗ ██╗ ██████╗ ██╗ ██╗██████╗██████╗██╗ ██████╗
██║ ████╔════██║ ██║ ██╔═══██╗ ██║ ████╔═══████╔══████║ ██╔══██╗
████████████╗ ██║ ██║ ██║ ██║ ██║ █╗ ████║ ████████╔██║ ██║ ██║
██╔══████╔══╝ ██║ ██║ ... |
def _retrieve_access_token(self):
try:
_ = pickle.load(open("config/auth_token.pickle", "rb"))
return _
except:
self._o_auth()
def _o_auth(self):
print('Authenticating please wait...')
self._check_config()
executable_path = {'executable_path': ... | This code manages token authentication by checking the expiration status of access and refresh tokens. If the refresh token is near expiration, it initiates OAuth; if the access token is expiring soon, it refreshes the token. Otherwise, it checks token status without action, ensuring continuous authenticated session ma... | def _td_login(self):
self._retrieve_access_token()
if self.access_token['refresh_token_expires_at'] - 100 <= int(time.time()):
self._o_auth()
elif self.access_token['access_token_expires_at'] - 50 <= int(time.time()):
self._o_auth_refresh()
else:
print... |
def find_priority(start: Cell, goal: Cell, g: dict, big_g_pref: bool) -> int: # not sure if works 100%
# finding f value
f = g[(start.x, start.y)] + heuristic(start, goal)
# constant bigger than any possible generated g value
c = start.maze.w * start.maze.h
# packing a random large number to break ... | This function simulates a repeated A* search where an agent navigates a maze using limited vision, updating its knowledge of obstacles as it moves. It initializes search parameters, expands paths via A*, and tracks expanded cells. The agent follows computed paths until encountering obstacles, updating the vision maze d... | def repeated_forward_a_star_search_experiment(screen, actual_maze: Maze, vision_maze: Maze, start: Cell, goal: Cell, big_g_pref: bool) -> int:
pygame.draw.rect(screen, (255, 0, 0), (actual_maze.get(
goal.x, goal.y).rect.x, actual_maze.get(goal.x, goal.y).rect.y, Cell.w, Cell.h))
counter = 0 # the valu... |
def find_priority(start: Cell, goal: Cell, g: dict, big_g_pref: bool) -> int: # not sure if works 100%
# finding f value
f = g[(start.x, start.y)] + heuristic(start, goal)
# constant bigger than any possible generated g value
c = start.maze.w * start.maze.h
# packing a random large number to break ... | The function performs repeated backward A* searches to navigate from a start to a goal in a maze, updating the agent's vision dynamically as it moves. It tracks the number of expanded cells during each search iteration, handling obstacles by recalibrating paths. The process continues until the goal is reached, returnin... | def repeated_backward_a_star_search_experiment(screen, actual_maze: Maze, vision_maze: Maze, start: Cell, goal: Cell, big_g_pref: bool) -> int:
pygame.draw.rect(screen, (255, 0, 0), (actual_maze.get(
goal.x, goal.y).rect.x, actual_maze.get(goal.x, goal.y).rect.y, Cell.w, Cell.h))
counter = 0 # the val... |
def find_random_cell(maze) -> Cell:
while True:
x = random.randint(1,maze.w-2)
y = random.randint(1, maze.h-2)
if not isinstance(maze.grid[x][y], Wall):
return maze.grid[x][y]
def make_maze_unsolvable(screen, actual_maze, goal: Cell) -> Maze:
directions = [(-1, 0), (1, 0), (0... | The code compares the performance of Forward Repeated A* algorithms with "big g" (preference for higher path costs) and "little g" (preference for lower path costs) tie-breaking strategies across multiple mazes. It generates mazes, runs both algorithms, tracks expanded cells, and calculates averages to evaluate how tie... | def big_g_vs_little_g(screen, num_mazes):
expanded_cells_list_big_g = []
expanded_cells_list_little_g = []
for i in range(int(num_mazes)):
print("Testing maze", i+1, "out of",num_mazes,"!")
pygame.display.set_caption("Forward Repeated A* (Big g preference)")
maze = Maze(WINSIZE)
... |
def find_random_cell(maze) -> Cell:
while True:
x = random.randint(1,maze.w-2)
y = random.randint(1, maze.h-2)
if not isinstance(maze.grid[x][y], Wall):
return maze.grid[x][y]
def make_maze_unsolvable(screen, actual_maze, goal: Cell) -> Maze:
directions = [(-1, 0), (1, 0), (0... | The code compares the performance of repeated forward and backward A* algorithms on multiple mazes by generating random mazes, running both search methods, and calculating the average number of expanded cells. It tests solvable and unsolvable mazes, tracks expansion counts, and prints statistics for each approach, high... | def forward_vs_backward(screen, num_mazes):
expanded_cells_list_forward = []
expanded_cells_list_backward = []
for i in range(int(num_mazes)):
print("Testing maze", i+1, "out of",num_mazes,"!")
pygame.display.set_caption("Repeated Forward A*")
maze = Maze(WINSIZE)
maze.genera... |
def erase(self):
for screen in self.screen_list:
screen.erase()
def inputScreenDraw(self):
if self.input_screen != None:
height, width = self.input_screen.getmaxyx()
spacing = ' ' * (width - len(self.ui.input_prompt) - len(self.ui.input_str) - 3)
self.addLine(self.input_screen, f'... | This code renders UI elements by erasing the screen, drawing input/menu screens, splitting lines by screen, applying scrolling logic, and rendering text with attributes. It handles special cases for input/menu screens, adjusts text positioning, and updates the display with empty lines and refreshes the curses window. | def draw(self):
self.erase()
# Handle optional screens
if self.input_screen != None:
self.inputScreenDraw()
if self.menu_screen != None:
self.menuScreenDraw()
self.splitLineListByScreen()
self.setViewTotalLines()
for screen, lines in self.screen_lines.items():
height, wid... |
def get_cols_from_inheaders(df, headers):
if not df.empty:
cols = df.columns
cols = re.split(r'\s*&\s*', headers) if headers else []
for c in cols:
if not( '*' in c or '!' in c or ('[' in c and ']' in c) or ('{' in c and '}' in c) ) and not( c in cols ):
logging.e... | The main task of the code is to read and process multiple input CSV files containing inferior, superior, and optionally third-level headers, merge them based on specified columns, generate cross-references, reorganize data structure (including column order and row explosion), remove duplicates, and output the processed... | def main(args):
'''
Main function
'''
logging.info("read input files of inferior header")
# with concurrent.futures.ProcessPoolExecutor(max_workers=args.n_workers) as executor:
# infdat = executor.map(read_infiles,args.inf_infiles.split(";"))
# infdat = pd.concat(infdat)
... |
def cnn():
print("\nChoose News Type (type number)")
time.sleep(2)
print("(1) Top Stories")
print("(2) World")
print("(3) U.S.")
print("(4) Politics")
print("(5) Technology")
print("(6) Health")
print("(7) Entertainment")
time.sleep(1)
print("Press Q to Quit\n")
time.slee... | The code defines a function `sourceSorter()` that repeatedly prompts the user for input until a valid option (1-4, 'q', 'quit', or 'c') is selected. Depending on the choice, it calls corresponding functions (`cnn()`, `bbc()`, etc.), quits the program, or runs a custom function. Its main task is to handle user menu navi... | def sourceSorter():
c = ""
while c not in ["1", "2", "3", "4", "q", "Q", "quit", "c", "C"]:
c = input("Enter choice: ").lower()
if c == "1":
cnn()
if c == "2":
bbc()
if c == "3":
cnbc()
if c == "4":
nytimes()
if c == "q" or c == "quit":
quit()
... |
def preprocess(data):
# impute
data.replace('?', value=None, inplace=True) # interpolates missing values using default method='pad'
# remove date and time column
datetime_col = data[["Date", "Time"]]
data = data.drop(columns=["Date", "Time"])
# normmalize
std_scaler = StandardScaler()
da... | The main task of the code is to process and cluster time-series data from a CSV file. It filters data for a specific date, preprocesses it, applies clustering with parameters E=0.6 and min_pts=14, and outputs the number of objects in each cluster. The code focuses on analyzing data patterns through filtering, preproces... | def main(filename):
print("working...")
data = pd.read_csv(filename)
data = data[data['Date'].apply(lambda x: x.endswith('/1/2007'))]
processed_data = preprocess(data)
# print("Generating k-distance-diagram...")
# start = time.time()
# k_distance(processed_data)
# print(processed_data)
... |
def get_light(time):
value = readLight()
x = {"sensorID": "0", "typeSensor": "light", "typeValue": "float", "value": value, "time": str(time)}
return x
def get_humidity():
value = 0
x = {"sensorID": "1", "typeSensor": "humidity", "typeValue": "float", "value": value}
return x
def get_pressure():... | The code's main task is to gather sensor data including light, humidity, pressure, and temperature, using the current datetime for light measurement, then serialize these values into a JSON-formatted string for output. | def hello_world():
import datetime
return json.dumps([get_light(datetime.datetime.now()), get_humidity(), get_pressure(), get_temp()]) |
def make_empty_grid():
grid=[]
gap=WIDTH//9
for i in range(9):
grid.append([])
for j in range(9):
grid[i].append(Cell(i,j,0,gap))
return grid
def update_selected(grid,inputBox):
gap=WIDTH//9
mouse=pygame.mouse.get_pos()
click=pygame.mouse.get_pressed()
if clic... | This code implements a graphical Sudoku solver with user interaction. It allows generating puzzles, inputting numbers, clearing the board, and solving via backtracking. The interface includes buttons, input fields, and checkboxes for solving methods. It handles valid/invalid input visualization, updates the grid dynami... | def main():
grid=make_empty_grid()
user_defined_grid=True
generateBTN = Button(244, 515, "Generate")
clearBTN = Button(344, 515, "Clear Board")
inputBox=InputBox(190,503,40,0)
solveBTN=Button(468,298,"Solve",24)
StepsBox=CheckBox(494,195,10)
MVRbox=CheckBox(494,260,10)
buttons=[gene... |
def returnError(msg=""):
return {"success": False, "error": msg}
def getUrlType(url=""):
if isProfileUrl(url):
return URL_TYPE_PROFILE
elif isArticleUrl(url):
return URL_TYPE_ARTICLE
else:
return URL_TYPE_UNKNOWN
def convertToLanguage(url, lang="en"):
# hl is a parameter that... | The function validates a URL, determines its type (article or profile), converts it to English, and fetches corresponding details (article/profile) from a database. If invalid or unsupported, it returns errors. | def parseUrlAndFetch(db, url):
if url == None or url == "":
return returnError("URL_REQUIRED")
url = url.strip()
urlType = getUrlType(url)
# Setting the URLs to return English pages.
if urlType == URL_TYPE_ARTICLE:
current_app.logger.debug("Article Type")
url = convertToLangu... |
def series_h0(self):
# start the sum from 1 for Riemann i.e. when a = 0. This ensures Riemann sub case gives meaningful results
sum0 = nsum(lambda k: exp(2 * pi * self.i * self.lam * k) * power(k + self.a, -self.s)
if (re(k + self.a) > 0) else 0.0, [0, self.n0])
if self.debug:
... | The code computes the sum of three components (val_h0, val_h1, val_h2), each derived by adding an integral and series-residue terms for different parameters. It returns the total value and prints debug information if enabled. | def lerch_ours(self):
series_and_residues_h0 = self.series_h0() + self.series_residues_h0()
val_h0 = self.integral_h0() + series_and_residues_h0
series_and_residues_h1 = self.series_h1() + self.series_residues_h1()
val_h1 = self.integral_h1() + series_and_residues_h1
series_and... |
def series_h0(self, s): # series sum in Eq 70
sum0 = nsum(lambda k: power(k, -s), [1, self.n0])
if self.debug:
print('series_h0 : ', sum0)
return sum0
def series_residues_h0(self, s): # second series on the rhs of Eq 77
val = mpf('0.0')
for k in range(- self.num_of_... | The code computes a value `val_our` by combining the integral of `h0` at `s` with a series-residue adjustment. It subtracts residue contributions from the series expansion of `h0` and adds the result to the integral. Debug prints show intermediate values if enabled. The function returns the final computed value. | def total_value(self, s):
series_and_residues_h0 = self.series_h0(s) - self.series_residues_h0(s)
val_our = self.integral_h0(s) + series_and_residues_h0 # Eq 77
if self.debug:
print('series_plus_residue_h0 ', series_and_residues_h0)
print('val_our ', val_our)
r... |
def series_h0(self, s):
sum0 = nsum(lambda k: self.xchar(k) * power(k, -s), [1, self.n0])
if self.debug:
print('series_h0 : ', sum0)
return sum0
def series_residues_h0(self, s):
val = mpf('0.0')
for k in range(- self.num_of_poles + 1, self.num_of_poles + 1):
... | This function calculates a total value by combining the integral of a function `h0` with the difference between its series expansion and residues. It returns the computed value, with optional debug prints showing intermediate results if `self.debug` is True. | def total_value(self, s):
series_and_residues_h0 = self.series_h0(s) - self.series_residues_h0(s)
val_our = self.integral_h0(s) + series_and_residues_h0
if self.debug:
print('series_plus_residue_h0 ', series_and_residues_h0)
print('val_our ', val_our)
return val... |
def verify_character_is_primitive(self):
cd = nsum(lambda n: self.xchar(n) * exp(-2 * pi * self.i * n / self.md), [1, self.md])
abs_diff = 0
for j in range(1, self.md + 1):
sum_val = nsum(lambda n: self.xchar(n) * exp(-2 * pi * self.i * j * n / self.md), [1, self.md])
exp... | This code initializes a mathematical object with parameters for complex analysis, setting up attributes like chi (a character), alpha, poles, and complex variables (eps, i). It validates chi's properties, computes roots (r0), constructs a grid (lin_grid), and prepares values for further calculations, likely in number t... | def __init__(self, s, chi, alpha=mpf('1.0'), num_of_poles=1):
self.s = s
self.chi = chi
self.md = len(chi)
if self.md > 1:
assert (chi[0] == 0 and chi[1] == 1)
else:
assert (chi[0] == 1)
self.i = mpc('0', '1')
self.alpha = alpha
sel... |
def get_site(url):
soup = ""
print("Scraping " + url)
try:
r = requests.get(url, timeout=5)
text = r.text.encode('ascii', 'ignore').decode('ascii')
soup = BeautifulSoup(text, 'lxml')
print("Success")
except Exception as e:
print("Connection Timed Out")
retur... | The function processes a list of websites by fetching their content, extracting visible text, and collecting outgoing links. It iterates through each site, retrieves its HTML content, strips unnecessary data, and compiles the processed information into a list. If the retrieved content is invalid, it assigns an empty st... | def get_sites_info():
content = []
i=0
initSize = len(sites)
for site in sites[:initSize]:
i += 1
soup = get_site(site.url)
if soup != "":
# Get outgoing links
add_oLinks_to_sites(soup, site)
site.content = get_visible_text(soup, site)
... |
def generateLists(sites):
# docID = 0
for site in sites:
docID = sites.index(site) #Could be better - O(n)
title = site.title
# append description to content
if site.content != "":
content = site.content + site.description
content = site.content
url =... | The main task of the code is to invert input 'sites' into a postings list, using stop-word filtering and stemming as specified. It generates term lists, exports postings, times the process, and returns the postings. Global flags control stop-word and stemming usage, while 'generateLists' processes sites, and 'exportPos... | def invert(sites, stop, stem):
start_time = time.time()
global useStopWords
global useStemming
useStopWords = stop
useStemming = stem
generateLists(sites)
# exportDict(mainDict)
exportPostings(postings)
# print(postings)
print("Time to generate lists: %.2f seconds" % (time.time()... |
def getQuery(query):
global stem
global stop
if query == "":
query = input("Search: ")
inputList = query.split()
for i in range(len(inputList)):
inputList[i] = invert.preProcess(inputList[i],stop,stem)
return inputList
def generateQueryVector(query):
terms = sorted(postings.k... | The code's main task is to process a query by formatting and preprocessing it, generate a query vector, and retrieve the most relevant documents using similarity search. It measures the time taken to generate the ranking of documents and returns this ranking. The function leverages `getQuery`, `generateQueryVector`, an... | def search(Q):
query = getQuery(Q) # formats and pre-processes query
generateQueryVector(query)
genRankingforQ = time.time()
ranking = mostSimilar() # finds most relevant doc to query
print("Time to generate ranking: {}".format(time.time() - genRankingforQ))
return ranking |
def read_dataset(file_patterns) -> DataFrame:
"""Read a list of Parquet files into a DataFrame."""
spark = get_spark_session()
files = [str(x) for x in itertools.chain(*(glob.glob(x) for x in file_patterns))]
if not files:
raise ValueError(f"No files found with patterns {file_patterns}")
log... | The main task of the code is to process datasets by cleaning them with state FIPS codes, compute travel statistics, and save intermediate results. It reads input data, merges it with state codes, cleans the data, calculates travel metrics, and writes cleaned data and aggregated travel statistics to the specified output... | def _run_queries(file_patterns, state_fips_codes, output_dir: Path):
df = read_dataset(file_patterns)
state_fips_df = read_state_fips_codes(state_fips_codes)
cleaned_df = write_dataframe(
clean_data(df, state_fips_df),
output_dir,
"cleaned",
)
travel_stats_df = calc_travel_st... |
def log_message(message: str, logfile: Optional[str] = None) -> None:
"""Logs a message to the console and optionally to a file."""
print(message)
if logfile:
# Make sure the log file exists
if not os.path.exists(logfile):
open(logfile, 'a').close()
with open(logfile, 'a'... | The code converts TIF images to PNG to preserve quality while reducing file size for social media use. It processes either a directory of TIF files or specific file paths, applies a regex pattern for naming, adjusts output size, and logs operations. The script handles user inputs via command-line arguments, validates p... | def main() -> None:
try:
parser = argparse.ArgumentParser(description='Convert TIF images to PNG to preserve quality while reducing file size for use in social media.')
parser.add_argument('--dir', help='Directory to scan for TIF files.')
parser.add_argument('--file', nargs='+', help='File p... |
def assign():
global num_of_vehicles
global num_of_packages
global package_weight
global vehicles_capacity
# ***********************************************************************************************
# Define a namedtuple to store vehicle data
vehicle_tuple = namedtuple("Vehicle", ["ca... | The main task of the code is to execute a simulated annealing algorithm for solving a vehicle routing problem. It generates multiple solutions, evaluates their total distances, and identifies the best solution with minimal distance. The code prints all generated solutions and highlights the optimal one, aiming to optim... | def simulated_annealing_main():
assign()
best_solution, best_distance, all_solutions = simulated_annealing()
# Print all possible solutions
for i, solution in enumerate(all_solutions):
print(f"Solution {i + 1} (Vehicle assignments):", solution)
print("Total distance:", total_cost(soluti... |
def genetic_algorithm(population_size, num_generations, solution_limit):
all_solutions = [] # Create a list to store all evaluated solutions
for generation in range(num_generations):
# Generate a new population for the current generation using random_solution_generator
population = [random_sol... | This code uses a genetic algorithm to assign packages to vehicles while respecting capacity constraints and minimizing total travel distance. It collects input data, generates solutions, evaluates fitness, selects the optimal solution, handles unassigned packages, and visualizes the best assignment. | def assign_packages_with_genetic_algorithm():
global num_of_vehicles
global num_of_packages
global vehicles_capacity
package_tuple = namedtuple("Package", ["weight", "x", "y"])
vehicle_tuple = namedtuple("Vehicle", ["capacity", "assigned_packages"])
num_of_vehicles = int(input("Enter the number ... |
def _get_distance(self):
"""
calculates the distance between sensor and object
:return (float): distance
"""
# set Trigger to HIGH
GPIO.output(self.gpio_trigger, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(self.gpio_tri... | The code's main task is to control lights based on proximity detection. It measures distance using `_get_distance()`, logs the value if enabled, and turns lights on for a set duration when an object is within a predefined threshold. If no object is detected, it turns the lights off. The method also increments a counter... | def turn_lights_smart(self, log=True):
"""
turns light on or off based on smart logic
:param (boolean) log: if True prints measured distance
:return:
"""
distance = self._get_distance()
if log:
print("Distance = %.1f cm" % distance)
if distan... |
def turn_lights_smart(self, log=True):
"""
turns light on or off based on smart logic
:param (boolean) log: if True prints measured distance
:return:
"""
distance = self._get_distance()
if log:
print("Distance = %.1f cm" % distance)
if distan... | The code's main task is to control lighting based on the system mode. It checks `self.system_mode` and executes corresponding methods: `turn_lights_smart()`, `turn_lights_on()`, or `turn_lights_off()`. If the mode is invalid, it raises an exception. After executing the action, it pauses for 0.5 seconds using `time.slee... | def run(self):
if self.system_mode == SystemMode.SMART:
self.turn_lights_smart()
elif self.system_mode == SystemMode.ON:
self.turn_lights_on()
elif self.system_mode == SystemMode.OFF:
self.turn_lights_off()
else:
raise Exception("Wrong s... |
def cancelPending(self):
for x in self.pending:
self.after_cancel(x)
self.pending.clear()
def doCheckURLs(self, dl_options):
if self.checkURLs.get():
self.currVideo = 0
dl_options['simulate'] = True
try:
self.updateProgressBar(True)... | The main task of the code is to initiate and manage the downloading of URLs using YouTubeDL, with features like progress tracking, cancellation support, URL validation, and error handling. It configures download options, updates the UI to show progress, executes the download process, and handles success/failure states ... | def downloadURLs(self):
self.inputButton.configure(text="Cancel",
command=self.cancelDownload) #to cancel download
self.cancelPending() #get rid of any pending after() calls
self.progressFrame.grid(row=50) #show progress bars
self.progressBar['value'] = 0
self.currP... |
def lookup_observable(self, value, type=None):
"""Method lookups specific observable by value and type.
Args:
value: value of Observable
type: type of observable, e.g. ipv4, hash-md5 etc
Returns:
Return dictionary with Observable details:
{creat... | This method searches for entities using filters on entity value (with wildcard support), entity type, or observable values. It constructs API parameters, queries an entity database, and returns matching entity details as a list or False if no results. The search prioritizes entity IDs for precise lookups and observable... | def search_entity(self, entity_value=None, entity_type=None, observable_value=None):
"""Method search specific entity by specific search conditions.
Note: search works with wildcards for entity value and with strict conditions for everything else.
Also, it's recommended to use this method t... |
def generate_real_samples(dataset, num_samples):
random_index = randint(0,dataset.shape[0], num_samples)
X = dataset[random_index]
reals = np.ones((num_samples, 1))
return X, reals
def generate_fake_samples_with_model(generator_model, latent_dimension, num_samples):
x_input = generate_latent_points(... | This function trains a Generative Adversarial Network (GAN) by alternating between updating the discriminator with real/fake samples and training the generator via the GAN model. It iterates over epochs and batches, generates synthetic data, evaluates model performance, and saves the generator model when accuracy thres... | def train_complete_model(generator_model,
discriminator_model,
gan_model,
dataset,
latent_dimension,
num_epochs=100,
batch_size=32):
batches_per_epoch = int(dataset.shape[0] / batch_size)
half_batch = int(batch_size / 2)
converged = False
for i in range(num_epochs):
for j in range(batches_... |
def getIndexGameByID(game_id):
"""
A function that return a index of the games list by game id, that the games[index].id equal to that id
:param game_id:
:return: the index of the games list; if id not found return -1
"""
game_id = int(game_id)
i = 0
for game in games:
if game.id... | The code handles HTTP GET requests for a multiplayer game, managing player initialization, game creation, turn checks, move processing, and game state updates. It communicates with clients to provide game data, check for opponents, and manage sessions, ensuring real-time interaction and updates between players. | def do_GET(self):
"""
A function that handles all of the get request from the client
"""
global players
global players_names
# global won
global waitingForGame
global games
client_type = "VIEWER"
if self.path[:6] == '/init?': # if it's ini... |
def flightPreventedExposures(pod, droneVC, params, numFlights):
# If there are no teams at this pod, EPE = 0
if pod.teamsAtPOD == 0:
return 0
#create two variations of this POD, with differing vaccinesInStock values
beforeFlightsPOD = copy.deepcopy(pod)
afterFlightsPOD = copy.deepcopy(pod)
... | The function delivers vaccines using drones to maximize prevented exposures per minute (EPE), prioritizing PODs (Points of Distribution) with the highest EPE ratio. It schedules drones to deliver vaccines to PODs needing them, ensuring flights complete within working hours. It tracks deliveries, updates POD stock, and ... | def deliverVaccinesByDroneEPE(t, PODs, workingMinutes, droneVC, numDrones, params, mdP):
deliveries = 0
vaccinesDelivered = 0
n = len(PODs)
ratios = np.zeros(n)
for i in range(0,n):
pod = PODs[i]
if pod.vaccinesInStock != np.inf:
ratios[i] = flightPreventedExposures(... |
def deliverVaccinesByDroneEPE(t, PODs, workingMinutes, droneVC, numDrones, params, mdP):
deliveries = 0
vaccinesDelivered = 0
n = len(PODs)
ratios = np.zeros(n)
for i in range(0,n):
pod = PODs[i]
if pod.vaccinesInStock != np.inf:
ratios[i] = flightPreventedExposures(... | The function `deliverByDrone` determines the vaccine delivery method based on the provided strategy (`vaccStrategy`). It selects between three approaches: 'EPE' (clever exposure-prevention), 'uncapped' (unrestricted delivery), or a default simple schedule. Each strategy invokes a corresponding helper method to compute ... | def deliverByDrone(vaccStrategy, t, PODs, workingMinutes, droneVC, numDrones, params, mdP):
''' Depending on vaccine delivery strategy, delivers vaccines by drone using helper methods.'''
if vaccStrategy == 'EPE': #clever exposure-prevention delivery schedule
delivDetails = deliverVaccinesByDroneEPE... |
def _pack_packet(self) -> bytes:
"""Pack data into packet.
Returns:
bytes: the packed packet.
"""
# True/False telling whether the goal was scored
struct_fmt = "?"
data = list()
# Add Notification if the goal is scored and we are waiting for kickoff
... | This function manages a game simulation loop by updating the game state, emitting data, checking for goals, handling ball resets, and triggering start/finish events. It decreases the match time, processes events, and manages robot positions. If the match ends, it returns False; otherwise, it continues the loop, returns... | def tick(self) -> bool:
# On the very first tick, note that the match has started
if self.time == self.match_time:
self.eventer.event(
referee=self,
type=GameEvents.MATCH_START.value,
payload={
"score_yellow": self.score_yel... |
def crawl_data(limit=40):
"""
Main function to crawl data an
d map to segment_id
"""
global checked_time_list
if not check_times(checked_time_list):
return
with open('selected_points.json', 'r') as f:
cover_points = json.load(f)
weather, temp = crawl_current_weather(... | The main task of the code is to crawl job data using the `crawl_data()` function, log execution time and status, and handle API key exhaustion by retrying up to `MAX_RETRY` times. On IndexError (likely API key limit), it resets the API counter, increments retry attempts, and recursively retries. If retries exceed the l... | def crawl_job():
global api_call_counter
global retry
try:
start_time = time.time()
timestamp = crawl_data()
end_time = time.time()
log(f"[{dt.datetime.now()}] - {timestamp}.json - Run time: {end_time - start_time} (sec)\n")
# print(f"[{dt.datetime.now()}] - {timestamp}.json - {end_time - s... |
def create_board(self):
for y in range(0, self.size):
self.board.append([])
for x in range(0, self.size):
# walls on borders
if y == 0 or y == self.size - 1 or x == 0 or x == self.size - 1:
self.board[y].append(Cell(x, y, content["WALL... | The main task of the code is to initialize a new game level by creating a board, generating a maze, placing exits, initializing the player, identifying free movement locations, and positioning enemies. It sets up the game environment's structure, obstacles, and interactive elements for gameplay. | def new_level(self):
self.board = []
self.freeLocations = []
self.baseLocations = []
self.create_board()
self.create_maze()
self.place_exits()
self.init_player()
self.getFreeLocations()
print(self.freeLocations)
self.place_enemies() |
def remove_punct(str1, str2):
bad_chars = [';', ':', '-','!', "*",")","("]
for i in bad_chars :
str1 = str1.replace(i, ' ')
str2 = str2.replace(i, ' ')
a=stemsentence(str1).split()
b=stemsentence(str2).split()
intersection=set(a).intersection(set(b))
return intersection
def f... | The code calculates similarity between product names from Amazon and Google, computes distance metrics, and categorizes matches based on length and predefined dictionaries. It stores results in dictionaries like `baseid`, `le`, and `considered` for further analysis. | def diction(amazon, description_of_amazon ):
start=0
if description_of_amazon!="":
intersection_of_amazon=remove_punct(amazon,description_of_amazon)
for google_name in df2['name']:
a=findsim( google_name, amazon)
distance=len(findsim( google_name, amazon))/len(rp(amazon))
... |
def getBlockchain():
if not blockchainExists():
startBlockchain()
f = open(blockchainFile, "r")
line = f.readline()
output = []
while len(line) > 0:
output.append(makeBlock(line))
line = f.readline()
f.close()
return output
def checkTransactions(toTest):
balance =... | The function mines a new block by validating stored transactions, generating a valid block with a nonce, and broadcasting a "prepare" message to other clients. It waits for the current proposed block to be processed, updates the ballot number, and sends the block data to peers for consensus, ensuring transaction integr... | def mineAndSendBlock():
global otherClients
global storedTransactions
global ballotNum
global proposedBlock
while proposedBlock.depth != 0:
time.sleep(0.1)
prevHash = "firstBlock"
toAdd = Block(0, "", "", ["",""])
while True:
bc = getBlockchain()
if len(bc) > 0:
... |
def temperature(self): #form text for temperature (field 1)
temper = 't grad C: ' + self.extract_data(1)
self.lab.configure(text=temper)
def humidity(self): # field 2 Thingspeak
hum = 'Humidity: ' + self.extract_data(2)
self.lab.configure(text=hum)
def pressure(self): # field 3 Thingspe... | The main task of the code is to periodically update sensor data based on the `self.parameter` value. It checks if the parameter is 'temperature', 'humidity', or 'pressure' and calls the corresponding method. If not, it extracts time data. The function schedules itself to repeat every 10 minutes (600,000 ms) using `self... | def update_data(self):
if self.parameter == 'temperature':
self.temperature()
elif self.parameter == 'humidity':
self.humidity()
elif self.parameter == 'pressure':
self.pressure()
else:
self.extract_time()
self.lab.after(600000, se... |
def apply_rule(ruletype, ref_val, input_text):
output = []
if ruletype == "Matcher":
output = matcher(ref_val, input_text)
if output == []:
output = ["Not Found"]
return output
elif ruletype == "Regex":
output = regex(ref_val, input_text)
if output == []:
... | The main task of the code is to process a POST request by applying predefined rules from a JSON file to user input text. It retrieves database objects, filters rules based on selected class, executes rules with logical operations, generates results, stores them in the session, and redirects to a new URL. If errors occu... | def rule_exe(request):
global flag_redirect
supergroup = pSupergroup.objects.all().distinct("supergroup")
group = pGroup.objects.all().distinct("group")
module = pModule.objects.all().distinct("module")
pclass = pClass.objects.all().distinct("pclass")
assignedChar = CharDetails.objects.all().dis... |
def deal_card():
""""Picks a random card from the blackjack infinite deck and return its value."""
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
return random.choice(cards)
def print_table(player_cards, dealer_cards, dealer_covered):
""""Print the blackjack table to stdout."""
cls()
print... | This code simulates a Blackjack game between a player and dealer. It deals initial cards, lets the player choose additional cards, checks for blackjack or busts, and has the dealer draw until reaching 17. The winner is determined by comparing scores, with special handling for blackjack. The game prints the table state ... | def play_game():
winner = ""
blackjack = False
player_cards = []
player_cards.append(deal_card())
player_cards.append(deal_card())
dealer_cards = []
dealer_cards.append(deal_card())
dealer_cards.append(deal_card())
another_card = True
while another_card and winner == "... |
def matmul(tensor1: List[int] , tensor2: List[int]):
dim_tensor1 = len(tensor1)
dim_tensor2 = len(tensor2)
if dim_tensor1 == 1 and dim_tensor2 == 1:
return dot(tensor1, tensor2)
elif dim_tensor1 == 2 and dim_tensor2 == 1:
return mv(tensor1, tensor2)
elif dim_tensor1 == 1 and dim_tensor2 == 2:
retu... | This function performs a linear transformation by computing the matrix multiplication of the input tensor with the transposed weight tensor. If a bias is provided, it verifies that the bias can be broadcasted to match the output tensor's shape. The function returns the resulting tensor from the matrix multiplication, e... | def linear(input: List[int], weight: List[int], bias: Optional[List[int]]):
out = matmul(input, t(weight))
if bias is not None:
assert broadcast(bias, out) == out
return out |
def resolve_virtual_env(name) -> Path:
"""Given the name of a virtual environment, get its path.
Args:
The name of a virtual environment.
Returns:
The path to the virtual environment directory.
Raises:
ValueError: If the virtual environment name is not known.
RuntimeEr... | The main task of the code is to ensure a virtual environment with a specified name and version exists. It checks if the environment already exists, verifies its Python version matches the expected version, and creates or replaces it if necessary. If an existing environment has an incompatible version, it either raises ... | def ensure_virtual_env(name, expected_version=None, *, force=False, **kwargs) -> Optional[Path]:
"""Ensure a virtualenv with the given name and version exists.
Args:
name: The name of the environment to check for.
expected_version: An optional required version as a string. "3.8" will match "3.... |
def _merge_wastewater_to_cview_summary(
cview_summary_df, freyja_wastewater_df):
freyja_w_id_df = fpu.make_freyja_w_id_df(
freyja_wastewater_df, SEQ_POOL_COMP_ID)
temp_df = freyja_w_id_df.merge(
cview_summary_df, on=SEQ_POOL_COMP_ID, how="inner")
fpu.validate_length(temp_df, "freyj... | This function generates a structured dashboard report by merging wastewater (freyja_ww_df) and case data (cview_summary_df), processing date formats, assigning unique IDs, and exploding lineage results into individual entries using lineage mappings, labels, and date parameters. The output is a consolidated DataFrame fo... | def generate_dashboard_report_df(
cview_summary_df, freyja_ww_df, labels_df,
lineage_to_parent_dict, curated_lineages,
labels_date, freyja_run_date):
temp_df = _merge_wastewater_to_cview_summary(
cview_summary_df, freyja_ww_df)
temp_df[COLLECT_DATE_KEY] = temp_df[COLLECT_DATE_KE... |
def _extract_date_from_filename(fp_string):
file_path = pathlib.Path(fp_string)
run_date_regex = r".*(20\d{2}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}).*"
re_match = re.match(run_date_regex, file_path.stem)
run_date_str = re_match.group(1)
pieces = run_date_str.split("_")
time_str = pieces[1].replace("-",... | The code generates a dashboard report by processing Freyja input data, applying QC thresholds to filter results, reformatting lineage labels, and compiling key metrics into a CSV file. It extracts dates, loads input files, identifies failing results, and outputs a structured report with specified columns to the given o... | def generate_dashboard_report(arg_list):
freyja_input_dir = arg_list[1]
output_dir = arg_list[2]
labels_fp = fpu.get_labels_fp(freyja_input_dir)
labels_date = _extract_date_from_filename(labels_fp)
freyja_results_fp = fpu.get_freyja_results_fp(freyja_input_dir)
freyja_run_date = _extract_date_f... |
def WindMatrixself(xLoc,preVecLoc,boat): # Gives the wind shadow give boat
windRet = np.zeros((30,30))
windRet[xLoc[boat,0],xLoc[boat,1]] += 5
if preVecLoc[boat,0] < 0 and preVecLoc[boat,1] >= 0:
windRet[xLoc[boat,0]%30,xLoc[boat,1]-1] = 1
windRet[(xLoc[boat,0]+1)%30,xLoc[boat,1]-1] = 0.6
windRet[(xLoc[boat... | The code evaluates the next viable movement for a boat by checking valid positions based on distance, angular alignment with previous vectors, wind conditions, and collision constraints. It calculates potential new positions, assesses their legality (e.g., boundaries, illegal crossings), computes movement scores, and u... | def nextStep(boat, iObs, xObsLoc, preVecObsLoc, xNewLoc, preVecNewLoc, minVecLoc, createIndicator, infiniteloop, tmpMinSortLoc, sIndexLoc, sObsLoc, wind,tTmp): # evaluates next viable steps for a boat
minvalue = 10000000
windSelf = WindMatrixself(xObsLoc[:,:,iObs+1],preVecObsLoc[:,:,iObs+1],boat)
for k in range(size... |
def WindPollyaddself(xLoc, amountBoats, vNew, currentBoat, windBase):# wind shadow from given boats
windRet = np.zeros((yMesh,yMesh))
x1 = np.maximum(np.minimum(xLoc[currentBoat,1],1900),100)
x0 = np.maximum(np.minimum(xLoc[currentBoat,0],1900),100)
windRet[x1-100:x1+101, x0-100 : x0+101] += windBase[:,:,vNew[curre... | This function evaluates potential next steps for a boat by calculating movement costs (tmpmin) based on wind conditions, legal crossing of boundaries/buoys, and collision checks. It iterates through possible directions, adjusts positions, and selects the minimum valid step while updating speed, position, and indices fo... | def nextStep(fboutloc, j, xNew, vNew, v, windBase, T, s, x0, wind, Zpost, crossedStart, xtmp, vtmp, sIndexLoc, createIndicator, iObs, infiniteloop): # evaluating aviable steps
windself = WindPollyaddself(xNew, amountBoats, vNew, j, windBase)
minvalue = 1000
minimumk = 8
if (fboutloc[j] >= 1 and x0[j,0] < pastbuoy... |
def unit_vector(v1):
""" Returns the unit vector of the vector. """
return v1 / (np.linalg.norm(v1)+d)
def angle_between(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
>>> angle_between((1, 0, 0), (1, 0, 0))
0.0
>>> an... | This function determines the next optimal movement step for a boat by evaluating potential positions along a sorted trajectory list, adjusting for collision avoidance and directional constraints. It iterates through candidate positions, scales coordinates based on angle deviations from a reference vector, and selects t... | def nextStepSecond(boat, PositionNext, iObs, xObs, preVecObs, xNew, preVecNew, sIndexLoc, sIndextmpLoc, s, tmpMinSortLoc, T): # Finding second/third ... best step
sortMinVec = np.argsort(tmpMinSortLoc[boat,:,sIndexLoc])
index = 0
while sortMinVec[index] != minSortK[boat, sIndexLoc]:
index += 1
if PositionNext > ... |
def WindMatrix(xLoc,preVecLoc): # Gives the wind shadow for all boats
windRet = np.zeros((30,30))
for boat in range(amountBoats):
windRet[xLoc[boat,0],xLoc[boat,1]] += 5
if preVecLoc[boat,0] < 0 and preVecLoc[boat,1] >= 0:
windRet[xLoc[boat,0],xLoc[boat,1]-1] += 1
windRet[(xLoc[boat,0]+1)%30,xLoc[boat,1]-... | The function recursively explores all possible paths a boat can take through a grid with obstacles, avoiding collisions by simulating wind effects and updating positions. It checks for crashes, iterates over boat movements, and propagates valid paths using recursion, ensuring no infinite loops while adjusting obstacle ... | def recurrsion(crash, xObsLoc, preVecObsLoc, sIndex, xNewLoc, preVecNewLoc, boat, iObs, collidVecLoc, minVecLoc, tmpMinSortLoc, sObsLoc, tTmp): # recurrsion to find the paths the boat can take
if crash == 0 and iObs < Kobs: # make sure a crash hasn't happend
for i in range(Kn): # observation before finding next posi... |
def startPosition(x0Return,vNew,amountBoats,strat):# getting startingpositions
x0Return[:,0] = x0Return[:,0]*25+920-250
for i in range(amountBoats):
if x0Return[i,1] <= 19:
x0Return[i,1] = x0Return[i,1]*25+240
else:
x0Return[i,1] = 100 # if boat start in front of starting line, teleports and starts far behi... | The function simulates the movement of multiple boats considering wind effects and collision avoidance, determining the order in which they cross a buoy. It uses parallel processing to compute boat paths, checks for legal buoy crossings, and returns an array indicating the crossing order. The code also generates visual... | def orderBoats(Zpostloc, Tloc, finalPosition, sFinal, strat, colorVec, windBaseloc, vNew, sortPosition, evolutionStep, evolutionIndex): # one round, returning the order the boats crossed the buoy
amountthreads = constants.amountthreads
global windBase
global Zpost
global T
windBase = windBaseloc
Zpost = Zpostloc... |
def WindPollyadd(xLoc, amountBoats, vNew, windBase): # wind shadow from all boats
windRet = np.zeros((xMesh,yMesh))
for i in range(amountBoats):
x1 = np.maximum(np.minimum(xLoc[i,1],1900),100)
x0 = np.maximum(np.minimum(xLoc[i,0],1900),100)
windRet[x1-100:x1+101, x0-100 : x0+101] += windBase[:,:,vNew[i]%9].copy... | This function recursively computes all possible safe paths a boat can take through an environment with obstacles, updating positions and velocities while checking for collisions. It iterates through observation steps, applies wind effects, and uses recursive calls to explore next states, ensuring no collisions occur. T... | def recurrsion(crash, xObs, preVecObs, sIndex, xtmp, vtmp, boat, iObs, collidVecLoc, sObs, windBase, fboutloc, T, Zpost, crossedStart): # recurrsion to find paths the boat can take
if crash == 0 and iObs < Kobs: # make sure a crash hasn't happend
for i in range(Kn): # observation before finding next position
wind... |
def __generate_factor_base__(self):
c = 3.38
B = int(c * np.exp(0.5 * np.sqrt(np.log2(self.n) * np.log2(np.log2(self.n)))))
#B = 6
prime = [True for _ in range(B)]
p = 2
while (p * p < B):
if prime[p]:
for i in range(p * p, B, p):
... | The main task of the code is to solve a system of linear equations generated from a factor base, compute a value `x` using the solution and smooth factors, and return `x` modulo `n-1` as an integer. This likely belongs to an algorithm for integer factorization, such as the Quadratic Sieve or Pollard's Rho, where solvin... | def solve(self):
self.base = self.__generate_factor_base__()
sle = self.__generate_sle__()
print(sle)
solution = self.__solve_sle__(sle)
l, factors = self.__generate_smooth_ball__()
x = 0
for i in range(len(self.base)):
x += factors[i] * int(solu... |
def __generate_factor_base__(self, a):
L = sympy.exp((sympy.log(self.n) / sympy.log(sympy.log(self.n)))**0.5)**(a)
prime = [True] * (int(L)+ 1)
i = 2
while i < L:
if prime[i] == True:
for j in range(i**2, int(L) + 1, i):
prime[j] =... | This code implements the Brillhart-Morrison algorithm for integer factorization. It generates a factor base, computes continued fractions, identifies smooth numbers, solves linear equations over GF(2), and calculates potential factors x and y by exponentiating base primes. The algorithm aims to find nontrivial factors ... | def __brillhart_morrison__(self, a):
base = self.__generate_factor_base__(a)
cf = self.__generate_continued_fraction__(len(base)-1)
sn, s = self.__get_smooth_numbers__(base)
if s:
s = np.array(s)
if len(find_index_of_nonzero_array(s)) > 1:
s2 = s %... |
def __rho_pollard__(self):
x = self.f(2, self.n)
y = self.f(self.f(2, self.n), self.n)
orbit = [x]
while orbit.count(x) < 2:
x = self.f(x, self.n)
y = self.f(self.f(y, self.n), self.n)
if x == y:
return None
d = math.gcd((... | This code performs integer factorization using specified methods (rho-pollard, trial-division, brillhart-morrison) to find a non-trivial divisor of a number. It iterates through chosen algorithms, attempting to compute factors until a valid divisor is found or a patience limit is reached, returning the divisor or None ... | def factorize(self):
if self.method == "rho-pollard":
if self.f:
d = self.__rho_pollard__()
i = 1
while d == None:
d = self.__rho_pollard__()
i += 1
if i == self.patience:
... |
def load_map(map_dir):
dat_files_data = load_dat_files(map_dir)
if dat_files_data == None:
return None
song_filename, diffs = dat_files_data
if len(diffs) == 0:
return None
return load_audio(f"{map_dir}/{song_filename}"), diffs
def get_note_angle(direction, direction_to_an... | The main task of the code is to process a map file (likely from a rhythm game) by extracting audio and note data, then generating training examples with contextual segments. It maps note directions to angles, iterates through difficulty levels, and creates sliding windows of audio/notes. For each segment, it collects n... | def full_load_map(map_folder):
load_map_data = load_map(map_folder)
if load_map_data == None:
return []
(song_data, segment_duration), diffs = load_map_data
direction_to_angle = numba.typed.Dict.empty(
key_type=numba.types.int64,
value_type=numba.types.int64,
)
angle_to_d... |
def navigate_to_videos(self):
videos_url = f'{self.channel_url}/videos'
self.browser.get(videos_url)
self.accept_cookies()
# WebDriverWait(self.browser, 10).until(
# EC.presence_of_element_located((By.CSS_SELECTOR, ScraperConfig.MOST_POPULAR_VIDEOS_SELECTOR))
# )
... | The function `scrape_video_data` navigates to a YouTube channel's video section, loads all pages, extracts video URLs, and gathers metadata (title, description, etc.) for each video. It handles exceptions during navigation and attribute extraction, skipping failed attempts. The result is a list of scraped video data. Y... | def scrape_video_data(self):
print(self.channel_url)
try:
self.navigate_to_videos()
except:
return
self.load_all_pages()
print("Extracting video urls...")
video_urls = self.extract_video_urls()
scraped_videos = []
for url in vide... |
def __load_similarity_db__(self):
map__ensembl_id__similar_ensembls_ids = {}
if os.path.exists(self.protein_similarity_file_path):
with open(self.protein_similarity_file_path,'r') as fp:
map__ensembl_id__similar_ensembls_ids = json.load(fp)
else:
map__ensembl_id__sequence = self.__load_map__ensem... | The code's main task is to load a similarity database mapping Ensembl IDs to similar IDs, compute PIPE similarity scores using this data, and save validation files for analysis. This process likely supports gene/protein similarity evaluation in bioinformatics pipelines. | def run(self,):
map__ensembl_id__similar_ensembls_ids = self.__load_similarity_db__()
self.__compute_PIPE_similarity_score__(map__ensembl_id__similar_ensembls_ids)
self.__save_validation_files__() |
def qrs_conversion(self, qrs_complexes):
# Convert a list of data to a numpy array of one.
self.logger.debug('In qrs_conversion')
if isinstance(qrs_complexes, numpy.ndarray):
return qrs_complexes
elif isinstance(qrs_complexes[0], QRSData):
self.logger.debug('I got... | The code implements the G-means clustering algorithm to group input data (qrs_complexes) into clusters. It iteratively applies k-means, splits clusters using an Anderson-Darling test (controlled by alpha), and stops when reaching max_k clusters or no new splits occur. It returns centroids and a dictionary mapping data ... | def cluster_data(self, qrs_complexes, max_k=50, alpha=0.0001):
"""
The main method of the GMeans class. It is used to cluster data with the G-means algorithm.
:param qrs_complexes: numpy.array of input data
:param max_k: maximal number of classes; surpassing this number will cause the al... |
def get_channels_topics_statistics(channel_ids: List[str]):
"""
:param channel_ids: ids of channels
:return: a json of information
"""
return make_api_call(','.join(channel_ids), "topicDetails,statistics")
def extract_statistics_from_response(response: Dict) -> Tuple[float, float, float, float]:
... | The function `add_channel_topics_statistics` processes a list of channel IDs in batches of 10, fetching statistics and topics for each channel via an API. It aggregates results into a dictionary with channel IDs as keys, storing extracted data like views, subscribers, and topics. It also identifies and logs any channel... | def add_channel_topics_statistics(channel_ids: List[str]) -> Dict[str, List[str]]:
"""
:param channel_ids:
:return:
"""
res = dict()
batch = len(channel_ids) // 10
for i in range(batch+1):
print("i", i, "batch", batch)
try:
batch_channel_ids = channel_ids[i * 10: ... |
def __solve_ads_integer_linear_problem(self, news_allocation):
"""
Solve the advertising integer LP.
:param news_allocation: 1D list of a page allocation returned by the find_best_allocation method
:return: 1D list of Ads objects. It corresponds toan Ads allocation on the page.
"... | This function allocates ads to slots using specified techniques (LP/res_LP) and approaches (pdda/wpdda/greedy). It validates ad pool size, solves allocation problems, applies random selection logic for pdda/wpdda, removes allocated ads from the pool, assigns them to slots with weighted beta tracking, and records click/... | def find_ads_best_allocation(self, news_allocation):
if len(self.ads_pool) < self.ads_slots:
raise RuntimeError("The ads pool is empty or too few articles are present. Use the method fill_ads_pool "
"before advertising pages.")
if self.ads_allocation_techniqu... |
def sample_quality(self, content, user, interest_decay=False):
"""
Returns a sample from the proper weighted beta distribution
:param content: The news for which we want a sample describing the probability the user clicks it
:param user: The user itself, used to access its story with all... | The function allocates the best news articles to page slots using either a greedy approach (standard) or linear programming (LP), optimizing for user interest and category diversity. It updates beta distributions with allocation results if specified, ensuring variety by assigning proportional slot prominence to categor... | def find_best_allocation(self, user, interest_decay=False, continuity_relaxation=True,
update_assignment_matrices=True):
"""
For each news in the news pool set a news sample pulled from the corresponding beta distributions.
Allocates the best news by adopting either ... |
def find_best_allocation(self, user, interest_decay=False, continuity_relaxation=True,
update_assignment_matrices=True):
"""
For each news in the news pool set a news sample pulled from the corresponding beta distributions.
Allocates the best news by adopting either ... | The main task of the code is to simulate a user's interaction with a website by allocating the best pages (and ads) based on interest decay settings, tracking user clicks, updating beta distributions for learning, and recording performance metrics like click rates, time taken, and reward averages. It handles both news ... | def user_arrival(self, user, interest_decay=False):
"""
This method defines the procedure to be adopted when a simulated user interacts with the site (
and then with the learner).
First finds the best page allocation for that user, by using a fixed or corresponding beta distributions.
... |
def load_fusion_adapter_model(self, args):
"""Load fusion adapter model.
Args:
args ([type]): [description]
Returns:
[type]: [description]
"""
adapter_names_dict = self.search_adapters(args)
base_model = RelPrompt.from_pretrained(
arg... | This code initializes a RoBERTa-based model (baseline or CoLAKE) by loading a tokenizer, model parameters (if a model path is provided), and vocabulary structures. It sets up model configuration, device placement, and max sentence length based on input arguments, enabling tasks like masked language modeling. | def __init__(self, args):
# self.dict_file = "{}/{}".format(args.roberta_model_dir, args.roberta_vocab_name)
self.tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
if args.model_path is not None:
print("Testing CoLAKE...")
print('loading model parameters from {... |
def draw_raw_segments(self):
for p0, p1 in self.raw_segments:
(x0, y0), (x1, y1) = p0, p1
ray.draw_line_v((x0, y0), (x1, y1), ray.DARKGRAY)
def draw_segments(self, seg_color=ray.ORANGE):
segments_ids = self.engine.bsp_traverser.seg_ids_to_draw
#
# for seg_id in se... | The code's main task is to render graphical elements by drawing raw segments, processed segments, and the player, while incrementing a counter for animation timing or frame rate control. | def draw(self):
self.draw_raw_segments()
self.draw_segments()
self.draw_player()
self.counter += 0.0005 |
def view(newWindow, label, file):
# sets the title of the
# Toplevel widget
newWindow.title(label)
# sets the geometry of toplevel
newWindow.geometry("1000x600")
Label(newWindow,
text=label).pack()
df = pd.read_csv(file)
if label == "income_statement":
df['Total_Expens... | The code creates a new Toplevel window based on the provided 'functionality' parameter, dispatching to specific functions like view(), add(), or create_po() to handle employee, customer, vendor, payroll, or financial data operations. It dynamically loads the appropriate UI for tasks such as viewing records, adding entr... | def openNewWindow(master, functionality):
# Toplevel object which will
# be treated as a new window
newWindow = Toplevel(master)
if functionality == func.view_emp:
view(newWindow, "View Employees", EMPLOYEE_FILE)
elif functionality == func.add_emp:
add(newWindow, "Add Employee", EMP... |
def load_data(data_path: Path) -> pd.DataFrame:
return pd.read_parquet(data_path)
def get_window(option: str, n_tokens: int, start: str) -> np.ndarray:
if start == "450":
start_val = 450
end_val = 3850
elif start == "550":
start_val = 550
end_val = 3850
elif start == "800... | The code processes spectral data by applying specified augmentations (e.g., EMSA or multiplication), splitting data into training/validation/test sets using methods like K-fold cross-validation or scaffold-based splitting, and saving processed datasets. It prepares data for machine learning tasks by handling normalizat... | def main(
data_path: Path,
output_path: Path,
n_tokens: int,
window: str,
augmentation: str,
special: str,
start: str,
split: str,
mixtures: bool,
target: str
):
data = load_data(data_path)
# Deal with EMSA setup
if augmentation == 'emsa':
spectra = np.vstack... |
def install_resstock(main_folder):
repo_name = "resstock"
if not check_install(repo_name):
return None
else:
branch = get_branch_version("restructure-v3")
clone_repository("https://github.com/NREL/resstock.git", main_folder, branch = branch)
run_setup(main_folder, repo_name, ... | This script guides users to install NREL packages (ResStock, Buildstockbatch, OCHRE) and download weather files for the Nova Metrics workflow. It prompts for a directory path, validates input, and executes installation functions. Users must connect to NREL VPN for OCHRE. Additional tools like Docker and REopt are recom... | def main():
print(
"""
The Nova Metrics workflow uses sevearl NREL developed packages.
It can be difficult to correctly download and install all of these.
This is an installer helper to help get the metrics workflow set up on your computer.
To run the full Nova Metrics workflow you need to down... |
def read_pnml(fileobj: IO) -> nx.DiGraph:
"""Parse the given file."""
root = etree.parse(fileobj).getroot()
if root.tag != "pnml":
raise ValueError("Currently limited to parsing PNML files")
net = nx.DiGraph()
for place in root.findall("./net/place"):
net.add_node(
place... | The function `compute_trap_spaces` computes minimal trap spaces in a Petri net from an input file (PNML/BNET format). It parses the network, identifies places, and applies specified methods (SAT, CP, ILP, ASP) to derive solutions. Results are either displayed or yielded as a generator, with options for debugging, paral... | def compute_trap_spaces(
infile: IO,
display: bool = False,
max_output: int = 0,
time_limit: int = 0,
computation: str = "min",
method: str = "asp",
debug: bool = False,
nprocs: int = 1,
) -> Generator[List[str], None, None]:
"""Do the minimal trap-space computation on input file inf... |
def layer_matches(self):
""" Are we in the correct layer?"""
if not self.args.layer:
return True
for l in self.groups:
if l and l.find(self.args.layer) != -1:
return True
return False
def process_svg_path_data(self, id, d):
"""Breaks up the "d" attribute into individual command... | This code parses SVG elements by tracking tags, extracting attributes like 'viewbox' for SVGs, 'inkscape:label' for groups, and 'd' for paths. It checks layer matches, processes path data if valid, and exits on encountering transforms in paths. The main task is to parse SVG structure, validate layers, and handle path d... | def handle_starttag(self, tag, attrs):
self.tags.append(tag)
if tag == 'svg':
self.viewbox = SVGParser.find_attr(attrs, 'viewbox')
if tag == 'g':
label = SVGParser.find_attr(attrs, 'inkscape:label')
self.groups.append(label)
if label and self.layer_matches():
print("Reading l... |
def run(self, filename):
# run instructions from input file
instructions = self.translate(filename)
return self.execute(instructions)
def log(self, results):
# print results
for result in results:
print(result)
def format_result(self, results):
# modify the re... | The main task of the code is to initialize a tree using a specified file, execute a program with an input file provided as a command-line argument, process the results, and log the formatted output. The code first runs an initialization script, then processes the input file, stores the results, and logs them after form... | def main(self):
# initiating the tree
self.run('./initiation.txt')
# run program with input file
filename = sys.argv[1]
results = self.run(filename)
# log results
self.log(self.format_result(results)) |
def _heatmap(self, all_results, primary_regroup, secondary_regroup):
# FIXME: sort_by only currently applied to columns!
figure = plt.figure('heatmap', figsize=self.figsize)
ax = figure.add_subplot(1, 1, 1)
matrix, row_names, column_names = self._metric_matrix(all_results,
... | The function `_generate_figures` dynamically generates visualization outputs based on instance attributes. It yields a heatmap if `self.secondary` is 'heatmap', a single plot if `self.figures_by` is 'single', or iteratively yields multiple plots via `_generate_plots` otherwise. The method acts as a flexible generator, ... | def _generate_figures(self, *args):
if self.secondary == 'heatmap':
yield self._heatmap(*args)
elif self.figures_by == 'single':
yield self._single_plot(*args)
else:
for plot in self._generate_plots(*args):
yield plot |
def _load_data(self, more_measures):
# XXX: this needs a refactor/cleanup!!! Maybe just use more struct arrays rather than namedtuple
measures = self.measures + more_measures
if self.input_type == 'confidence':
"""
{'intervals': {'fscore': {90: (0.504, 0.602),
... | The code processes and visualizes results by sorting, filtering, and regrouping data based on parameters like `sort_by`, `best_in_group`, and `figures_by`. It loads data, validates parameters, filters for best systems, removes temporary measures, and generates plots. Results are either displayed interactively or saved,... | def __call__(self):
more_measures = []
if self.sort_by and self.sort_by not in ('score', 'name', 'none', 'measure') and self.sort_by not in self.measures + more_measures:
more_measures.append(self.sort_by)
if self.best_in_group not in (False, True) and self.best_in_group not in self.... |
def entropy(px):
p_valid = px[np.nonzero(px)]
p_valid = p_valid / np.sum(p_valid)
return -sum(p_valid * np.log2(p_valid))
def set_pair_key(father, son, ind_to_label):
return ind_to_label[son] + ':' + ind_to_label[father]
def margin_x(c22):
pxy = c22.astype(float) / np.sum(c22)
return pxy.sum(axi... | This function propagates marginal probability distributions through a tree structure, updating entropy (H), conditional entropy (marginal_H), and KL divergence (dkl) metrics. It starts from a root node, iterates through parent-child pairs, computes conditional probabilities, and updates child marginals while accumulati... | def update_marginals(sorted_tree_graph, c22_dict, root_ind,
ind_to_label, root_marginals):
visited, stack = set(), [root_ind]
new_marginals = dict()
new_marginals[root_ind] = root_marginals
H = entropy(np.array(root_marginals))
marginal_H = H
dkl = 0.0
while stack:
... |
def _distance_reward(self, lane_pos_threshold=-0.05, scale_factor=50):
# Baseline reward is a for each step
my_reward = 0
# Get current position and store it for the next step
pos = self.cur_pos
prev_pos = self.prev_pos
self.prev_pos = pos
if prev_pos is None:
... | The code converts an action (velocity, angle) into motor commands for a robot's wheels, calculates adjusted angular velocities, limits duty cycles, and executes the action via a simulator. It computes cumulative rewards for distance, velocity, proximity, and orientation, logs parameters, and returns observations, rewar... | def step(self, action):
vel, angle = action
# Distance between the wheels
baseline = self.unwrapped.wheel_dist
# assuming same motor constants k for both motors
k_r = self.k
k_l = self.k
# adjusting k by gain and trim
k_r_inv = (self.gain + self.trim) /... |
def get_last_fetched_content_created_at_utc():
if not os.path.exists(LOCAL_DB_FILE_NAME):
with open(LOCAL_DB_FILE_NAME, "w") as file:
pass
with open(LOCAL_DB_FILE_NAME, "r") as file:
try:
data = json.load(file)
return data
except Exception as e:
... | The main task of the code is to retrieve newly created submissions and comments by comparing their timestamps with the last fetched times. It fetches submissions and comments created after the previously recorded timestamps, ensuring incremental data retrieval without reprocessing older content. | def main():
data = get_last_fetched_content_created_at_utc()
last_fetched_submission_created_at_utc = data.get("submission", 0)
last_fetched_comment_created_at_utc = data.get("comment", 0)
fetch_submissions(last_fetched_submission_created_at_utc)
fetch_comments(last_fetched_comment_created_at_utc) |
def page_state(self, link, parent_link):
page_target_topics = self.processer.page_target_topics(link)
page_relevant = True if page_target_topics >= self.args.relevant else False
if page_relevant:
self.relevant.append((link, page_target_topics))
reward = self.args.reward_true ... | This code implements a reinforcement learning algorithm for web page exploration. It trains a model using Q-learning with epsilon-greedy exploration, prioritizing links based on calculated Q-values. The agent updates its weight vector (self.w) based on rewards from visited pages, constructs a directed graph (DG) of pag... | def train(self, args):
self.args = args
self.w = np.ones(5*(5+3)) * 0.01
self.B = []
self.visited = set()
self.relevant = []
self.DG = nx.DiGraph()
self.visited_pages = 0
for link in self.args.seeds:
_, state = self.page_state(link, None) # 5 ... |
def run_it(*args):
try:
p = subprocess.Popen(args, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
return [line.decode('utf-8') for line in p.stdout.readlines()]
except FileNotFoundError:
return None
def locate_vcvars_files():
drives = drive_letters()
vcvars_32 = []
vcvars_64 = []
... | The main task of the code is to configure a Windows build environment for a project (likely ansak-string) by parsing command-line arguments, validating paths for VC++ variables and tools, generating a `configvars.py` file with configuration values, and creating a `make.cmd` script to execute the build process. It ensur... | def main(argv=sys.argv):
global v
run_it('git', 'submodule', 'update', '--init')
parser = argparse.ArgumentParser(
description="Configure script for ansak-string on Windows")
parser.add_argument('--prefix',
help='non-default location to install files (does not '
... |
def is_end(self) -> bool:
return self.cursor >= len(self.expression)
def token(self) -> str:
return self.expression[self.cursor] if not self.is_end() else ""
def advance(self):
self.cursor += 1
while self.cursor < len(self.expression) and self.token().isspace():
self.cursor +... | This code parses a regular expression from a token stream, constructing ReX objects (like Concatenation, Union, Symbol, KleeneStar) by recursively handling grouped expressions, operators (|, ,), and Kleene stars (*). It advances through tokens, validates syntax, and returns the parsed ReX structure. | def __next__(self) -> ReX:
if self.is_end():
raise StopIteration
current_token = self.token()
result: ReX
if current_token == "(":
self.advance()
first_rex = self.__next__()
if self.is_end() or self.token() not in [",", "|"]:
... |
def get_kinematic_type(base_description):
type = get_type(base_description)
if type == "2WD" or type == "4WD" or "2T" in type:
return "skid_steering"
elif "1FAS" in type:
return "one_axle_steering"
elif "2AS" in type:
return "two_axle_steering"
elif "2FWS" in type:
re... | This function determines the kinematic type of a robot from its description and returns the corresponding command limits. It uses conditional checks to call specific helper functions for skid, omni, one/two-axle, two-wheel, or default four-wheel steering configurations, ensuring appropriate motion constraints are appli... | def get_command_limits(base_description):
kinematic_type = get_kinematic_type(base_description)
if kinematic_type == "skid_steering":
return get_skid_steering_command_limits(base_description)
elif kinematic_type == "omni_steering":
return get_omni_steering_command_limits(base_description)
... |
def continue_shooting(ai_settings, screen, ship, bullets):
if ai_settings.continue_shooting and len(bullets) < ai_settings.bullet_allowed:
new_bullet = Bullet(ai_settings, ship, screen)
bullets.add(new_bullet)
pygame.mixer.Channel(0).play(pygame.mixer.Sound('music/gun_shot.wav'))
def check_keydown_event(event, s... | The function `check_events` handles user input and game events, processing keyboard presses, mouse clicks, and quit signals. It manages shooting mechanics, updates game state, checks for play button clicks, and saves the highest score upon exiting, ensuring interactive control over the game's actions and transitions. | def check_events(ai_settings, screen, ship, bullets, play_button, stats, aliens, score_board, alien_bullets):
"""Respond to keypresses and mouse events"""
continue_shooting(ai_settings, screen, ship, bullets)
for event in pygame.event.get():
if event.type == pygame.QUIT:
with open("highest_score.txt", 'w') as h... |
def graph_loss(self, output, no_mass, fig, ax):
"""
Graph the mass loss as a power law.
"""
if no_mass == False:
# Shift mass loss and multiply by -1 so we can take log
loss_history = np.array([self.mass_history[i+1] - self.mass_history[i]
... | The code generates and saves plots of key metrics (mass loss, topples/length/area exponents, density) and their correlations to a specified directory. It creates subplots, checks/output directory existence, calls plotting methods, writes correlation data to a file, and returns calculated exponents and density. | def graph(self, output='results/output/', no_mass=False, no_grid=False):
'''
Save plots of the important figures and the correlation between them
to the 'output' directory.
This function assumes the 'output' directory exists; if it does not
an error will occur.
'''
... |
def get_statistics(self, field):
'''Return power law statistics of the passed field
Field should be one of area_history, length_history, etc. '''
# Start our analysis mid-way through evolution, to avoid pre-critical noise
start = self.get_start_index()
data = field[start:]
... | This function generates and saves power-law distribution plots for avalanche statistics (mass loss, topples, length, area) and mass density, using data from simulations. It creates log-log plots, saves them as PNGs in the specified output directory, and outputs a correlation matrix. The code assumes the output director... | def graph(self, output='output/', no_mass=False):
'''
Save plots of the important figures and the correlation between them
to the 'output' directory.
This function assumes the 'output' directory exists; if it does not
an error will occur.
Consider refactoring into separat... |
def get_boundary_by_frac(image, endpoint_bound_frac=0.05):
h, w = image.shape[:2]
endpoint_boundary = (h * endpoint_bound_frac, w * endpoint_bound_frac, h * (1-endpoint_bound_frac), w * (1-endpoint_bound_frac))
return endpoint_boundary
def adaptive_threshold_wrapper(image, maxValue, block_size, C, max_block... | The code segments a guidewire in an image by thresholding the red channel, applying morphological dilation, selecting connected components via thresholding (Otsu/manual), skeletonizing the mask, and pruning fragmented structures. It returns the final guidewire mask, detected endpoints, and intermediate processing metri... | def segment_guidewire(image: np.ndarray, connnected_components_thresholding='otsu', dialation_ksize=5, endpoint_bound_frac=0.05, skeleton_only=False, allow_fragmentation=False, ignore_fil_process=True):
endpoint_boundary = get_boundary_by_frac(image, endpoint_bound_frac)
intermediate_outputs = {}
image_r = ... |
def blankLine():
print("----------------------------------------------")
def containerLine():
cursor.execute("SELECT * FROM Containers")
containers = cursor.fetchall()
for i in containers:
print(f"Container Number : {i[0]} Number of Crates : {i[1]}")
def crateSheet():
flag = False
whi... | The main task of the code is to display a formatted "Current Inventory" layout by calling helper functions to print blank lines, container lines, and crate sheets, structuring the output with spacing and visual separation for inventory visualization. | def inventoryTicket():
blankLine()
print("Current Inventory")
blankLine()
containerLine()
blankLine()
crateSheet()
blankLine() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.