dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_exact_link(job = None, location = None):
if job == None:
url = 'https://www.indeed.com/jobs?q=software+engineer&l='
else:
url = 'https://www.indeed.com/jobs?q=' + filter_for_url(job)+'&l=' + filter_for_url(location)
return url
def get_soup(link):
#basic function to parse the soup... | The code scrapes job listings from Indeed based on a specified job title and location, extracts details like job title, company, location, link, and work type, and saves the data into a CSV file in the user's Downloads folder with a timestamped filename. | def run(job = "Software Engineer Intern", location = "Manhattan, New York"):
url = get_exact_link(job, location)
print("The website being parsed is : ", url, '\n')
page = get_soup(url)
pages = parse_all_pages(page)
soups = get_all_soups(pages)
df = pd.DataFrame()
for soup in soups:
... |
def promotion_dialog(self):
promotion_types = {
'Queen': chess.QUEEN,
'Rook': chess.ROOK,
'Bishop': chess.BISHOP,
'Knight': chess.KNIGHT
}
popup = tk.Toplevel(self.root)
popup.title("Choose piece for promotion")
for piece, type in p... | This code handles mouse clicks on a chessboard GUI to select and move pieces. It calculates the clicked square's position, checks if the piece belongs to the player, and either selects it or attempts to move it. If a pawn reaches the last rank, it triggers a promotion dialog; otherwise, it executes the move if legal. I... | def click_square(self, event):
col_size = row_size = 50
col = event.x // col_size
row = 7 - (event.y // row_size)
square = chess.square(col, row)
piece = self.board.piece_at(square)
if piece and piece.color == self.player_color:
self.selected_piece_square = sq... |
def calc_mean(filename, key):
"""Return the average value for given filename and key (column in csv file)"""
mean = 0
for item in items(filename):
mean +=float((item[key]))
mean = mean / count(filename)
return mean
def items(filename):
"""Return one line at a time as dictionary.
The... | This function calculates the standard deviation of a specified column in a CSV file. It computes the mean of the column, sums the squared differences between each value and the mean, divides by the total number of items, and returns the square root of this value, representing data dispersion. | def calc_stddev(filename, key):
"""Return the standard deviation value for given filename and key (column in csv file)
Standard deviation is the measure of dispersion of a set of data from its mean. ... Standard Deviation is also known as volatility. It gives a sense of how dispersed the data in a sample is fr... |
def calc_mean(filename, key):
"""Return the average value for given filename and key (column in csv file)"""
mean = 0
for item in items(filename):
mean +=float((item[key]))
mean = mean / count(filename)
return mean
def items(filename):
"""Return one line at a time as dictionary.
The... | The code calculates the variance of a specified column in a CSV file. It computes the mean of the column, sums the squared differences between each value and the mean, then divides by the total number of items to return the variance, which measures data dispersion around the mean. | def calc_variance(filename, key):
"""Return the variance for given filename and key (column in csv file)
Variance measures how far each number in the set is from the mean and thus from every other number in the set.
"""
variance = 0
mean = calc_mean(filename, key)
for item in items(filename):
... |
def count(filename):
"""Return the number of items in the given file."""
num_items = 0
for item in items(filename):
num_items += 1
return num_items
def calc_sum(filename, key):
"""
Return the sum for given filename and key (column in csv file)
"""
sum = 0
for item in items(fi... | The main task of the code is to analyze a text file's specified column by parsing command-line arguments, reading the data, and computing statistical metrics (count, sum, mean, variance, standard deviation, median) using helper functions. Results are printed to the console. | def main():
"""
Entry point if the module is started as designated program.
"""
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="Text file to be analyzed.")
parser.add_argument("key",
help="Name of the column that should be analyzed.")
args = p... |
def evaluate_fitness(self):
for ant in self.ants:
ant.calculate_cost()
def evaporate_pheromone(self):
self.G = self.G * (1-self.evaporation_rate)
def place_pheromone(self):
for ant in self.ants:
for i in range(self.n):
self.G[i][ant.path[i]] += ant.pheromone_delta
def best_ant(self):
return self.best_... | This code implements an Ant Colony Optimization (ACO) algorithm to find an optimal solution (path/assignment) with cost below a specified goal. It iteratively generates ants that construct solutions using pheromone trails, evaluates their fitness, updates pheromones through evaporation and deposition, and tracks the be... | def fit(self, M, goal, n_iterations):
self.M = M
self.n = len(self.M)
self.G = np.full((self.n, self.n), self.initial_pheromone)
best_ant = None
real_best_ant = None
for epoch in range(n_iterations):
self.ants = []
for _ in range(self.n_ants):
ant = Ant(self.M, self.G, self.alpha, self.beta)
s... |
def save_bottleneck_features(batch_size=128, epochs=50):
# load VGG16 model except for fully-connected layers
model = load_vgg16()
# get required data for training
train_data = get_data(train_data_dir, nb_train_samples)
print('train data reading done')
# get and save train bottleneck features
... | The main task of the code is to parse a test directory path from command-line arguments, save bottleneck features, train a top model, and fine-tune a model. It uses argparse to retrieve input parameters, processes test data, and executes a machine learning pipeline involving feature extraction, model training, and fine... | def main():
# parse arguments to get test directory
parser = argparse.ArgumentParser()
# gets filename from arguments
parser.add_argument("--test_dir", "-f", type=str, required=True)
# args will contain name of the test directory
args = parser.parse_args()
save_bottleneck_features()
tr... |
def load_data_from_file(fname):
with open(str(pathlib.Path(__file__).parent.absolute()) + "\\\\" + fname) as file:
content = file.read().split("\n")
return content
def extract_data(pdata):
data = list()
for y in pdata:
data.append([int(x) for x in y])
return data
def mark_basins(pdat... | The code processes a map file by loading, cleaning, marking basins, counting their sizes, and computing the product of the three largest basin sizes, then printing the result. | def part2():
data = load_data_from_file("map.txt")
clean = extract_data(data)
marked_map = mark_basins(clean)
sizes = count_basin_sizes(marked_map)
result = compute_product_of_3_largest(sizes)
print(result) |
def get_count(self, count: Optional[Union[str, int]] = None) -> Union[str, int]:
if count is None and self.persistent_count is not None:
count = self.persistent_count
if count is not None:
count = (
1
if (
(str(count) in pl_cou... | This function pluralizes adjectives with special rules, handling user-defined forms, known patterns, and possessives. It checks count=1 for no change, applies user-defined mappings, matches known special cases via regex, processes possessive forms by pluralizing the noun part, and returns False if no rules apply. | def _pl_special_adjective(
self, word: str, count: Optional[Union[str, int]] = None
) -> Union[str, bool]:
count = self.get_count(count)
if count == 1:
return word
# HANDLE USER-DEFINED ADJECTIVES
value = self.ud_match(word, self.pl_adj_user_defined)
if... |
def partition_word(self, text: str) -> Tuple[str, str, str]:
mo = PARTITION_WORD.search(text)
if mo:
return mo.group(1), mo.group(2), mo.group(3)
else:
return "", "", ""
def postprocess(self, orig: str, inflected) -> str:
inflected = str(inflected)
if "|" ... | The function generates the plural form of a given text, preserving original whitespace. If a count is provided, it returns the original text if the count is 1, 'a', 'an', etc., otherwise returns the plural. It uses helper methods to handle special cases for adjectives, verbs, and nouns, then combines processed parts wi... | def plural(self, text: str, count: Optional[Union[str, int]] = None) -> str:
"""
Return the plural of text.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start and end i... |
def partition_word(self, text: str) -> Tuple[str, str, str]:
mo = PARTITION_WORD.search(text)
if mo:
return mo.group(1), mo.group(2), mo.group(3)
else:
return "", "", ""
def postprocess(self, orig: str, inflected) -> str:
inflected = str(inflected)
if "|" ... | The function `plural_adj` pluralizes an adjective in the given text if the provided count is not a singular indicator (e.g., 1, a, an, etc.). It preserves original whitespace and returns the adjective unchanged when the count matches specific singular forms. Otherwise, it applies pluralization rules to the adjective wh... | def plural_adj(self, text: str, count: str = None) -> str:
"""
Return the plural of text, where text is an adjective.
If count supplied, then return text if count is one of:
1, a, an, one, each, every, this, that
otherwise return the plural.
Whitespace at the start... |
def next_pos_batch(self):
if self.start_batch + self.batch_size > len(self.triples["train"]):
ret_triples = self.triples["train"][self.start_batch : ]
self.start_batch = 0
else:
ret_triples = self.triples["train"][self.start_batch : self.start_batch + self.batch_size]... | The code generates training batches for a model, handling two formats: "pos_neg" returns positive and negative triple indices separated by head, relation, tail, while "triple_label" combines positive triples (with +1 label) and negatively sampled triples (with -1 label), shuffled for training. It retrieves positive tri... | def next_batch(self, format="pos_neg", neg_ratio=1):
if format == "pos_neg":
bp_triples = self.next_pos_batch()
bn_triples = self.generate_neg_triples(bp_triples)
ph_idx, pr_idx, pt_idx = self.shred_triples(bp_triples)
nh_idx, nr_idx, nt_idx = self.shred_triples(b... |
def render_json_by_version(outdir, packages, version):
"""Render json file for `version`
:param outdir: Path to the directory to use to store all universe objects
:type outdir: str
:param packages: package dictionary
:type packages: dict
:param version: DC/OS version
:type version: str
... | This function renders DC/OS universe packages based on the specified version. For versions <1.8, it notifies that zip-based files are deprecated. For versions ≥1.8, it generates JSON files, validates the repository, and creates a content-type file to define the universe version compatibility. The output is stored in th... | def render_universe_by_version(outdir, packages, version):
"""Render universe packages for `version`. Zip files for versions < 1.8
are no longer updated. Use json files for version >= 1.8
:param outdir: Path to the directory to use to store all universe objects
:type outdir: str
:param packages: pa... |
def generate_package_from_path(root, package_name, release_version):
"""Returns v3 package metadata for the specified package
:param root: path to the root of the repository
:type root: pathlib.Path
:param package_name: name of the package
:type package_name: str
:param release_version: package... | The main task of the code is to generate universe objects from a package repository by parsing command-line arguments, validating input/output paths, enumerating DCOS packages, and creating JSON files (e.g., `universe.json`, version-specific files) along with content-type files in the specified output directory. It pro... | def main():
parser = argparse.ArgumentParser(
description='This script generates all of the universe objects from '
'the universe repository. The files created in --out-dir are: '
'universe.json.')
parser.add_argument(
'--repository',
required=True,
type=pathlib.P... |
def verbose_log(self, *args) -> None:
"""print statements if you want a verbose run for debug"""
if self.verbose:
print(*args)
def first_init(self) -> None:
"""create config folder+file when none exist at first init"""
Path.mkdir(self.config_folder, parents=True, exist_ok=Tru... | This code initializes a project configuration by setting attributes from keyword arguments, checking if a config folder exists, creating it if not, validating the config file's integrity, and loading the configuration. It ensures proper setup and defaults if the config is invalid or missing. | def __init__(self, **kwargs):
super().__init__()
# get all kwargs passed to class constructor
self.project_name = kwargs['project_name']
self.project_id = kwargs.get('project_id', self.project_name)
self.project_version = kwargs.get('version', '0.0.1')
self.conf_name = k... |
def select_dice(score, opponent_score, dice_swapped):
"""Return the dice used for a turn, which may be re-rolled (Hog Wild) and/or
swapped for four-sided dice (Pork Chop).
DICE_SWAPPED is True if and only if four-sided dice are being used.
"""
# BEGIN PROBLEM 4
if dice_swapped:
dice = f... | This function simulates a turn-based game between two players using provided strategies. Each player rolls dice based on their strategy, with rules for dice swapping (Pork Chop) and score swapping (Swine Swap). The game continues until one player reaches the goal score, returning both players' final scores. | def play(strategy0, strategy1, score0=0, score1=0, goal=GOAL_SCORE):
"""Simulate a game and return the final scores of both players, with
Player 0's score first, and Player 1's score second.
A strategy is a function that takes two total scores as arguments
(the current player's score, and the opponent'... |
def check_cases():
for case in data_map.keys():
time_diff = datetime.datetime.now(timezone('Africa/Cairo')) - data_map[case][-1]['time']
if(int(time_diff.total_seconds()) >= 2):
print("found time diff")
Report(data_map[case])
def frame_decoder(base64_frame):
frame_bytes =... | The function processes a video frame by decoding it, analyzing it with a model, and storing the results in a data map indexed by camera ID. It appends the processed frame's result to a list associated with the camera ID and saves the updated data map to a file for persistent storage. | def handle_frame(frame_data):
check_cases()
image = frame_decoder(frame_data['frame'])
result = process_frame(image, Models, frame_data['camera_id'], socketio)
if(frame_data['camera_id'] not in data_map.keys()):
data_map[frame_data['camera_id']] = []
data_map[frame_data['camera_id']].append(... |
def loadModel(data_root, file_list, backbone_net, gpus='0,1,2,3', resume=None):
if backbone_net == 'MobileFace':
raise NotImplementedError
elif backbone_net == 'Res50':
net = ResNet(10575)
elif backbone_net == 'Res101':
net = NotImplementedError
else:
print(backbone_net,... | The code evaluates a ResNet50 model on the LFW dataset for a specified epoch by loading pre-trained weights, extracting features, and computing 10-fold cross-validation accuracies. It outputs individual fold accuracies and their average, using GPU resources and saving features to a .mat file for analysis. | def evaluationAPI(epoch):
print('Starting evaluation epoch %d ...'%epoch)
resume = '/data2/snapshot/epoch_%d_iteration_800.pth'%epoch
root = '/data2/datasets/lfw/lfw'
file_list = '/data2/datasets/lfw/pairs.txt'
backbone_net = 'Res50'
gpus = '0,1,2,3'
feature_save_path = '/data2/saved_feature... |
def getQuestionNum(txt):
"""
parses question number (integer part) and return integer as a string
"""
txt = txt.strip()
if (not txt) or len(txt) == 0:
return ""
if txt[-1] in [".", ",", ";", ":", ")", "-"]:
txt = txt[:-1]
return getQuestionNum(txt)
if txt[0] in ["."... | The main task of the code is to extract coordinates of questions from scanned pages by processing each page with OCR, identifying question numbers, and saving cropped images of each question based on detected coordinates. It resizes, blurs, and analyzes images to detect text boxes, validates question numbers, and saves... | def getCoords():
lastQuesNum = 0
for i in range(fromPg, toPg + 1):
img = cv2.imread(f"./raw_pages/page{i}.jpg")
# ? if you are changing these end correction crop values then also note to change marginImg below
img = img[config.border["top"] : config.border["bottom"], :].copy()
... |
def checkToOccupy(computer):
# Checks if a specified computer is occupied, and returns the placement number
if computer.occupied == True:
return True, computer.number
return False, computer.number
def occupyComputers(computerList, grouping, amount, mode):
# Sets the specified computers as "... | The function `findEqualSeatings` searches for a row in `computerList` containing exactly `amount` computers. It checks if all computers in such a row are available and, if so, marks them as occupied. If no full row is found, it delegates to `findAdjustedSeatings` for alternative arrangements. The task involves identify... | def findEqualSeatings(computerList, amount):
# To find a row with exactly the amount of computers requested
print("Looking for entire full computer rows...")
successfullyOccupied = False
for grouping in range(len(computerList)):
if successfullyOccupied:
continue
if len(compu... |
def getGVector(self): # generate the size for the G vector (paragraph 3.1 of the paper)
num = 0
for node in self.G.node:
num += self.G.node[node]['weight']
vector_gValue = []
val = math.pow((1 + self.epsilon/2),
math.fl... | This method employs dynamic programming (as described in paragraph 3.2) to determine the optimal partition of input trees based on cost constraints. It initializes a bin-packing structure, computes the best partition configuration using recursive cost evaluation, and converts the result into a set of elements for outpu... | def evaluatePartitionsMethod2(self,listTrees,listTotalCosts): # method that uses dynamic programming (paragraph 3.2 of the paper)
GVector = self.getGVector()
vectorG = np.zeros(len(GVector), dtype=int)
packer = Binpacker(round((1 + self.epsilon) * self.num / self.k))
gDic... |
def get_circuit(filename):
file1 = open(filename, 'r')
Lines = file1.readlines()
qubits=[]
gates=[]
qubits=re.findall('[0-9]+', Lines[0])
qubits=[int(s) for s in qubits]
for line in Lines[1:len(Lines)]:
if "QGate" in line:
gates.append(re.findall('[0-9]+', line))
if "QInit" in line:
val= re.findall("\... | The main task of the code is to process a quantum circuit from a file, convert it into a graph, partition the graph using KaHyPar, evaluate the partition's performance with the OE function, verify the solution, and output results including cost, memory usage, and partition details for a given circuit and parameters. | def main_func_OM(filename,i):
start_time=time.time()
qubits, gates= get_circuit('Inputs/'+filename)
print(filename)
MyData=Circuit_to_Graph(qubits, gates)
print("graph constructed")
print(qubits)
num=int(i)
print(num)
#epsilon=get_epsilon(filename, num, qubits)
epsilon=0.2
print(epsilon)
v_part=KaHyPar_part... |
def bilancedPartition(self, subTree, threshold, G):
if (subTree.data.number_of_nodes() <= 1): # if subtree is a leaf, return it
return subTree
else:
partition = kernighan_lin_bisection(subTree.data)
X = G.subgraph(partition[0]) # spotting the two sub-sets of divisio... | The code partitions a graph into balanced subgraphs using a dynamic programming approach. It generates a tree structure, prunes it to remove unnecessary nodes, calculates partition costs, and selects the optimal partition configuration using dynamic programming. The main task is to divide the graph into balanced partit... | def run(self):
#self.division(self.root, self.epsilon * self.num / (3 * self.k), self.G)
self.bilancedPartition(self.root, self.epsilon * self.num / (3 * self.k), self.G) # partition the graph and generate the tree
listTrees = self.pruneTree(self.root) # ... |
def get_monthly_data():
"""Check if all files in semantic location history directory are json files."""
year_dirs = []
for year in os.listdir(SEMANTIC_DIR):
year_dir = SEMANTIC_DIR / year
if len(year) == 4 and year_dir.is_dir():
year_dirs.append(year_dir)
monthly_data_dict =... | The main task of the code is to process monthly data files by parsing their contents into activity segments and saving these segments in a structured JSON format. It iterates through each month's data, loads the JSON records, extracts activity segments using `parse_monthly_data`, and stores them in a designated directo... | def main():
monthly_data_dict = get_monthly_data()
for key in monthly_data_dict:
print(f"Processing {key}...")
sample = monthly_data_dict[key]
sample = Path(sample)
with sample.open("r") as f:
records = json.load(f)
# print_dict_keys(records)
_, ac... |
def new_board(): ## Function to create a new game board ##
board = [
[None, None, None],
[None, None, None],
[None, None, None]
]
return board
def render(board): ## Function to render and display the game board ##
rows = []
for y... | This function plays a game between two players or a player and the AI on a board, taking alternating turns. It renders the board, accepts moves from players or AI, checks for a winner, and declares the result (win/draw) when the game concludes. | def play(player1_f, player2_f): ## Function to play the game between two players or a player and the AI ##
players = [ # Define the players as symbols ('X' and 'O') and their respective functions
('X', player1_f), ... |
def scroll_slow(self, scrollable_element, start=0, end=3600, step=100, reverse=False):
if reverse:
start, end = end, start
step = -step
for i in range(start, end, step):
self.browser.execute_script("arguments[0].scrollTo(0, {})".format(i), scrollable_element)
... | The main task of this code is to automate the job application process on a job board platform by locating and clicking the "Easy Apply" button, scrolling through job details, filling out application forms, handling modal dialogs, and verifying successful submission while managing exceptions and error states during the ... | def apply_to_job(self):
easy_apply_button = None
try:
easy_apply_button = self.browser.find_element(By.CLASS_NAME, 'jobs-apply-button')
except:
return False
try:
job_description_area = self.browser.find_element(By.CLASS_NAME, "jobs-search__job-detail... |
def scroll_slow(self, scrollable_element, start=0, end=3600, step=100, reverse=False):
if reverse:
start, end = end, start
step = -step
for i in range(start, end, step):
self.browser.execute_script("arguments[0].scrollTo(0, {})".format(i), scrollable_element)
... | This code automates job application by scraping job listings from a website, checking for availability, extracting job details (title, company, location), filtering out blacklisted keywords/companies, applying to eligible jobs, and logging results. It handles exceptions, scrolls pages, and writes data to files while av... | def apply_jobs(self, location):
no_jobs_text = ""
try:
no_jobs_element = self.browser.find_element(By.CLASS_NAME, 'jobs-search-two-pane__no-results-banner--expand')
no_jobs_text = no_jobs_element.text
except:
pass
if 'No matching jobs found' in no_jobs... |
def load_base_context(rootdir):
c = {}
if os.path.isfile(os.path.join(rootdir, 'templates/context.json')):
deep_update_context(c, _load_context_file(os.path.join(rootdir, 'templates/context.json')))
if _has_yaml and os.path.isfile(os.path.join(rootdir, 'templates/context.yaml')):
deep_update... | The function aggregates context data for Jinja templates by loading a base context from a specified directory, merging injected data, adding a Git hash if applicable, incorporating optional dictionaries, applying override contexts, and finally including settings context. It returns a combined dictionary for template re... | def load_all_context(conference, inject, dictionary=None):
if conference and conference.jinjaenabled and conference.jinjadir:
try:
c = load_base_context(conference.jinjadir)
except ValueError as e:
return HttpResponse("JSON parse failed: {0}".format(e), content_type="text/pla... |
def checkValid(self, direction):
# check if move is blocked by wall
newX, newY = self.potentialPosition(direction)
if newX == -1 or newX == self.width:
return False
if newY == -1 or newY == self.height:
return False
# check if move is blocked by snake body... | The code handles a snake's movement in a grid-based game. It checks if a move is valid, updates the board state, and calculates rewards. If the snake moves toward food, it extends the snake, updates the board, and increases the reward. Invalid moves trigger a game over. The function returns the updated game state, rewa... | def makeMove(self, direction):
gameOver = False
if self.checkValid(direction):
# set reward if moving in the right direction
if self.calcFoodDirection()[direction] == 1:
reward = 1
else:
reward = 0
(headX, headY) = self.snak... |
def make_dir(path):
try:
os.mkdir(path)
except FileExistsError:
pass
except OSError as err:
logger.error(f"An error has occurred: {err}")
raise
def get_device_dir(self, device_id, absPath=False):
p = os.path.join(self.get_profile_dir(), "AssetTracker_" + device_id)
... | This function saves provided data into a JSON file for a specific device. It creates the necessary directory structure using the device ID, generates the appropriate file path, and writes the data in formatted JSON format with an indent of 4 spaces for readability. | def save_device_json(self, device_id, data):
make_dir(self.get_device_dir(device_id))
with open(self.get_device_json_filepath(device_id), 'w') as outfile:
json.dump(data, outfile, indent=4) |
def show_frames(frames, title = 'Title'):
cv2.imshow(title, np.vstack(frames))
cv2.waitKey(0)
def map_keys_to_notes(notes, keys, first_note):
new_notes = notes.copy()
for i in range(keys.shape[0]):
current_note = first_note
octave = 0 if not (current_note == 'C' or current_note == 'C#') else 1
for j in range(... | The main task of the code is to convert piano key pixels in an image into musical notes by detecting black and white keys, mapping them to note names, filtering noise via count thresholds, and recentering octaves around Middle C. It processes grayscale images, isolates keys using thresholding and morphological operatio... | def pixels_to_notes(grey, trim_start, trim_end, first_white_note, first_black_note, animate = False):
# Map pixels -> black keys (do black first b/c easier to isolate than white keys)
_, black_keys = cv2.threshold(grey, 225, 255, cv2.THRESH_BINARY_INV)
## Fill in black keys
black_keys = cv2.erode(black_keys, np.one... |
def pixels_to_notes(grey, trim_start, trim_end, first_white_note, first_black_note, animate = False):
# Map pixels -> black keys (do black first b/c easier to isolate than white keys)
_, black_keys = cv2.threshold(grey, 225, 255, cv2.THRESH_BINARY_INV)
## Fill in black keys
black_keys = cv2.erode(black_keys, np.one... | The function converts a Synthesia video into a musical score by analyzing each frame's keyboard to detect pressed notes. It identifies left/right hand notes via color thresholds, maps pixel data to musical notes, and compiles results into lists for each hand. The process involves image cropping, edge detection, and dyn... | def synthesia_to_notes(fvs, first_white_note = 'A', first_black_note = 'A#', lh_bgr = [1, 0, 0], rh_bgr = [0, 1, 0], animate = False, logging = False):
#
# Converts Synthesia video that starts with keyboard showing to Song
#
NOTE_THRESHOLD = 0.6 # Percent of note's pixels that must be hit to "count"
lh_song, rh_so... |
def pixels_to_notes(grey, trim_start, trim_end, first_white_note, first_black_note):
# Map pixels -> black keys (do black first b/c easier to isolate than white keys)
_, black_keys = cv2.threshold(grey, 225, 255, cv2.THRESH_BINARY_INV)
## Fill in black keys
black_keys = cv2.erode(black_keys, np.ones((5,5), np.uint8... | This function processes video frames to detect and track piano notes being pressed. It crops frames to focus on the keyboard, identifies white/black keys, maps pixel data to musical notes, and logs/animates detected notes. The output is a list of notes hit at each frame, enabling analysis of played melodies from visual... | def synthesia_to_notes(fvs, template_img, first_white_note = 'A', first_black_note = 'A#', animate = False, logging = False):
#
# NOTE: This ignores "template_img" for now and assumes video starts with keyboard showing
#
NOTE_THRESHOLD = 0.8 # Percent of note's pixels that must be hit to "count"
song = [] # List o... |
def getCategoryIds(category):
""" returns a list containing the id of the category, or a list containing the ids of all subcategories.
Returns empty lists if no matching category. """
category = category.lower()
catMap = getCategories()
if category in catMap: # Supercategory
return [cat[... | The code fetches COCO dataset images for a specified category, processes each image to crop and resize objects matching the category, excluding small or overlapping bounding boxes. It saves individual cropped images to a destination folder with structured filenames, ensuring compliance with target dimensions and avoidi... | def fetchCategory(category, targetDims, destination):
catsToFetch = getCategoryIds(category)
if (catsToFetch == []):
print(f"No COCO images for {category}.")
return
images = getImages()
imageAnns = getImageAnnotations()
if not os.path.exists(destination):
os.makedirs(destin... |
def calculate_posterior_mean(
self, curr_images: torch.Tensor, curr_timesteps: torch.Tensor, noise: torch.Tensor
) -> torch.Tensor:
"""Calculates posterior mean for distribution that is used to sample x_{t - 1}
Args:
curr_images: Tensor of shape (b, c, h, w) representing noised ... | The code calculates the previous timestep images (x_{t-1}) from the current noised images (x_t) in a diffusion model. It computes the posterior mean and variance, adds scaled noise, and returns the predicted previous images. For t=0, it directly returns the current images. | def calculate_previous_timestep_images(
self, curr_images: torch.Tensor, curr_timesteps: torch.Tensor, noise: torch.Tensor
) -> torch.Tensor:
"""Calculates x_{t - 1} from x_{t}
Args:
curr_images: Tensor of shape (b,c,h,w) that represents noised images at current timesteps
... |
def score_board(board, cpu):
"""
Scores the current board state
:param board: The board that is to be scored
:param cpu: The cpu player
:return: The score of the current board state.
"""
score = 0
for row in range(len(board) - 1, -1, -1):
for column in range(7):
if (board[row][column] == 0):
continue... | This function simulates gameplay using the minimax algorithm to explore possible board states by recursively evaluating moves for the player and CPU. It updates a score array based on board favorability, limits search depth with a counter, and generates new board configurations by dropping pieces in valid columns. The ... | def minimax(board, player, counter, start_col, board_scores, cpu):
"""
Simulates gameplay between the player and the hard cpu in order to create possible board states.
:param board: The game board, 2D list of 6x7 dimensions.
:param player: The player dropping the piece, int.
:param counter: The depth of the sea... |
def create_board():
"""
Returns a 2D list of x rows and y columns to represent
the game board. Default cell value is 0.
:return: A 2D list of rowsXcolumns dimensions.
"""
return [[0 for i in range(game_parameters["columns"])] for j in range(game_parameters["rows"])]
def end_of_game(board):
"""
Checks if the ga... | The main task of the code is to run a game with multiple players and CPUs, managing turns, updating the game board, handling different CPU difficulty levels (easy, medium, hard), checking for win/tie conditions, and displaying the final result. It loops until the game ends, alternating between players/CPU and determini... | def start_game():
"""
Runs a game of any amount of players and/or CPUs.
:return: None
"""
board = create_board()
current_player = 1
while end_of_game(board) == 0:
clear_screen()
print_board(board)
if players[current_player - 1][0] == "easy":
cpu_player_easy(board, current_player)
elif players[curre... |
def score_board(board, cpu):
"""
Scores the current board state
:param board: The board that is to be scored
:param cpu: The cpu player
:return: The score of the current board state.
"""
score = 0
for row in range(game_parameters['rows'] - 1, -1, -1):
for column in range(game_parameters['columns']):
if (... | The main task of the code is to simulate gameplay between a player and a hard CPU using the minimax algorithm to explore possible board states. It evaluates move favorability by recursively generating board copies, updating scores based on the game's outcome, and prioritizing the CPU's optimal moves. The function updat... | def minimax(board, player, counter, start_col, board_scores, cpu):
"""
Simulates gameplay between the player and the hard cpu in order to create possible board states.
:param board: The game board, 2D list of 6x7 dimensions.
:param player: The player dropping the piece, int.
:param counter: The depth of the sea... |
def drop_piece_cpu(board, player, column):
"""
Drops a piece into the game board in the given column.
Please note that this function expects the column index
to start at 1.
:param board: The game board, 2D list of 6x7 dimensions.
:param player: The player dropping the piece, int.
:param column: The index of col... | The function determines the CPU's optimal move on hard difficulty using the minimax algorithm. It simulates all possible moves by creating board copies, evaluates each via recursive minimax with depth 3, and selects the column with the highest score to drop the player's piece, prioritizing winning strategies while coun... | def cpu_player_hard(board, player):
"""
Executes a move for the CPU on hard difficulty.
This function creates a copy of the board to simulate moves.
This uses the minimax algorithm.
It looks for possible moves of the other player and tries to find the best possible response
:param board: The game board, 2D ... |
def drop_piece_cpu(board, player, column):
"""
Drops a piece into the game board in the given column.
Please note that this function expects the column index
to start at 1.
:param board: The game board, 2D list of 6x7 dimensions.
:param player: The player dropping the piece, int.
:param column: The index of col... | The function `cpu_player_hard` implements a hard-difficulty AI for a game (likely Connect Four) using the **minimax algorithm**. It simulates all valid moves by copying the board, evaluates potential outcomes recursively, and selects the column with the highest score to drop a piece. The minimax algorithm predicts oppo... | def cpu_player_hard(board, player):
"""
Executes a move for the CPU on hard difficulty.
This function creates a copy of the board to simulate moves.
Minimax algorithm
It looks for possible moves of the other players and tries to find the best possible response
:param board: The game board, 2D list of 6x7 d... |
def create_board():
"""
Returns a 2D list of 6 rows and 7 columns to represent
the game board. Default cell value is 0.
:return: A 2D list of 6x7 dimensions.
"""
board = [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0... | The code runs a Connect 4 game where a player competes against a CPU. It initializes the board, lets the player choose difficulty, alternates turns between the player and CPU (with difficulty-based strategies), checks for game endings, and prints results like victory or tie. | def game_against_cpu():
"""
Runs a game of Connect 4 against the computer.
:return: None
"""
board = create_board()
level_of_difficulty = validate_input("Choose your difficulty (easy, medium, hard): ", ["easy", "medium", "hard"])
while end_of_game(board) == 0:
print_board(board)
execute_player_turn(1, boar... |
def validate_input(prompt, valid_inputs):
"""
Repeatedly ask user for input until they enter an input
within a set valid of options.
:param prompt: The prompt to display to the user, string.
:param valid_inputs: The range of values to accept, list
:return: The user's input, string.
"""
input_option = input(pro... | The main task of the code is to present a Connect 4 game menu, allowing users to view rules, play local 2-player mode, challenge the computer, or exit. It uses input validation to handle selections and routes users to corresponding functions (print_rules, local_2_player_game, game_against_cpu) until they choose to exit... | def main():
"""
Defines the main application loop.
User chooses a type of game to play or to exit.
:return: None
"""
print("=============== Main Menu ===============")
print("Welcome to Connect 4!")
print("1. View Rules")
print("2. Play a local 2 player game")
print("3. Play a game against the computer")
... |
def __getConnected__(self):
global CONNECTED
self.cout.printg(f"=== Connected users ===")
for i in list(CONNECTED.keys()):
self.cout.printy('[+]',end=' ')
self.cout.printg(f"{i:>2}")
print()
def __isHost__(self,host):
global CONNECTED
return host i... | This function processes commands for remote control operations, including AI translation, host management, data retrieval (passwords, cookies, WiFi), file transfer, and connection handling. It uses AES encryption, checks command validity, and returns processed results or specific byte sequences for different tasks. | def filterCommand(self,command,conn,addr,aes):
global AIAPI,CONNECTED,CONNECT
out = False
try: out = command.split('--out')[1].strip()
except: pass
if command.startswith('/AI'):
if not AIAPI:
AIAPI = "bxhfviemh3b9piofzmggwz85ns4np1yk"#self.cout.scan('P... |
def __genFirstAesHost__(self,key,conn):
iv = md5(key).digest()
aes = AESencryption(key,iv)
host = self.__sendCommand__('hostname',conn,aes).strip()
return self.__roundsIV__(aes),host
def __getSymmetricKey__(self,conn):
msg = os.urandom(32)
self.sendMsg(conn,msg)
... | This code establishes a reverse shell connection using AES encryption, allowing remote command execution and data exfiltration. It generates symmetric keys, filters commands, and handles encryption rounds. The loop processes commands from the client, with specific byte sequences triggering AES reinitialization or comma... | def getShell(self,conn,addr):
global CONNECT ,CONNECTED
self.cout.printy(f"Connecting to ",end=''), self.cout.printg(addr[0])
aes, hostname = self.__genFirstAesHost__(self.__getSymmetricKey__(conn),conn=conn)
self.cout.getTools(['Reverse Shell','Keylogger','Encypt session','steal passwor... |
def _check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
def _raining(self):
self._check_if_group_empty()
self._keep_on_raining()
def _update_screen(self):
self.screen.fill(pygame.Color(0,255,0))
self.raindrops.... | The code defines a `run` method that continuously loops, performing three tasks: checking for events, updating the location (likely simulating rain movement), and refreshing the screen. Its main task is to maintain an interactive loop for real-time updates, such as animating rain effects and responding to events in a g... | def run(self):
while True:
self._check_event()
self._raining() # update new location
self._update_screen() |
def _check_all_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_KEYDOWN_events(event)
elif event.type == pygame.KEYUP:
self._check_KEYUP_event... | The code defines a `run` method that continuously loops, checking for events, updating elements, and redrawing the screen in an infinite cycle, likely for real-time applications like games or GUI interfaces. | def run(self):
while True:
self._check_all_events()
self._update_all_elements()
self._draw_screen() |
def _check_event(self):
# Watch for keyboard and mouse events.
# set_allowed to avoid checking on other events
pygame.event.set_allowed([pygame.QUIT, pygame.KEYUP, pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN])
for event in pygame.event.get(): # returns a list of events that have taken place ... | The code runs the main game loop, handling events and updating the game state. When active, it updates game elements and hides buttons; when inactive, it resets the screen, spawns new aliens, repositions the ship, and displays buttons. The loop continuously renders the screen until the game quits. | def run_game(self):
'''Start the main loop for the game'''
while 1: # to constantly run the game till quit -> NOTE: 1 is faster than True
self._check_event()
if self.stats.game_active:
# remove button
self.button.show_button = False
... |
def _create_root_node(self):
"""
Construct root node
"""
self.root = _Node()
self.root.depth = 0
self.root.idx = 0
self.root.parent = self.root
self.root._slink = self.root
def _build_McCreight(self, T):
"""
Builds a Suffix tree using McCre... | This code initializes a suffix tree by creating a root node, appending a terminating symbol to the input string, and constructing the tree using either the McCreight or brute-force algorithm based on the method parameter. It defaults to McCreight if an unrecognized method is provided. | def __init__(self, string, method='McCreight'):
self._create_root_node()
# Add terminating symbol (required by McCreight algorithm)
string += '$'
self.word = string
# Build suffix tree
if method == 'McCreight':
self._build_McCreight(string)
elif met... |
def get_category(self, entity):
if entity:
for entity_class in entity.INDIRECT_is_a: # get main class of the entity
if entity_class.name == "Component" or entity_class.name == "Value" or entity_class.name == "Goal" or entity_class.name == "Capability":
break
... | The function `find_adaption` identifies alternative entities for a given input by searching the ontology, checking same-category morphisms, and deducing cross-category alternatives if needed. If no alternatives exist, it logs a warning and returns `None`. Valid alternatives trigger change propagation via `propagate_tpm... | def find_adaption(self, entity_name):
entity = self.onto.search_one(iri="*{}".format(entity_name))
cat = self.get_category(entity)
functors = self.get_functors(entity, cat)
obj_alternative = self.get_alternative_from_morphisms(functors, entity, cat) # search altenative in same c... |
def show(inp):
inp = np.floor(inp / 256.0 * 10)
for i in range(14):
for j in range(28):
print(end=f'\033[48:5:{232 + int(inp[i*2, j]) * 2}m') # ]
print(end=f'\033[38:5:{232 + int(inp[i*2+1, j]) * 2}m') # ]
print(end='▄')
print(end='\033[0m') # ]
... | The code trains a neural network on the MNIST dataset using backpropagation. It reshapes and normalizes input images, one-hot encodes labels, and iteratively updates weights through 50 training steps. After each step, it prints weight percentiles and evaluates test error using a separate `test_emnist()` function. The g... | def train_emnist():
global nyu
import mnist
input, output = mnist.train_images(), mnist.train_labels()
for i in range(10):
show(input[i])
x = input.reshape((input.shape[0], 28*28)) / 255.0
y = np.zeros((output.shape[0], 10), dtype=float)
for i in range(len(output)):
y[i][o... |
def load():
try:
with open('nn.npy', 'rb') as f:
for i in range(len(w)):
w[i] = np.load(f)
b[i] = np.load(f)
except FileNotFoundError:
pass
except Exception:
import sys
print("Couldn't load nn.npy")
sys.exit(1)
def train_emn... | The main task of the code is to load resources, attempt to train a model on the EMNIST dataset, and ensure results are saved regardless of training success. The `load()` function initializes necessary components, `train_emnist()` executes the training process, and `save()` persists outcomes, guaranteed by the `finally`... | def main():
load()
try:
train_emnist()
finally:
save() |
def gravity_update(self):
self.settings.Blue_jump_speed -= self.settings.gravity
self.settings.Gold_jump_speed -= self.settings.gravity
def _check_events(self):
"""respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
... | The main task of the code is to start and manage the game loop, handling gravity updates, collision checks, player input, timer logic, and screen rendering. It continuously updates game elements (blue and gold entities), processes events, applies physics, and maintains the game state using Pygame, ensuring real-time in... | def run_game(self):
"""Start the main loop for the game."""
pygame.mixer.music.play(loops=0, start=0.0, fade_ms=0)
while True:
self.current_time = pygame.time.get_ticks()
self.blue.current_time = self.current_time
self.gold.current_time = self.current_time
... |
def get_total_papers(self, query, params):
encoded_query_params = urllib.parse.urlencode(params)
request_url = f'{self.base_uri}?{encoded_query_params}'
tree = self.send_request(request_url)
if tree.xpath(self.total_papers_xpath):
return int(tree.xpath(self.total_papers_xpath)[0].text.replace(' ',... | This code retrieves a specified number of papers based on a query by paginating through results, adjusting parameters for each page, and optionally formatting the output. It uses progress tracking if enabled and stops once the desired result size is reached. | def query(self, query, params={'from': 0, 'page': 1}, result_size=5000, format=None, progress=False):
total_papers = []
params = {'q': query, **params}
total = self.get_total_papers(query, params)
if not total:
return None
if progress:
pages = tqdm(range(1, total + 1, self.page_size))
... |
def get_weather(w1, w2, w3):
try:
# GET THE CURRENT WEATHER IN AMSTERDAM:
r = re.get('http://api.weatherapi.com/v1/current.json?key=16a275e088724a3eba1143500221201&q=Amsterdam&aqi=no')
weather = r.json()
icon = "http:" + str(weather['current']['condition']['icon'])
# st.write... | The code creates a Streamlit app with interactive buttons to switch between map and plot views for predicting overcrowded moments at locations. It displays weather data, overcrowdedness percentiles, and dynamically renders either map or plot predictions based on user selection, using global state to track the active vi... | def app():
with st.container():
# st.title('Homepage')
col_title, w1, w2, w3 = st.columns([0.8, 0.15, 0.15, 0.15])
get_weather(w1, w2, w3)
st.markdown("---")
col_map, col_plot, col_empty = st.columns([0.1, 0.1, 0.8])
global display
if col_map.button("📍 Map... |
def process_text(self, msg: str):
"""Process a string, adding all links"""
# Extract each sentence
sentences = [s.strip() for s in re.split(r'[.!?]', msg) if len(s.strip()) > 0]
# Extract each word, inserting the sentence start and end flags
# Convert sentence to lowercase to avo... | This code processes a text string by extracting n-grams based on the specified order. It splits the input into lowercase words, maintains a rolling window of previous words (n-grams), and updates the model with transitions from the history to the current word. When `self.order == -1`, it uses an alternative processing ... | def process_text_ngram(self, msg:str):
"""Process a string using ngrams"""
if self.order == -1:
self.process_text(msg)
return
# Extract each word
words = [w for w in re.split(r'[,\s]', msg.lower()) if len(w) > 0]
# Initialize rolling ngram
... |
def get_dev_and_ports_from_packets(src_ip, src_port, dst_ip, dst_port, flows):
direction = True
if f"{src_ip}-{dst_ip}" in flows:
dev = f"{src_ip}-{dst_ip}"
if f"{src_port}-{dst_port}" in flows[dev]:
ports = f"{src_port}-{dst_port}"
elif f"{dst_port}-{src_port}" in flows[dev]... | This code processes a pcap file to extract network flows, grouping packets by source/destination IPs and ports. It tracks active/inactive flows using timeouts, computes metrics for each flow, and exports extended flow records to a CSV file. The function returns counts of exported flows and parsed packets. | def timeseries_plugin(arg):
cnt_flows = 0
cnt_packets = 0
with open(arg.flows, "w") as w:
writer = csv.writer(w)
print("Write header:", end=" ")
writer.writerow(HEADER)
print("Done")
print("Creating extended flows from packets:")
print(
f"\r N... |
def get_dev_and_ports_from_packets(src_ip, src_port, dst_ip, dst_port, flows):
direction = True
if f"{src_ip}-{dst_ip}" in flows:
dev = f"{src_ip}-{dst_ip}"
if f"{src_port}-{dst_port}" in flows[dev]:
ports = f"{src_port}-{dst_port}"
elif f"{dst_port}-{src_port}" in flows[dev]... | The code processes a CSV file of network packets to generate extended flow records, grouping packets by device and port pairs. It calculates metrics like packet/byte counts, direction ratios, and exports these flows to a new CSV file. The function returns the number of exported flows and parsed packets. | def timeseries_plugin_csv(arg):
cnt_flows = 0
cnt_packets = 0
with open(arg.flows, "w") as w:
writer = csv.writer(w)
print("Write header:", end=" ")
writer.writerow(HEADER)
print("Done")
print("Creating extended flows from packets:")
print(
f"\r ... |
def parse_arguments():
"""Parse program arguments using the argparse module.
Returns:
Namespace: Parsed arguments.
"""
parser = argparse.ArgumentParser(
description="""Module for add information about Network Dependency for each flow. Supported inputs of flows are NEMEA IFC, flow CSV fi... | The main task of the code is to process input files (pcap, CSV, or time-series CSV) to generate time-series data, selecting the appropriate processing function based on input type. It measures and reports the time taken, flow/packet processing rates, and outputs performance metrics like seconds per flow/packet and thro... | def main():
"""Main function of the module."""
arg = parse_arguments()
print("Loadind pcap:", end=" ")
tic = time.perf_counter()
print("Open write file")
if arg.pcap != "":
if arg.file != "":
cnt_flows, cnt_packets = save_timeseries(arg)
else:
cnt_flows,... |
def getSensorBeaconCoordFromLine(line):
line = line.strip().split(':')
sensor = line[0]
sensor = sensor.split(',')
sensor = ( int(sensor[0].split('=')[1]) , int(sensor[1].split('=')[1]) )
beacon = line[1]
beacon = beacon.split(',')
beacon = ( int(beacon[0].split('=')[1]) , int(beacon[1].sp... | The code processes a file to determine either the number of positions in a specific row that cannot contain a beacon (part 'one') or to find a coordinate not covered by any sensor's range and compute a tuning frequency (part 'two'). It reads sensor and beacon coordinates, calculates excluded positions for part 'one', a... | def processFile(part):
setPositionsCannotExist = set()
# List of beacon at the searched row
beaconsSearchedRow = []
# Variable for the second part, dict of sensors coordinate and its manhattan distance
dictManhattanDistanceSensors = {}
# Build the cave map
with open(filePath, 'r') as f:
... |
def draw_lines(self):
# Fill background
self.display.fill(self.colors['dark_bg'], pg.Rect(0, 0, self.width, self.height))
box_size = (120, 120)
coordinates = [i for i in product([10, 250], [250, 10])]
# Fill light boxes
for x, y in coordinates:
self.display.fi... | The code initializes a Pygame window, sets up a display surface, draws grid lines, displays a start menu, and creates UI buttons for grid settings and speed controls to prepare the game environment for user interaction. | def initialize(self):
pg.init()
self.display = pg.display.set_mode(size=(self.width, self.height))
self.draw_lines()
self.start_menu()
self.create_grid_buttons()
self.create_speed_buttons() |
def maze_solved(self, clear=False):
position = (408, 275)
rect = pg.Rect(*position, 150, 25)
if clear:
self.update(position, rect=rect)
return
self.draw_font('Solved!', rect=rect)
def draw_font(self, string, position=None, size=25, color=None,
bo... | The code renders a puzzle grid by iterating through each cell. It clears a 'Solved!' message, then draws numbers in non-zero cells using bold text and updates empty cells. Coordinates are spaced to position elements correctly, creating a visual representation of the puzzle grid. | def draw_puzzle(self, puzzle):
# Clear 'Solved!' message
self.maze_solved(True)
y = self.coord_start
for row in puzzle:
x = self.coord_start
for num in row:
if num:
self.draw_font(str(num), (x, y), color=self.colors['text_bright... |
def _message_count(self) -> int:
"""Calculate the total number of messages sent."""
messages = 0
for k, v in nx.get_edge_attributes(self.graph, "messages").items():
for _, z in v.items():
if z is not None:
messages += 1
return messages
de... | The code propagates beliefs across a graph by iteratively sending messages between nodes. It continues until twice the number of edges have been processed, checking each edge to determine if a message can be sent in either direction and executing it if possible. This process updates beliefs dynamically through the netw... | def propagate(self) -> None:
"""Propagate belief across the tree."""
while self._message_count() < (2.0 * len(self.graph.edges)):
for (source, target) in self.graph.edges.keys():
if self._can_send(source, target):
self._send_message(source, target)
... |
def get_ood_scores_single(image, model):
image = image.unsqueeze(0)
with torch.no_grad():
image = image.to(device)
output = model(image)
score = -to_np((1 * torch.logsumexp(output / 1, dim=1)))
return output, score[0]
def reliability(p_list):
N = len(p_list)
max_index = np.ar... | The main task of the code is to poison a subset of input images by modifying their predicted probabilities based on a specified ratio and attack method. It classifies images into in-distribution (ID) and out-of-distribution (OOD) categories using OOD scores, applies poisoning to a portion of ID samples via a trigger fu... | def poison_fun_tensor(args,model, image_tensor, transform_test,
attack, ratio, dataset, trigger_path, poison_way, poison=True):
# image_tensor is the input image list or tensor
# trigger number = close_set_num * ratio
# poison decide whether the input was poisoned
if poison == Fal... |
def normalise_weights(weights):
"""Normalise weights to sum to one.
Args:
weights (List[float]): A list of weights over the objectives.
Returns:
ndarray: An array of weights summing to one.
"""
normalised_weights = np.array(weights) / sum(weights)
... | This code initializes a navigation system with a 2D grid, risk assessment, and hardware control. It sets up grid graphs, risk/conditional risk values, serial communication for movement, and path planning. The class tracks state, interventions, and logs world states for decision-making in dynamic environments. | def __init__(self, width, height, weights, start=(0, 0), prior_risk=0.1, prior_conditional_risk=0.5,
empirical_threshold=10, field=None):
self.field = field
self.width = width
self.height = height
self.weights = self.normalise_weights(weights)
self.state = start
... |
def log_world_state(self):
"""Log the world state for visualisation by the dashboard."""
world_dict = defaultdict(list)
for vertex in self.graph.nodes:
world_dict['X'].append(vertex[0])
world_dict['Y'].append(vertex[1])
world_dict['Unvisited'].append(max(0.1,... | The code executes a monitoring plan by iteratively processing each step. It logs the current state, determines movement directions between states, and uses a command driver to execute actions. If successful, it updates the system state, model, and risk probabilities; otherwise, it aborts. The loop continues until the p... | def execute_plan(self):
"""Execute the current monitoring plan."""
while self.plan:
self.log_world_state()
next_state = self.plan.pop(0)
if self.plan:
next_next_state = self.plan[0]
else:
self.next_plan = self.get_plan(next_... |
def decode_command(self, byte_command):
"""Decode an incoming command from CropBot.
Args:
byte_command (bytes): The CropBot command as a bytestring.
Returns:
str: The direction to drive into.
"""
command = byte_command.decode('utf-8').strip('\n')
... | The code executes a command from CropBot by decoding it into movement directions, attempting to move the robot, detecting the observed color, and returning a byte-encoded response indicating movement success and the detected color. | def execute_command(self, command):
"""Execute an incoming command.
Args:
command (bytes): A command from CropBot.
Returns:
bytes: A response with the driving success and observed color.
"""
direction, next_direction = self.decode_command(command)
... |
def read_weights(self):
"""Read new weights from a file.
Raises:
FileNotFoundError: When the file does not exist.
"""
try:
with open('weights.json') as f:
weights_dict = json.load(f)
self.weights = self.normalise_weights(weights_dict['... | The code continuously monitors the environment by repeatedly reading weights, updating edge weights, executing a plan, and updating the plan. The loop continues as long as `execute_plan()` returns `True`, ensuring ongoing environmental monitoring and adaptive plan adjustments. | def monitor(self):
"""Continuously monitor the environment."""
keep_monitoring = True
while keep_monitoring:
self.read_weights()
self.update_edge_weights()
keep_monitoring = self.execute_plan()
self.plan = self.next_plan |
def get_connection(self,database: Optional[str] = None) -> 'pyodbc.Connection':
database = database or ''
if database not in self._connections:
conn_string = database
try:
cnxn = pyodbc.connect(conn_string, timeout=3)
except pyodbc.O... | The function executes a SQL SELECT query by constructing a query string from provided parameters and conditions, fetching the results using a database connection, and returning the retrieved data as a list of records. | def fn_execute_select_query(self ,obj_parameters,type_condition ):
listresponse = []
self.obj_connection = self.get_connection(self.str_connection)
vvSelect , vvWhere = self.fn_get_query(obj_parameters,type_condition)
vvSqlSelectScript = vvSelect + vvWhere
print(vvSqlS... |
def get_connection(self,database: Optional[str] = None) -> 'pyodbc.Connection':
database = database or ''
if database not in self._connections:
conn_string = database
try:
cnxn = pyodbc.connect(conn_string, timeout=3)
except pyodbc.O... | This function executes an SQL UPDATE operation on a database table using provided parameters and conditions. It returns a success flag or, if flagSelect is True, the updated records. The function constructs the SQL script, handles database connections, and optionally fetches results after the update. | def fn_execute_update(self ,obj_put_parameters,obj_parameters,type_condition,flagSelect: Optional[bool] = False ):
varGoodExecutionFlag = False
if self.data_structure['type'] == "table":
listresponse = []
self.obj_connection = self.get_connection(se... |
def get_sections(self, table, base=[]):
# returns a list of all the flattened sections that have config values
sections = []
is_section = False
for key in table:
if isinstance(table[key], ConfigValue):
is_section = True
elif isinstance(table[key], ... | The code loads a configuration file, validates its structure by checking for required sections and keys, converts values to specified data types, and raises errors for missing or incorrect configurations. It creates the file if it doesn't exist and attempts to save it if loading fails. | def load(self, filename: str):
"""Attempts to load a configuration from a specified file.
This function will also create the file if it doesn't exists already and it will update the file with any options that may not be defined.
:param filename: The filename to load the config from.
:t... |
def sparseconv3d(x, w, final_resolution, start_resolution=32, f=None, up=1, down=1, padding=0, type='minkowski', input_res=None, force_no_mask=False):
if type == 'pytorch':
mask = (x != 0).any(dim=1, keepdim=True).type_as(x)
w = w.permute(0, 1, 4, 3, 2)
if up == 2:
mask = torch.n... | This code performs a forward pass of a convolutional layer, applying either sparse or dense 3D convolution based on the layer's configuration, followed by bias addition and activation function application, with parameters for gain, sparsity, and resampling control. | def forward(self, x, gain=1, force_no_mask=False):
w = self.weight * self.weight_gain
b = self.bias.to(x.dtype) if self.bias is not None else None
flip_weight = (self.up == 1) # slightly faster
if self.is_sparse:
x = sparseconv3d(x=x, w=w.to(x.dtype), final_resolution=self.fi... |
def to_dense(t, res, final_resolution=None, start_resolution=None):
if start_resolution is None:
global __DENSE_RESOLUTION__
if __DENSE_RESOLUTION__ is None:
raise RuntimeError('Please provide start_resolution or set global variable __DENSE_RESOLUTION__ before using this function')
... | This function generates a pruning mask for sparse tensors (Minkowski/PyTorch formats) by analyzing visibility, thresholding, and ensuring minimum entries per batch. It processes density/SH data, checks visible voxels, applies pruning rules, and enforces sparsity constraints while preserving essential features for rende... | def get_mask_for_pruning(self, weights, pose, threshold=0, keep_at_least=10):
if self.sparse_type == 'minkowski':
mask = torch.ones(len(weights), dtype=torch.bool, device=weights.device) # default, keep all
density_data_list = weights.decomposed_features
sh_data_list = [torc... |
def sparse_conversion(x, final_resolution, coords=None, sparse_type='minkowski', res=None):
''' coords of shape [1, C, S * N]'''
if sparse_type == 'pytorch':
return x
elif sparse_type == 'minkowski':
tensor_shape = x.shape
all_strides = [final_resolution//tensor_shape[-3], final_reso... | This code processes input tensors through convolutional layers with style modulation, supporting both dense and sparse tensor formats. It handles different architectures (resnet, skip), generates RGB outputs, and includes optional pruning for sparse representations. The function computes feature maps and produces image... | def forward(self, x, img, ws, force_fp32=False, fused_modconv=None, update_emas=False, prune=False, pose=None, **layer_kwargs):
_ = update_emas # unused
misc.assert_shape(ws, [None, self.num_conv + self.num_torgb, self.w_dim])
w_iter = iter(ws.unbind(dim=1))
if ws.device.type != 'cuda':
... |
def modulated_sparseconv3d(
x, # Input tensor of shape [batch_size, in_channels, in_height, in_width].
weight, # Weight tensor of shape [out_channels, in_channels, kernel_height, kernel_width].
styles, # Modulation coefficients of shape [batch... | This code implements a modulated 3D convolution (StyleGAN-style) that handles both dense and sparse tensors. It applies affine transformations to input styles, generates noise based on mode, performs convolution with optional upsampling, and applies activation functions. The function supports sparse tensor operations v... | def forward(self, x, w, noise_mode='random', fused_modconv=True, gain=1):
assert noise_mode in ['random', 'const', 'none']
if not self.is_sparse:
in_resolution = self.resolution // self.up
misc.assert_shape(x, [None, self.in_channels, in_resolution, in_resolution, in_resolution])... |
def modulated_sparseconv3d(
x, # Input tensor of shape [batch_size, in_channels, in_height, in_width].
weight, # Weight tensor of shape [out_channels, in_channels, kernel_height, kernel_width].
styles, # Modulation coefficients of shape [batch... | This code performs a modulated convolution operation (either sparse or dense) on input tensor x using weights and styles derived from input w. It applies affine transformation, modulation, and bias activation, with conditional handling for sparse/dense convolutions based on the 'is_sparse' flag. The operation includes ... | def forward(self, x, w, fused_modconv=True):
styles = self.affine(w) * self.weight_gain
if self.is_sparse:
x = modulated_sparseconv3d(x=x, weight=self.weight, styles=styles, final_resolution=self.final_resolution, start_resolution=self.dense_resolution,
... |
def to_dense(t, res, final_resolution=None, start_resolution=None):
if start_resolution is None:
global __DENSE_RESOLUTION__
if __DENSE_RESOLUTION__ is None:
raise RuntimeError('Please provide start_resolution or set global variable __DENSE_RESOLUTION__ before using this function')
... | This code processes input tensors `x` and `img` using sparse or dense representations based on `self.sparse_type`. It generates a pruning mask from classification features (last channel of `img`) and pose data, applies pruning to `x` and `img` if needed, and returns the pruned tensors. Debug mode validates consistency ... | def forward(self, x, img, pose):
assert img.shape[1] == 4
if self.sparse_type == 'minkowski':
cls = ME.SparseTensor(
features=img.F[:, -1:],
coordinate_manager=img.coordinate_manager,
coordinate_map_key=img.coordinate_map_key,
)
... |
def create_job_headers_table(db_path, table_name):
""" Create JobHeaders table that stores last update time
Create a JobHeaders table that has columns for each allowed
key from the JobHeader JSON object returned by the API. This
function does NOT load data into the table but only creates
it if it d... | The function identifies jobs requiring download by comparing current WDL job headers (from API) with stored records in a SQLite database. It returns jobs either never downloaded or modified since last sync, ensuring data consistency. The function creates the database/table if non-existent, uses parameters like API key,... | def get_jobs_to_download(api_key, db_path, table_name):
""" Return a pd.DataFrame of jobs that need to be downloaded
The job that need to be downloaded are those that
1) have not been downloaded previously (according to the records in
the table given by table_name in the database located at db_path... |
def get_api_url(job_id):
""" Return the WDL PersecData API endpoint
The endpoint returned by this module is:
https://api.welldatalabs.com/persecdata/<job_id>
Parameters
----------
job_id: str
The job_id to search the PerSec API for
Returns
-------
url: str
The... | The function `download_job_persec` repeatedly attempts to download PerSecData for a specified job ID from the WDL API, using an API key for authentication. It saves the downloaded data into CSV files as defined by `persec_filenames`, handling various HTTP status codes and retrying up to `max_attempts` times with a dela... | def download_job_persec(job_id, api_key, persec_filenames,
default_delay=70, max_attempts=3):
""" Download PerSecData for job_id and save CSVs given by persec_filenames
Repeatedly try to download the PerSecData data for the job indexed
by job_id from the WDL API. On success, the Pe... |
def d_in_ell(d: Dot, e: Ellipsoid):
d = d_to_ecs(d, e)
x, y, z = d.x, d.y, d.z
t = e.k * (x ** 2) + e.l * (y ** 2) + e.m * (z ** 2) - e.r ** 2
return t
def rot_dot(d: Dot, angle: Dot, reverse: bool = None):
d2_t = np.array([d.x, d.y, d.z, 1])
r_mat = get_rotation_matrix(angle)
if reverse is ... | This function determines if two ellipsoids intersect by translating and rotating them, checking the distance between centers, and calculating line-ellipsoid intersections. If the distance is within a tolerance (epsilon), it returns True and intersection points; otherwise, False and points. | def ell_intersection(e1: Ellipsoid, e2: Ellipsoid, epsilon: float = None, testing: bool = None):
if epsilon is None:
epsilon = 0
# E1 CENTER MUST BE 0,0,0 I.E.
d1 = e1.center
d2 = e2.center
d1_t = Dot(0, 0, 0)
t = d_in_ell(d1, e2)
if t > 0:
t = np.sqrt(t)
if t <= epsilon:... |
def IsServer(self, pkt):
return pkt.ip.dst == self.target_ip
def IsClient(self, pkt):
return pkt.ip.src == self.target_ip
def GetSrcKey(pkt):
srcIP = pkt.ip.src
srcPort = ""
if hasattr(pkt, 'udp'):
srcPort = str(pkt.udp.srcport)
elif hasattr(pkt, 'tcp'):
srcPort = str(pkt... | This function processes network packets by inserting them into multiple rows based on hash calculations, checking for saturation conditions (e.g., count thresholds), resetting buckets upon saturation, tracking time intervals between saturations, and extracting features for storage in CSV files. It handles TCP/UDP packe... | def InsertToAllRows(self, pkt):
hasIp = hasattr(pkt, 'ip')
hasTcp = hasattr(pkt, 'tcp')
hasUdp = hasattr(pkt, 'udp')
canInsert = False
if (hasIp and hasTcp) or (hasIp and hasUdp):
canInsert = True
if self.IsServer(pkt):
self.pktCountS += 1... |
def set_jpg(self,size):
jpg_const = "INITIAL_JPEG_%s"%(size,)
assert hasattr(self,jpg_const), "No uCAM_III.%s constant"%(jpg_const,)
reply = self.command(getattr(self,jpg_const))
assert self.check_ack(reply,self.INITIAL_JPEG_1[1])
def set_package_size(self,size):
size_const = "PK... | The main task of the code is to configure camera settings and capture a photo. It introduces delays between commands, sets JPEG size and package size, adjusts exposure settings, and triggers a snapshot command. The function ensures proper timing and verification for each step to prepare and capture an image. | def takephoto(self):
time.sleep(self.interCommandDelay)
self.set_jpg(self.jpgSize)
time.sleep(self.interCommandDelay)
self.set_package_size(self.pkgSize)
time.sleep(self.interCommandDelay)
self.command(self.EXPSETTINGS,verify=True)
time.sleep(self.interCommandDela... |
def create_missing_folders():
# From the github, some folders do not appear, this is to ensure they are present in the program
required_folders = [
"centers",
"cropped_centers",
"cropped_sides",
"faces",
"sides",
"squares",
"faces/Blue",
"faces/Gre... | The main task of the code is to process a Rubik's cube image by calibrating colors, converting images to numerical data, and rendering a simulation. It handles image acquisition, color assignment, error handling for poor camera quality or unsolvable cubes, and cleans up files afterward. | def main():
create_missing_folders()
answer = ask_calibration()
if answer == "Yes":
calibrate()
load_colors()
clean_directory()
show_directions()
get_cube() # method to get the cubes photos and screenshots
convert_to_img()
file_as_color()
try:
Cube = convert_to_n... |
def sampling_point(self):
#Randomly sample a point
if random.uniform(0, 1) < self.goal_bias:
newvertex = self.goal
else:
x = random.randint(1, self.grid.shape[0]-1)
y = random.randint(1,self.grid.shape[1]-1)
newvertex = tree(x, y)
#Check if... | The code implements a path planning algorithm, likely RRT (Rapidly-exploring Random Tree), by iteratively sampling points, finding nearest nodes, checking obstacles, and connecting nodes optimally. It rewires the tree for cost efficiency and returns a collision-free path to the goal if found, otherwise returns None aft... | def main(self):
for i in range(self.iter):
samplepoint=self.sampling_point()
nearnode =self.nearnode(samplepoint)
new_node =self.towards_nearnode(nearnode=nearnode,newvertex=samplepoint)
if self.obstaclecheck(nearnode,new_node):
near_nodes = se... |
def analyze(filename, verbose=0):
"""Takes a file and returns a dictionary of keyword-value pairs"""
f = open(filename, "rb")
lines = []
dic = {}
while 1:
line = f.readline()
# until eof
if not line:
break
# python 3 intially returns bytes value rather th... | (The main task of the code is to read structured vector field data from an OMF file. It analyzes the input file to extract dimensions, locates the data section's starting byte, reads the structured OOMMF data with appropriate parameters, and returns the vector field. Debug mode optionally prints dimensional details.) | def read_structured_omf_file(infile, debug=False):
"""Takes file name and returns vector field of data
stored in omf-file format in that filename.
This is the recommended interface.
"""
# learn about infile
ovf_run = analyze(infile)
dimensions = (int(ovf_run["xnodes:"]),
... |
def clear_display(self):
"""
Clear all 10 digits of the display panel.
:return: None
"""
self.__send_extended_byte_array(self.MODE_CLEAR_DISPLAY, [])
def __string_to_byte_array(instr):
return_array = []
for array_char in instr:
return_array.append(ord(array_char))
pad_count = 10 - len(return_arra... | The function `show_message` displays a given string on a panel, truncating it to 10 characters if necessary and issuing a warning. It converts the string to a byte array, validates its length, and sends it for display. If the input is empty, it clears the panel. | def show_message(self, msg):
"""
Display specified string in display panel.
:param msg: Message to display in the panel. The maximum allowed length of this string is 10.
:return: None
"""
if len(msg) == 0:
self.clear_display()
else:
if len(msg) > 10:
warnings.warn("Input string is truncated to... |
def add_course(curriculum: Curriculum, electives:OrderedDict, course: str, catalog: List[Course]):
new_curr = None
# find the course to extract its prereq info
if course in [c.name for c in curriculum.courses]:
# in this case, somethings up, let's leave that alone for now
# TODO
# in... | This function calculates the optimal and worst-case complexity values for a curriculum template by recursively exploring all possible elective course combinations. It iterates through electives, modifies the template by adding selected courses, removes elective placeholders, and compares results from recursive calls to... | def swing_calc(template: Curriculum, electives: OrderedDict[str, List[str]], catalog: List[Course]):
my_results = [(0,0), (10000,0)]
print("Loop!:", electives)
if len(electives) == 0:
return [(template.complexity()[0], template), (template.complexity()[0],template)]
# for elective in electives
... |
def add_impact(curr:Curriculum, courses: List[str], catalog:List[Course])->List[tuple[float, str]]:
# to calculate the impact just add the course
ret = []
for course_name in courses:
# add course to curr
new_curr = add_course(curr, course_name, catalog)
# calculate metrics and subtra... | The function `min_complexity` identifies the minimal set of courses required to satisfy curriculum requirements while minimizing complexity. It calculates the impact of adding courses, organizes them, selects the least impactful courses to meet requirements, updates the curriculum, and verifies the estimated vs. actual... | def min_complexity(curr: Curriculum, reqs: List[tuple[int, List[str]]], catalog: List[Course])->Curriculum:
# step 1: calculate the add impact of each course in reqs
## first make a list from the set of all unique courses in reqs
flat_reqs = []
for elective in reqs:
for course in elective[1... |
def add_impact(curr:Curriculum, courses: List[str], catalog:List[Course])->List[tuple[float, str]]:
# to calculate the impact just add the course
ret = []
for course_name in courses:
# add course to curr
new_curr = add_course(curr, course_name, catalog)
# calculate metrics and subtra... | The function `max_complexity` optimizes a curriculum by selecting courses that maximize impact while satisfying requirements. It calculates the impact of each course, prioritizes high-impact courses, and adds them to the curriculum. It verifies if the estimated complexity increase aligns with actual results, returning ... | def max_complexity(curr: Curriculum, reqs: List[tuple[int, List[str]]], catalog: List[Course]) -> Curriculum:
# step 1 calculate the add impact of each course
# but first make a list from the set of all unique courses in the reqs
flat_reqs = []
for elective in reqs:
for course in elective[1]:
... |
def act(self, state, neural_net_to_use, no_grad=True):
state = torch.FloatTensor(state)
actions = self.forward_pass(neural_net_to_use, state, no_grad)
return actions
def fit_actor_output_to_env(self, action):
# Below assumes action between 0 and 1, which is right for sigmoid
retu... | This code trains a reinforcement learning agent using experience replay and target network updates. It collects environment interactions, stores them in a buffer, and periodically trains neural networks (actor and critic) with batches of experiences. The OUNoise adds exploration noise to actions, while soft updates sta... | def train(self, num_steps, batch_size):
state = self.env.reset()
noise = OUNoise(self.env.action_space)
for step in range(num_steps):
action = self.act(state, self.actor_net)
action = noise.get_action(action.detach().numpy(), step)
action = self.fit_actor_o... |
def get_pr_num():
if len(sys.argv) == 2:
return sys.argv[1]
return input("Which pull request would you like to merge? (e.g. 34): ")
def connect_jira(cmd):
return jira.client.JIRA({'server': JIRA_API_BASE},
basic_auth=get_credentials(cmd))
def prompt_for_fix_version(cmd, ... | (This code automates merging a GitHub pull request and updating its associated JIRA ticket. It checks if a PR is mergeable, confirms the merge, executes the merge, prompts for JIRA updates, and resolves the JIRA issue with a PR reference and fix versions. The tool integrates GitHub and JIRA workflows for code review an... | def cli():
# Location of your Arrow git clone
print("ARROW_HOME = " + ARROW_HOME)
print("PROJECT_NAME = " + PROJECT_NAME)
cmd = CommandInput()
pr_num = get_pr_num()
os.chdir(ARROW_HOME)
github_api = GitHubAPI(PROJECT_NAME)
jira_con = connect_jira(cmd)
pr = PullRequest(cmd, githu... |
def opening_sequence(screen, clock):
try:
tankImg = pygame.image.load('Tanks/images/tank_main.jpg')
tankImg = pygame.transform.rotozoom(tankImg, 0, WIDTH / 700)
except pygame.error as message:
tankImg = pygame.Surface(SCREEN_DIMS)
tankImg.fill(GREEN)
i = 0
while True:
... | The code initializes a "Battle Tanks" game, runs an opening sequence, generates players and a map via a menu, and enters a loop to execute game rounds. It resets player stats, regenerates maps, and shuffles players after each round. The game_sequence function determines progression, with the store accessible post-round... | def main():
# Initialize pygame and create window
round_num = 1
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Battle Tanks")
clock = pygame.time.Clock()
#Run the opening sequence
opening_sequence(screen, clock)
#Generate the players and... |
def loader(self):
with open('settings.yaml', "r") as f:
data = yaml.safe_load(f)
return data
def calculateRankScore(self, sd:str, size:str):
data = self.loader()
d = data.get('dimensions')
if sd not in d:
raise Exception("incorrect dimension")
... | This code aggregates and analyzes dimensional data using the Pareto front method to identify optimal (non-dominated) and dominated solutions. It processes ranked scores, applies NSGA-II for multi-objective optimization, and compiles results into a structured table with 'Solution' and 'Dominated' columns, replacing NaN ... | def paretoAgg(self, size:str):
data = self.loader()
d = data.get('dimensions')
self.dims = list(d.keys())
li = []
for x in self.dims:
dimension_ranking = self.calculateRankScore(x, size)
dimension_ranking = dimension_ranking['Result']
... |
def loader(self):
with open('settings.yaml', "r") as f:
data = yaml.safe_load(f)
return data
def getRanks(self, sd, size):
df = self.file_reader(sd, size)
df_transpose = df.T
df_full_ranks = []
for index, row in df_transpose.iterrows():
df_full_ran... | The main task of the code is to generate a table containing Pareto-optimal and dominated solutions using NSGA-II multi-objective optimization. It processes input data, computes rankings, identifies non-dominated solutions, formats configurations, and combines results into a structured DataFrame with empty string placeh... | def paretoQ(self, size:str):
data = self.loader()
d = data.get('dimensions')
dimensionsAll = self.getRanks(sd = list(d.keys())[-1], size=size)
dimensionsAll = dimensionsAll.reset_index().values
dimensions = np.array(self.getRanks(sd = list(d.keys())[-1], size=size)[:], d... |
def loader(self):
with open('settings.yaml', "r") as f:
data = yaml.safe_load(f)
return data
def getRanks(self, sd, size):
df = self.file_reader(sd, size)
df_transpose = df.T
df_full_ranks = []
for index, row in df_transpose.iterrows():
df_full_ran... | The code identifies Pareto-optimal solutions and dominated points using NSGA-II multi-objective optimization. It processes input dimensions, generates rankings, separates Pareto and dominated sets, converts them into structured dataframes, and merges them into a table with solutions and dominated entries, replacing NaN... | def paretoQ(self, size:str):
data = self.loader()
d = data.get('dimensions')
dimensionsAll = self.getRanks(sd = list(d.keys())[-1], size=size)
dimensionsAll = dimensionsAll.reset_index().values
dimensions = np.array(self.getRanks(sd = list(d.keys())[-1], size=size)[:], d... |
def loader(self):
with open('settings.yaml', "r") as f:
data = yaml.safe_load(f)
return data
def calculateRankScore(self, sd:str, size:str):
data = self.loader()
d = data.get('dimensions')
if sd not in d:
raise Exception("incorrect dimension")
... | This function performs multi-objective optimization using NSGA-II on ranked dimension data. It aggregates Pareto optimal solutions and dominated points from input data, converts them into structured configurations, and returns a combined table showing both Pareto and dominated solutions with NaN values replaced by empt... | def paretoAgg(self, size:str):
data = self.loader()
d = data.get('dimensions')
self.dims = list(d.keys())
li = []
for x in self.dims:
dimension_ranking = self.calculateRankScore(x, size)
dimension_ranking = dimension_ranking['Result']
... |
def loader(self):
with open('settings.yaml', "r") as f:
data = yaml.safe_load(f)
return data
def calculateRankScore(self, sd:str, size:str):
data = self.loader()
d = data.get('dimensions')
if sd not in d:
raise Exception("incorrect dimension")
... | This function calculates the normalized Kendall tau distance between two ranking sets (rankset1 and rankset2) for each element in the input list 'li'. It processes dimensions, 'paretoAgg', and 'paretoQ' by extracting rank scores, aligning them with Pareto solutions, and computing coherence metrics. Results are compiled... | def coherence(self, li:list, rankset1:str, rankset2:str):
data = self.loader()
d = data.get('dimensions')
dims = list(d.keys())
result = []
for x in li:
if x in dims:
var1 = self.calculateRankScore(x, rankset1)
var1 = var1['Res... |
def loader(self):
with open('settings.yaml', "r") as f:
data = yaml.safe_load(f)
return data
def getRanks(self, sd, size):
df = self.file_reader(sd, size)
df_transpose = df.T
df_full_ranks = []
for index, row in df_transpose.iterrows():
df_full_ran... | The function calculates conformance scores for given criteria dimensions or special cases ('paretoQ', 'paretoAgg') by filtering ranked data, counting valid entries, and applying a formula. It returns a DataFrame with conformance values indexed by criteria names and columns by input size. | def conformance(self, li:list, size:str, k:int, h:int):
data = self.loader()
d = data.get('dimensions')
query = data.get('query')
dims = list(d.keys())
data = []
idx = []
for x in li:
if x in dims:
criteria_table = self.getRank... |
def solveNaive(self, game: Board, player: Colour) -> int:
"""
Check if there is a move for the current player to instantly win the game
:param game: The board instance
:param player: The colour of the player to place a chip
:return: The column that wins the game, -1 if none
... | The code determines the optimal move for a player in a board game by prioritizing immediate wins, blocking opponent wins, and applying minimax with depth-based evaluation. It selects from minimax-optimal moves, refining choices using attack/prophylactic scores and central-column preference. If ties persist, it randomly... | def solveBoard(self, game: Board, player: Colour) -> int:
"""
Uses a mix of AI techniques to determine the optimal move given a game board
:param game: The game state to solve
:param player: The player for whom we want to find the optimal move
:return: The column in which to play... |
def make_player_move(self, game: Board, placing_colour: Colour):
valid_input = False
while not valid_input:
input_col = int(input("Input column to place " + placing_colour.value + ": "))
if 0 <= input_col < Board.COLUMNS and game.move_available(input_col):
valid_i... | The code implements a game loop where a player and AI alternate turns on a board game. It allows user input to determine if the solver (AI) moves first and selects the player's color (RED/YELLOW). The game continues until a winner is determined or a tie occurs, with results displayed at the end. | def play(self, game: Board):
print(game)
player_colour = Colour.RED
player_first = True
answer = input("Should the solver make the first move? Y/N ")
if answer == "Y" or answer == "y":
player_first = False
answer = input("What colour should the solver be? R/Y... |
def initialize_main_window(self):
"""Initialize the main window of the bank GUI with its settings and position."""
window = tk.Tk()
window.report_callback_exception = handle_exception
window.title("MY BANK")
window.geometry("800x600") # Width x Height in pixels
screen_w... | The main task of the code is to initialize and configure GUI elements for a financial application, including the main window, options panel, account frames, transaction widgets, and summary components. It orchestrates the setup of essential interface elements to facilitate user interaction with account management and t... | def setup_gui_elements(self):
"""Setup all the GUI elements like the main window, options, account frames, etc."""
self._window = self.initialize_main_window()
self.make_options()
self.initialize_account_frames()
self.initialize_transaction_widgets()
self._summary() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.