dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def readStates():
filename = "board_input.txt" # Reading the input file
fp = open(filename, "r")
while True:
line = fp.readline()
if line == "":
break
line_split = line.split('\n') # Splitting each line
for i in line_split:
if i == "":
... | The code allows user selection between Teacher Mode and Non-Teacher Mode to run a game multiple times. In Teacher Mode, it reads game states from a file, calculates weights, and prints statistics, then executes the game loop. In Non-Teacher Mode, it generates training data, calculates weights, and runs the game loop. B... | def selectoption():
global playUntil
global nextFlag
global board
option = int(input("1. Teacher Mode\n2. Non Teacher mode\nOption:"))
if option == 1:
gameshouldwork = input('Enter number of time the game should work : ')
playUntil = gameshouldwork
spam = 0
readSta... |
def get_row_by_id(self, id_):
hnt_table = hnt_metadata.tables[self.HNT_DB_TABLE_NAME]
select_stmt = select([hnt_table]).where(hnt_table.c.id == id_)
logger.debug(f"[{self.HNT_SERVICE_NAME}] fetching ID: {id_}, {select_stmt}")
row = hnt_db_engine.execute(select_stmt).fetchone()
r... | The main task of the code is to retrieve data rows either by a specific ID or in bulk using `_get_rows`, then transform each row into the required payload format for the hnt database via `_transform_row`, yielding the results one by one. If an `id_` is provided, it fetches a single row directly; otherwise, it processes... | def get_forms(self, id_):
"""
Calls _get_rows method to get rows one by one, then calls _transform_row
method to transform each row into required payload format for hnt db
"""
# if given an id, bypass the normal _get_rows method and just get our single row
if id_:
... |
def RF_make_prediction(x: list, RF: list):
# Get predictions for trees in random forest
predictions = [
DT_make_prediction(x, i) for i in RF
]
# Get majority vote in predictions
#if sum(predictions) >= len(RF):
# return 1
return predictions
def RF_success_count(RF: list, p: int):... | The function evaluates a random forest model by testing each tree's prediction accuracy and the majority vote accuracy across all samples. It tracks individual tree successes, converts them to percentages, prints each tree's accuracy, and returns the overall model accuracy as a percentage of correct predictions. | def RF_test_random_forest(X: list, Y: list, RF: list):
# Variables
successes = 0
RF_successes = [0] * (len(RF))
# Test each sample on random forest
for sampleNum in range(0, len(X)):
RF_results = RF_make_prediction(X[sampleNum], RF) # Get results for each tree
if sum(RF_results)... |
def prepare_unpacked_folder(target_dir):
unpacked_dir = dirman.create_dir(target_dir, "unpacked")
if not unpacked_dir:
return None
ret = dirman.create_dir(unpacked_dir, "dx11")
if not ret:
return None
ret = dirman.create_dir(unpacked_dir, "dx12")
if not ret:
return None... | The main task of the code is to unpack and convert PAK files from the Elex 2 game directory into DOC format, handling user confirmation, disk space warnings, and directory management. It reads configuration settings, prepares target folders, extracts PAK files, and converts them while ensuring proper error handling and... | def main():
config.read_config()
# no need to use locks if not using multithreading (saved miliseconds you can spend however you want!)
if config.current.get("max_threads"):
console.create_lock()
console.print_warning("This script may require A LOT of space to unpack everything, up to triple s... |
def checkEvent(self):
self.acc=vec(0,gravity)
self.jump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.acc.x = ... | This code runs a game loop, handling player movement physics (acceleration, velocity, position), collision checks, screen updates, and game state management. It initializes score, processes events, updates game objects, checks for game over conditions, and exits gracefully by fading music and quitting Pygame. | def run(self):
self.score=0
self.gameOver = False
while not self.gameExit:
self.checkEvent()
self.acc.x+=self.vel.x*player_Fric
self.vel+=self.acc
self.pos+=self.vel+0.5*self.acc
self.checkHorizontalCrossing()
self.updateScr... |
def messageToScreen(self,msg,size, color, x, y):
font=pygame.font.Font(self.font_name,size)
text_surface=font.render(msg,True,color)
text_rect=text_surface.get_rect()
text_rect.midtop=(x,y)
self.gameDisplay.blit(text_surface,text_rect)
def waitForKeyPress(self):
waiting=T... | This code renders a game start screen using Pygame, displaying scaled background images and a "Press any key" prompt. It waits for user input, cycles through multiple images with a continue button, and transitions to the game menu after three key presses. The function handles image loading, scaling, display updates, an... | def startScreen(self):
display_size = self.gameDisplay.get_size()
background_image = pygame.image.load("./prehistory/back1.jpg") # Replace with your image
background_image = pygame.transform.scale(background_image, display_size)
self.gameDisplay.blit(background_image, (0,0))
con... |
def retrieve_lyrics(item):
sem = True
print("Item : ",item)
parsed_data = json.loads(item)
artists_songs = parsed_data["artists_songs"]
try:
artist = artists_songs.split('-')[0]
song = artists_songs.split('-')[1]
song = song.split('[')[0]
song = song.lower(... | The function `get_lyrics` retrieves lyrics for a given item and stores them in JSON format if successful. It also checks if 24 hours have passed since the last retry, triggering a retry of songs in a list and updating the retry timestamp. The global `last_retry_time` tracks the last retry attempt, ensuring retries occu... | def get_lyrics(item):
global last_retry_time
lyrics = retrieve_lyrics(item)
if lyrics is not None:
json_create(item, lyrics)
current_time = time.time()
if current_time - last_retry_time >= (60*60*24):
print("Retrying 24 hours later...")
retry_songs(retry_list)
las... |
def get_conn(connection_args):
return connect(None,
database=connection_args['database'],
host=connection_args['host'],
user=connection_args['user'],
password=connection_args['pass'])
def build_create_database_statement():
database_name... | This code generates 1000 random databases, each containing 1000 tables with 1 inserted record. It uses nested loops to create SQL statements for databases, tables, and data insertion, executes them via a database connection, and prints progress details. The main task is to automatically create and populate a large volu... | def create_random_metadata(connection_args):
conn = get_conn(connection_args)
cursor = conn.cursor()
for x in range(1000):
database_name, database_stmt = build_create_database_statement()
cursor.execute(database_stmt)
for y in range(1000):
tablename , query = build_crea... |
def _update_synth(self):
c = self._c_grid.get_values()
m = self._m_grid.get_values()
params = {'carrier_freq': c[0], 'carrier_amp': c[1],
'mod_freq': m[0], 'mod_depth': m[1]}
self._fm.set_params(params)
def _set_animation_samples(self):
samples = self._fm.get_... | This code initializes an FM Explorer application, setting up GUI components, audio synthesis, and user interaction elements. It configures carrier/modulation parameter grids, waveform/spectrum displays, audio synthesis parameters, and status messaging systems for an FM synthesis tool with adjustable parameters and real... | def __init__(self, window_size,
init_carrier_max=(1000.0, MAX_VOL),
init_modulation_max=(400.0, 25.),
carrier_init=(440., 0.31),
modulation_init=(100, 0.)):
"""
initialize app window
:param window_size: Width x height
"... |
def setOutfileInfo():
logPath = createAppFolders()
return logPath
def logEvent(msg, logPath):
logWriter = open(logPath,"a")
msg = "\n" +str(getLogDateTime())+" EventLogged: "+msg
logWriter.write(msg + "\n")
logWriter.close()
def searchDir(newPath,logPath):
path = newPat... | The main task of the code is to repeatedly scan a specified directory, log events to a file, and toggle between moving/returning files using a demo module. It runs in an infinite loop, pausing for a set duration between scans, until manually terminated. | def main():
path = 'C:\\testFileDirectories'
run = 10
sec = 10
alive = True
logPath = setOutfileInfo()
##goes until closed manually
while alive == True:
logEvent(("Scan Starting in "+ path),logPath)
searchDir(path,logPath)
logEvent("Scan Finished.",logPath )... |
def get_output(self, img_path, aspectRatios=None):
cmd = self.cmd_template.format(img_path.absolute())
if aspectRatios is None:
aspectRatios = self.aspectRatios
if aspectRatios is not None:
aspectRatio_str = " ".join(str(ar) for ar in aspectRatios)
cmd = f"{cm... | The code plots top K salient regions of an image along with their crops and saliency maps, arranging them in a grid. It adjusts layout based on image aspect ratio, number of crops, and parameters like topK and col_wrap. Saliency scores are visualized, with optional sampling and symmetry checks. | def plot_img_crops(
self,
img_path,
topK=1,
aspectRatios=None,
checkSymmetry=True,
sample=False,
col_wrap=None,
add_saliency_line=True,
):
img = mpimg.imread(img_path)
img_h, img_w = img.shape[:2]
print(aspectRatios, img_w, img... |
def native_python():
start_ts = time.time()
res = fibonacci(N)
end_ts = time.time()
print(f"[python] Execution time is {end_ts - start_ts} seconds")
return res
def ctypes_fibonacci():
lib = ctypes.CDLL('./ctypes_util/libutils.so')
lib.fibonacci.restype = ctypes.c_int
lib.fibonacci.argsty... | The main task of the code is to compare the results of multiple Fibonacci sequence implementations (native Python, ctypes, CFFI, C API, and Cython) by asserting their equality and printing the common result. It verifies cross-implementation consistency and outputs the computed Fibonacci value. | def main():
py_res = native_python()
ctypes_res = ctypes_fibonacci()
cffi_res = cffi_fibonacci()
capi_res = capi_fibonacci()
cython_res = cython_fibonacci()
assert(py_res == ctypes_res == cffi_res == capi_res == cython_res)
print(f"Result is {py_res}") |
def InitializeComponent():
DrawGrid()
DrawModes()
pygame.display.update()
def HandleEvents():
global IsRunning, grid, x, y
events = pygame.event.get()
for event in events:
# Quit the game window
if event.type == pygame.QUIT:
IsRunning = False
sys.exit()
... | The main task of the GameThread function is to manage the game loop by continuously handling user events, redrawing the game grid, and updating the display while the game is running. It initializes components, processes input, renders visuals, and maintains real-time interaction using a while loop controlled by the IsR... | def GameThread():
InitializeComponent()
while IsRunning:
HandleEvents()
DrawGrid()
pygame.display.update() |
def create_user_dict(self, name_col):
user_dict = {}
counter = 0
for i in self.df_visit[name_col].unique():
user_dict[i] = counter
counter += 1
return user_dict
def create_item_dict(self, id_col, name_col):
item_dict = {}
for i in range(self.df_ite... | The code initializes a class by loading user and item data from CSV files, creating user-item dictionaries, fitting a model, and generating interaction feature matrices. It stores these matrices as instance variables for further processing or analysis in recommendation systems or similar tasks. | def __init__(self, path_visit, path_item):
self.df_visit = pd.read_csv(path_visit)
self.df_item = pd.read_csv(path_item)
self.user_dict = self.create_user_dict(name_col='user_id')
self.item_dict = self.create_item_dict(id_col='mon_id', name_col='name')
self.model = self.model_fit... |
def cmdLineParse(iargs = None):
parser = createParser()
inps = parser.parse_args(args=iargs)
inps.slc_dirname = os.path.abspath(inps.slc_dirname)
inps.orbit_dirname = os.path.abspath(inps.orbit_dirname)
inps.aux_dirname = os.path.abspath(inps.aux_dirname)
inps.work_dir = os.path.abspath(inps.wo... | The code processes SAR (Synthetic Aperture Radar) data based on a specified workflow (interferogram, offset, correlation, or slc). It validates inputs, checks for existing output directories, selects date pairs, and executes the chosen workflow's processing pipeline, such as generating interferograms or stacking SLC da... | def main(iargs=None):
inps = cmdLineParse(iargs)
if os.path.exists(os.path.join(inps.work_dir, 'run_files')):
print('')
print('**************************')
print('run_files folder exists.')
print(os.path.join(inps.work_dir, 'run_files'), ' already exists.')
print('Pleas... |
def arcan_get(proj_name, result, proj_res):
report_filepath = str(lib.ROOT_PATH) + f"/Arcan/{proj_name}/component-metrics.csv"
metric_col_name = {"LOC":"LinesOfCode", "FANIN":"FanIn", "FANOUT":"FanOut"}
proj_res["arcan_loc"] = 0
proj_res["arcan_filenum"] = 0
csvfile = open(report_filepath, 'r')
... | The main task of the code is to collect and return both file-level and project-level metrics for a given project name by invoking four separate functions (arcan_get, deg_get, sgraph_get, dv8_get), which populate the result and proj_res dictionaries with respective data. The function aggregates these metrics and returns... | def get_result(proj_name):
result = {} # Metrics in file level
proj_res = {} # Metrics in project level
arcan_get(proj_name, result, proj_res)
deg_get(proj_name, result,proj_res)
sgraph_get(proj_name, result, proj_res)
dv8_get(proj_name, result, proj_res)
return result, proj_res |
def delta_fst_true(true_scenario):
''' Returns the delta_fst's that are larger than the actual delta_fst'''
same_avg = avg_fst(true_scenario[0])
diff_avg = avg_fst(true_scenario[1])
delta_fst = round(abs(same_avg - diff_avg),3)
return delta_fst
def delta_fst_average(poss_populations):
'''
Ta... | This function identifies significant genetic loci by performing permutation tests on gene and ecotype data. It calculates p-values for each gene, compares delta-FST values, and determines significance (p ≤ 0.05). Results are logged and saved in CSV files, distinguishing significant loci from all tested genes. | def identify_significant_loci(input_prefix, gene_file, ecotype_file):
'''
This function performs various data processing and analysis tasks to
identify significant loci based on genetic and ecotype data. It writes logs
and results to files and outputs a completion message when finished.
'''
log ... |
def move_part(self, pickup_pose, place_pose):
"""
Move a part from one pose to another pose
Args:
pickup_pose (geometry_msgs.Pose): Current pose of the part in world frame
place_pose (geometry_msgs.Pose): Pose of the part in the bin in the world frame
Returns:
... | The code performs a pick-and-place operation for two parts (A and B) using dynamically retrieved coordinates. It logs locations, creates poses for each part, and calls `move_part` to transfer them. After processing both parts, it confirms completion if both movements succeed, with error handling if not. | def pickandplace(self):
"""
Pick and Place poses for both parts retrieved dynamically
"""
rospy.loginfo("Pick A location {}".format(self.pick_coordinates_a))
rospy.loginfo("Place A location {}".format(self.place_a))
# Pick and Place part 1
self.count += 1 # count... |
def get_transform(self, parent_frame, child_frame):
try:
now = rospy.Time.now()
self._tf_listener.waitForTransform(parent_frame,
child_frame,
now, rospy.Duration(0.5)
... | The main task of the code is to determine the correct camera assignments for parts based on their colors and locations, generate frame identifiers for robotic pick-and-place operations, and handle scenarios where parts share the same color by analyzing their positions. It concatenates parts from two cameras, checks col... | def main(self):
"""
Main function to start the Node core
"""
# Instantiate camera type to concatenate for frames
cam_name_1 = ''
cam_name_2 = ''
# To get total parts in the workcell
self.concatenated_list_of_parts = self.list_of_parts_cam1 + self.list_of_p... |
def __create_root(self):
"""Creates the main root of the game"""
self.__root = tk.Tk()
self.__root.title(ROOT_NAME)
self.__root.protocol("WM_DELETE_WINDOW", self.on_closing)
def __create_upper_frame(self):
"""Creates the upper frame(the place for the timer and the score)"""
... | The main task of the code is to create a graphical user interface (GUI) by initializing the root window, upper frame, display label, button grid, and bottom formatting components. It assembles the entire screen view through a series of private methods, structuring the layout and elements of the application's interface. | def __create_gui(self):
"""Summerize the create of the whole screen view"""
self.__create_root()
self.__create_upper_frame()
self.__create_display_label()
self.__create_buttons_grid()
self.__create_buttom_format() |
def _total_height(self) -> int:
"""Return the screen height for this visualization."""
return self._num_floors * FLOOR_HEIGHT + STAT_WINDOW_HEIGHT
def _setup_sprites(self, elevators: List[sprites.ElevatorSprite]) -> None:
"""Set up the initial sprites for this visualization.
Position th... | This code initializes a visualization system for elevator simulation. If visualization is enabled, it sets up a Pygame window, creates sprite groups for rendering elevators and stats, configures display settings, and prepares initial rendering. It checks the 'visualize' flag to determine whether to execute setup steps,... | def __init__(self,
elevators: List[sprites.ElevatorSprite],
num_floors: int,
visualize: bool) -> None:
"""Initialize this visualization.
If visualize is False, this instance does nothing.
"""
self._visualize = visualize
if not s... |
def max_heapify_up(A, n, c):
p = parent(c)
if A[p] < A[c]:
A[c], A[p] = A[p], A[c]
max_heapify_up(A, n, p)
def shift_right(self):
self.min_heap.append(self.k_array.pop(len(self.k_array) - 1))
min_heapify_up(self.min_heap, len(self.min_heap), len(self.min_heap) - 1)
def max_heapi... | This function adds a bowl of size 's' to a data structure, maintaining a sorted list (k_array) and two heaps (max_heap, min_heap) to manage the top-k elements. It inserts 's' into the appropriate position in k_array, adjusts heaps based on comparisons with k_array's bounds, and balances heaps via shifts and heapify ope... | def record_bowl(self, s):
"Add bowl with size s"
if len(self.k_array) == 0:
self.k_array.append(s)
elif len(self.k_array) < self.k:
for i in range(len(self.k_array)):
if self.k_array[i] > s:
self.k_array[i:i] = [s]
... |
def deserialize_outpoint(transaction):
out_hash = deserialize_uint256(transaction)
out_index = deserialize_uint32(transaction)
return {'hash': out_hash, 'n': out_index}
def deserialize_script(transaction):
script_data = ''.join(deserialize_vector(transaction, deserialize_char))
return script_data
de... | The code deserializes a transaction's input by extracting the previous output (prevout), script signature (scriptSig), and sequence number (nSequence) using helper functions, then returns them as a structured dictionary for further processing in blockchain operations. | def deserialize_txin(transaction):
outpoint = deserialize_outpoint(transaction)
scriptSig = deserialize_script(transaction)
nSequence = deserialize_uint32(transaction)
return {'prevout': outpoint, 'scriptSig': scriptSig, 'nSequence': nSequence} |
def deserialize_int32(transaction):
i = transaction.tx_data[:4]
transaction.tx_data = transaction.tx_data[4:]
return struct.unpack("<i", i)[0]
def deserialize_vector(transaction, deserialization_function):
vec = []
l = deserialize_varint(transaction)
for i in range(l):
vec.append(deseria... | This function deserializes a blockchain transaction from a byte stream into a structured dictionary. It reads the transaction version, inputs (vtxin), outputs (vtxout), and handles SegWit witness data if present. The code checks flags to determine parsing logic, adjusting for witness data when needed by reprocessing in... | def deserialize_transaction(transaction):
tx = {}
tx["version"] = deserialize_int32(transaction)
tx["vtxin"] = deserialize_vector(transaction, deserialize_txin)
tx["flags"] = 0
if len(tx["vtxin"]) == 0 and WITNESS:
tx["flags"] = int(deserialize_char(transaction), 16)
if tx["flags"] !... |
def convert_to_raw_github_url(github_url):
# Check if the URL is already a raw URL
if 'raw.githubusercontent.com' in github_url:
return github_url
# Replace the domain
raw_url = github_url.replace('github.com', 'raw.githubusercontent.com')
# Remove '/blob'
raw_url = raw_url.replace('/b... | The function validates feedstocks by checking their stores for public status and geospatial attributes, collects errors, and returns a catalog of valid feedstocks while raising exceptions on failures. | def validate_feedstocks(*, feedstocks: list[upath.UPath]) -> list[Feedstock]:
errors = []
valid = []
catalog = []
for feedstock in feedstocks:
try:
feed = Feedstock.from_yaml(convert_to_raw_github_url(feedstock))
if feed.stores:
print('🔄 Checking stores'... |
def convert_to_raw_github_url(github_url):
# Check if the URL is already a raw URL
if 'raw.githubusercontent.com' in github_url:
return github_url
# Replace the domain
raw_url = github_url.replace('github.com', 'raw.githubusercontent.com')
# Remove '/blob'
raw_url = raw_url.replace('/b... | The code validates feedstock configurations either for a single provided file path or all feedstocks in a directory. It checks YAML validity, reports success/failure, and includes error traces for invalid cases. | def validate(args):
if args.single:
# If single file path is provided, validate just this one feedstock
try:
_ = Feedstock.from_yaml(convert_to_raw_github_url(args.single))
print(
format_report(
'✅ Valid feedstock:', [{'feedstock': str(args... |
def to_tuple(input):
t = ()
for i in range(len(input)):
ti = ()
for j in range(len(input[i])):
ti = ti + (input[i][j],)
t = t + (ti,)
return t
def cycles_1000(input0):
for _ in range(1000):
input0 = cycle_1(input0)
return input0
def prettyprintuple(input):... | The code simulates 1,000,000 iterations of a cyclic process on the input data, converts it to a tuple, and returns the resulting counter value after processing. It measures execution time and prints intermediate results. The commented section suggests an optimized cycle detection approach for larger iterations, but the... | def solve_part_2(input):
global cycle_start, cycle_end, memory
start = time.thread_time_ns()
input = to_tuple(input)
for i in range(1_000_000):
input = cycles_1000(input)
# for i in range(1_000_000_000):
# if cycle_start != -1 and cycle_end != -1:
# cycle_len = cycle_end ... |
def read_input():
headers = {'Cookie': 'session={}'.format(open("../sessionId").readline())}
return requests.get("https://adventofcode.com/2023/day/14/input", headers=headers).text.splitlines()
def solve_part_1(input0):
start = time.thread_time_ns()
input1 = to_list(move_N(to_tuple(input0)))
counter... | The main task of the code is to read input lines, strip whitespace from each line, and return the results of two solving functions (`solve_part_1` and `solve_part_2`) applied to the processed input. It prepares the input data for problem-solving tasks, likely for Advent of Code-style challenges, by cleaning the input a... | def main():
input = read_input()
# input = open("test_input").readlines()
input = list(map(lambda s: s.strip(), input))
return solve_part_1(input), solve_part_2(input) |
def get_stretch_stress(path_distance="sansbulle_distance.csv", path_force="sansbulle_force.csv"):
data_distance = get_data(path_distance)[:130]
data_force = get_data(path_force)
temps = data_force["t(s)"]
force_raw = data_force[" F(N)"]
func_f = interp1d(temps, force_raw)
force = func_f(data_dis... | The code plots experimental and modeled stress-stretch curves from CSV data. It reads stretch-stress data, identifies material parameters (c0, c1), calculates a stress model, and visualizes both experimental and modeled curves. The plot includes labels, a legend, and is saved as an image file. The main task is to compa... | def plot_ss(path_distance="sansbulle_distance.csv", path_force="sansbulle_force.csv", title="sansbulle"):
stretch, stress = get_stretch_stress(path_distance, path_force)
c0, c1 = identifier(path_distance, path_force)
stress_model = sigma(stretch, c0, c1)
plt.title("identification " + str(title))
plt... |
def split_img(img, dim=0):
get_sum = np.sum(img, axis=dim)
get_sum[get_sum > 0] = 1
a = np.array(get_sum[:-1], dtype="int32")
b = np.array(get_sum[1:], dtype='int32')
c = np.arange(get_sum.size - 1, dtype='int32')
delta_sum = (a - b) * c
mask_x_d = [-x for x in delta_sum if x < 0]
mask... | The function `get_all_masks` splits an input image into two parts, retrieves masks for each part using `get_masks`, combines the masks from both parts, and generates a list of final masks by applying `generate_mask` to each coordinate pair in the combined list. | def get_all_masks(img):
img_1, img_2 = split_img(img)
p_0 = get_masks(img_1, 0)
p_1 = get_masks(img_2, 1)
for p in p_1:
p_0.append(p)
masks_list = [generate_mask(img, xy) for xy in p_0]
return masks_list |
def exp_test(path):
global seuil_max
img = read_img(path)
[x1, x2] = get_axis_char(img, 0)
img_new = np.zeros(img.shape)
img_new[800:1200, x1:x2] = 255 - img[800:1200, x1:x2]
cv2.blur(img, (20, 20))
img_new[img_new <= seuil_max] = 0
img_new[img_new > seuil_max] = 1
return img_new
def... | This function processes images in a directory to detect and calculate spatial distances of points, normalizes these distances relative to the first detected values, and saves the results along with annotated images. It iterates through up to 200 images, extracts timestamps, applies mask detection, and stores normalized... | def get_distance_all(path, path_save):
if not os.path.isdir(path_save):
os.mkdir(path_save)
if not os.path.isdir(path):
print("Not a dir")
exit()
distance = []
for root, dir, files in os.walk(path):
for i, img_path in enumerate(sorted(files)[:200]):
time = flo... |
def get_arg(key, default=None):
# type: (str, Any) -> Any
"""Get the argument value or default"""
if default is None:
default = ""
return plugin.args.get(key, [default])[0]
def add_menu_item(method, label, **kwargs):
# type: (callable, Union[str, int], Any) -> None
"""wrapper for xbmcplu... | The function handles search operations in a media plugin, managing query parameters, saving/removing searches, and displaying results. It processes user input, retrieves data via URLs, parses results, and configures XBMC's UI with categories, content types, and sorting options for search results. | def search():
# type: () -> Optional[bool]
"""Search the archive"""
query = get_arg("q")
offset = int(get_arg("offset", 0))
# remove saved search item
if bool(get_arg("delete", False)):
bfis.searches.remove(query)
xbmc.executebuiltin("Container.Refresh()")
return True
... |
def load_data(data_path):
try:
data = pd.read_csv(data_path)
return data
except FileNotFoundError:
print("File not found. Please check the file path.")
return None
def create_menu_bar():
menu_bar = wx.MenuBar()
# File Menu
file_menu = wx.Menu()
file_menu.Append(w... | The main task of the code is to create a GUI application using wxPython that loads crash statistics data from a CSV file, initializes a menu bar, and displays a home screen for interacting with the dataset. The application sets up a window with global variables for data and UI components, then starts the wxPython main ... | def main():
global app_frame
global accident_data
global left_grid
dataset_path = "Crash Statistics Victoria.csv"
accident_data = load_data(dataset_path)
app = wx.App(False)
app_frame = wx.Frame(None, wx.ID_ANY, "Victoria Dataset App", size=(800, 800))
menu_bar = create_menu_bar()... |
def topBar(self, window):
# Add top bar with file, edit, view, etc.
self.menuBar = tk.Menu(window)
self.fileMenu = tk.Menu(self.menuBar, tearoff=0)
self.fileMenu.add_command(label="Settings", command=self.settingsMenuClick)
self.fileMenu.add_command(label="Open object folder", co... | This code initializes a GUI application for inspecting astronomical light frames. It sets up the window, loads settings, creates UI elements like a top bar and status bar, calculates exposure times from selected dates and paths, and prepares image preview components. The main task is to provide an interface for reviewi... | def __init__(self, objectPath:str, selectedObject:str, selectedDates:list):
super().__init__()
self.settings = Settings()
self.detailsWindow = None
self.imageName = tk.StringVar()
self.showFitDetailChk = tk.IntVar()
self.autostretchImage = tk.IntVar()
self.current... |
def is_collided(self, car_id):
car_borders = self._get_car_borders(car_id)
for b in self.borders:
for c_b in car_borders:
if b.is_crossing(c_b):
return True
return False
def is_collided_with_other_car(self, car_id):
car_borders = self._get_... | This function calculates the reward, done status, and finish information for a car in a reinforcement learning environment. It returns 0 reward and marks the episode as done if already terminated. If the car collides, it gives a -50 penalty and ends the episode. If the car finishes the track, it provides a reward based... | def _get_car_reward_done_info(self, car_id):
if self.dones[car_id]:
return 0, True, {}
finished = False
if self.is_collided(car_id) or self.is_collided_with_other_car(car_id):
reward = -50
done = True
elif self.is_finished(car_id):
reward =... |
def _update_rays(self):
self.rays.clear()
for angle in np.linspace(*self.vision_range, self.rays_count, endpoint=True):
global_angle = self.direction + angle
ray = Border.from_point_angle(self.car_position, global_angle, self.ray_max_distance)
self.rays.append(ray)
de... | The code implements a single step in a reinforcement learning environment, updating the agent's direction and velocity based on the action, calculating new position, checking for collisions or episode termination, computing reward, and returning observations, reward, and done status for the agent's training. | def step(self, action):
angle_change, velocity_change = action['angle_change'], action['velocity_change']
self.steps_count += 1
self.direction += angle_change[0]
self.velocity = np.clip(self.velocity + velocity_change[0], self.min_velocity, self.max_velocity)
direction = np.deg2r... |
def _update_rays(self):
self.rays.clear()
for angle in np.linspace(*self.vision_range, self.rays_count, endpoint=True):
global_angle = self.direction + angle
ray = Border.from_point_angle(self.car_position, global_angle, self.ray_max_distance)
self.rays.append(ray)
de... | The code resets the environment's state for a new episode by initializing the agent's direction, velocity, and position, clearing historical data, generating a new track layout, updating rendering components, and returning the initial observation and environment information. | def reset(self, *, seed=None, options=None):
# Choose the agent's location uniformly at random
self.direction = 0
self.velocity = 10
self.steps_count = 0
self.car_position.fill(0)
self.position_history.clear()
self.borders, self.finish_line, self.turns = generate_... |
def get_leader(self):
return max(self.iterate_agents(), key=lambda i: 0 if self.dones[i] else self.positions[i][0])
def iterate_agents(self):
return (str(i) for i in range(self.cars_number))
def _draw_car(self, car_id, canvas, window_center):
import pygame
car_borders = self._get_car_bor... | The code renders a game frame using Pygame, visualizing the track, finish line, cars, velocities, rewards, and turn angles. It centers the view on the leader car, displays dynamic data like steps, competitor distances, and upcoming turns, and outputs either real-time visuals for human players or saves frames as images ... | def _render_frame(self, obs):
import pygame
assert self.render_mode is not None
canvas = pygame.Surface((self.window_size, self.window_size))
canvas.fill((255, 255, 255))
leader_car_id = self.get_leader()
window_center = self.positions[leader_car_id] - [self.win... |
def make_action(self, action, car_id):
angle_change, velocity_change = action['angle_change'], action['velocity_change']
self.directions[car_id] += angle_change[0]
self.velocities[car_id] = np.clip(self.velocities[car_id] + velocity_change[0], self.min_velocity, self.max_velocity)
... | The main task of the code is to process agent actions, update the environment state, compute rewards and termination conditions for each car, and return the next observation, rewards, termination flags, and additional information. It handles multi-agent step execution, cumulative reward tracking, and environment termin... | def step(self, actions):
self.steps_count += 1
for car_id, action in actions.items():
self.make_action(action, car_id)
rewards, dones, info = {}, {}, {}
for car_id in actions:
rew, dones[car_id], info[car_id] = self._get_car_reward_done_info(car_id)
... |
def generate_start_positions(self):
positions = [np.array([i * 20, 0.0]) for i, _ in enumerate(self.iterate_agents())]
#random.shuffle(positions)
return {i: p for i, p in zip(self.iterate_agents(), positions)}
def iterate_agents(self):
return (str(i) for i in range(self.cars_number))
def... | The code resets the environment by initializing agent positions, directions, velocities, and track elements. It prepares the simulation state, updates car rays, generates the initial observation, and returns it along with environment info for the reset state. | def reset(self, *, seed=None, options=None):
# Choose the agent's location uniformly at random
self.positions = self.generate_start_positions()
self.directions = {i: 0 for i in self.iterate_agents()} # Theta
self.velocities = {i: 1 for i in self.iterate_agents()}
self.rays_list =... |
def _flat_multiquestion(question):
properties = {}
for nested_question in question.questions:
properties.update(build_question_properties(nested_question))
schema_addition = {}
for nested_question in question.questions:
if nested_question.get('followup'):
schema_addition = m... | The function generates a schema for a nested multi-question structure by merging properties and required fields, ensuring no additional properties. It returns a dictionary mapping the question's ID to the constructed schema. | def _nested_multiquestion(question):
properties, schema_addition = _flat_multiquestion(question)
object_schema = merge_schemas({
"type": "object",
"additionalProperties": False,
"properties": properties,
"required": _nested_multiquestion_required(question),
}, schema_additio... |
def load_questions(schema_type, framework_slug, lot_slug):
loader = ContentLoader('./')
loader.load_manifest(
framework_slug,
MANIFESTS[schema_type]['question_set'],
MANIFESTS[schema_type]['manifest']
)
manifest = loader.get_manifest(framework_slug, MANIFESTS[schema_type]['manif... | The function generates a schema by loading and filtering questions, then merging them into an empty schema structure using properties, `anyof` constraints, and dependencies. It returns the finalized schema for a specified type, name, and framework/lot identifiers. | def generate_schema(schema_type, schema_name, framework_slug, lot_slug):
questions = load_questions(schema_type, framework_slug, lot_slug)
drop_non_schema_questions(questions)
schema = empty_schema(schema_name)
schema = build_schema_properties(schema, questions)
schema = merge_schemas(schema, _mult... |
def _dynamic_list(question):
# Some dynamic list questions use `{{ item }}` in temlate fields.
# This call to filter ensures that `item` is in the template context
# (yes, filter() can mutate objects, go figure).
# Replacing `item` with something random shouldn't really matter,
# because we don't ex... | This function processes multi-part questions by converting subquestions into standalone questions. It checks if the input is a dynamic list, handling it via _dynamic_list, otherwise flattens multiquestion structure into property and schema components. Required fields are merged into the schema if present, ensuring vali... | def multiquestion(question):
"""
Moves subquestions of multiquestions into fully fledged questions.
"""
if question._data['type'] == 'dynamic_list':
return _dynamic_list(question)
else:
property_schema, schema_addition = _flat_multiquestion(question)
required_fields = _flat_... |
def remove_duplicates_diag_relevance(ranked_list_2d, n_rows, n_cols):
# from 1D to 2D
mat = np.array(ranked_list_2d).reshape((n_rows, n_cols))
# 1D array ordered by the diagonal heuristic
ranked_list_by_rel = from_mat_diag_relevance_to_1d(mat)
# remove duplicates
_, unique_indices = np.unique... | The function calculates the Normalized Discounted Cumulative Gain (NDCG) for a 2D ranked list of items, comparing it to an ideal scenario. It processes multiple rows of rankings, computes relevance scores, removes duplicates, and normalizes the DCG by the ideal DCG to evaluate the quality of the ranked lists against gr... | def ndcg_2d(ranked_list_2d: list, pos_items: np.ndarray, single_list_len: int, relevance=None, verbose=False):
"""
Calculates the NDCG_2D for the given ranked list of
:param ranked_list_2d: 2D list of item ids ranked, this is the list to evaluate
:param pos_items: array of the relevant item ids (groun... |
def check_popped_status (n):
global goal_found
if point_in_goal(n[5][0], n[5][1]):
goal_node = {"C2G": n[0], "C2C": n[1], "TC": n[2], "node_index": n[3], "parent_coor": n[4], "node_coor": n[5]}
Closed_List.append(goal_node)
print("goal node position:", n[5])
print("target positio... | The code implements a pathfinding algorithm using a priority queue (Open_List) to explore nodes in a map. It processes each node by adding it to the closed list, checks its validity, and generates new nodes in multiple directions (e.g., ±30°, 60°, straight). Each new node is validated against map boundaries, obstacles,... | def exploreNodes():
global goal_found
hq.heapify(Open_List)
while Open_List:
if goal_found:
break
popped_node = hq.heappop(Open_List)
Closed_Coor.add((popped_node[5][0], popped_node[5][1]))
#popped node is checked and added to the closed list as a dic
check_popp... |
def getNewUser(client_socket):
try:
# Receiving our "header" containing message length
message_header = client_socket.recv(HEADER_LENGTH)
# If we received no data client has closed client_socket and we can return false
if not len(message_header):
return False
# ... | The main task of the code is to handle client connections, process user survey responses, determine if a virus test is required based on answers, and route users to a doctor if needed. It manages client interactions, stores user data, and sends appropriate responses while maintaining a loop to receive and process messa... | def clientThread(client_socket, client_address):
new_user = getNewUser(client_socket)
username = new_user['data']
clients[client_socket] = username
print(f"{username} has connected to the server")
#-----------code separates here for doctor and patient -------------------
if username == "Doc... |
def split_array_argument(argument_type: str):
if argument_type.startswith('array'):
von, bis = argument_type.find('<'), argument_type.find('>')
return 'array', argument_type[von+1:bis]
else:
return argument_type, None
def tab(text: str, n_tabs: int, *, tab_first=False):
return '\n'.j... | This function generates C code conditions for handling command-line arguments, including checking argument names/aliases, validating types, and assigning values. It constructs conditional blocks (if/else if) based on argument details like name, alias, default, and type, then formats these into a template for argument p... | def generate_c_handle_command_arguments_condition(command_name, argument_name, argument_details, *, index):
write = 'false' if command_name == '_arguments' else 'true'
argument_alias = argument_details.get('alias')
argument_default = argument_details.get('default')
argument_raw_type = argument_details.... |
def generate_header_extern_functions(commands: dict):
functions = [generate_header_extern_function(command_details) for _, command_details in commands.items()]
return '\n'.join(functions)
def generate_header_declared_help_functions(commands: dict):
functions = [generate_header_declared_help_function(command... | The function generates a header file by combining three components: external function declarations, declared help functions, and declared functions. It uses a template to format these parts into a cohesive header file structure, likely for code generation or API documentation. | def generate_header_file(commands: dict):
extern_functions = generate_header_extern_functions(commands)
declared_help_functions = generate_header_declared_help_functions(commands)
declared_functions = generate_header_declared_functions(commands)
return header_template.format(extern_functions=extern_func... |
def tab(text: str, n_tabs: int, *, tab_first=False):
return '\n'.join([(('\t' * n_tabs) if tab_first or index != 0 else '') + line for index, line in enumerate(text.splitlines())])
def generate_c_handle_command_required_declarations(arguments: dict):
lines = [f'bool is_assigned_{purge_name(argument_name)} = fal... | This function generates C code for handling a command by formatting declarations, conditions, and logic based on provided command details, using a template. It constructs necessary C function components like parameter checks, variable declarations, and execution logic, then assembles them into a structured string for c... | def generate_c_handle_command_function(command_name: str, command_details: dict):
arguments = command_details.get('arguments')
arguments = arguments if arguments is not None else {}
write = 'false' if command_name == '_arguments' else 'true'
required_declarations = tab(generate_c_handle_command_require... |
def chooseWhoYouAre():
print("Who are you? ")
print("1. Customer")
print("2. Admin")
print("3. Exit")
userInput = int(input("What is your choice: "))
return userInput
def CustomerDisplay():
print("Hello Customer, Welcome to CinemaHouseX2")
print("Please select an option from the menu bel... | The main task of the code is to display a welcome message, prompt the user to choose their role (customer or admin), and redirect to corresponding functions based on the input. If invalid input is provided, the program exits. | def InitialDisplay():
print("Hello , Welcome to CinemaHouseX2")
type = chooseWhoYouAre()
if type == 1:
CustomerDisplay()
elif type == 2:
adminDisplay()
else:
exit() |
def parse_heading(self, line):
if line.startswith('#'):
if line.startswith('###'):
self.pdf.set_font(self.font, 'B', self.font_size)
self.pdf.cell(0, 10, txt=line[3:].strip(), ln=1)
elif line.startswith('##'):
self.pdf.set_font(self.font, '... | This code parses markdown content line by line, converting elements like headings, code blocks, commands, LaTeX formulas, and tables into a PDF document. It handles formatting, spacing, and nested structures, using specific parsing methods for each markdown element and adjusting layout with line breaks and image insert... | def parse(self):
lines = self.markdown.splitlines()
while (len(lines) > 0):
line = lines.pop(0).strip()
if line.startswith('#'):
self.parse_heading(line)
elif line.startswith('```'):
codeblock = self.parse_block(lines, '```', '\n')
... |
def readIIDHuman():
"""
Reads ppi from Human IID file in database dir.
Returns list of unique ppi interactions as tuple (src,des).
Removes unwanted PPI between a protein and itself.
"""
filename = './database/human_annotated_PPIs.txt'
logger.info('Reading human PPI from %s. Removing PPI betw... | The code compiles protein-protein interaction (PPI) and transcription factor (TF) interaction data into a unified TSV file for specified species (human/mouse), removing self-interactions. It checks if the output file exists; if not, it reads species-specific interaction data, combines PPI and TF interactions into a Dat... | def getNetworkInteractions(args):
"""
Compiles interactions into one file and stores it in database dir, if needed.
Removes unwanted PPI between a protein and itself.
"""
logger.info('Compiling %s network interactions from data files...',args.s)
#get filepath
if args.s == 'human':
... |
def getNetworkInteractions(args):
"""
Compiles interactions into one file and stores it in database dir, if needed.
Removes unwanted PPI between a protein and itself.
"""
logger.info('Compiling %s network interactions from data files...',args.s)
#get filepath
if args.s == 'human':
... | The main task of the code is to execute a NetResponse analysis by retrieving network interactions, identifying driver genes, intermediates, and responses, then prioritizing these elements using the provided arguments. The function orchestrates these steps sequentially and returns None upon completion. | def runAnalysis(args):
"""
Runs NetResponse analysis
"""
#logger.info('*******************************')
print('*************************************************')
logger.info('Running NetResponse analysis...')
#logger.info('*******************************')
print('**********************... |
def get_master_tracklist(self):
payload = {
"method": "core.tracklist.get_tl_tracks",
"jsonrpc": "2.0",
"id": 101
}
self.write_message(payload)
def cancel_futures(self):
if self.playback_state_future != None:
self.playback_state_future.set_result('STOPPED')... | This function synchronizes with Mopidy via WebSocket, processing events like tracklist changes, playback state updates, and track metadata. It maintains local state by updating tracklists, current tracks, and playback status based on received messages, handling JSON responses to reflect Mopidy's real-time data. It also... | def mopidy_run(self):
logger.debug("mopidy sync start")
self._mopidy_ws_opened = True
self.get_master_tracklist()
while self._mopidy_ws_opened and not self._stop:
logger.debug("mopidy sync read messages")
msg = yield from self.mopidy_ws.read_message()
logger.debug("... |
def skip_whitespace(self):
while self.current_char is not None and self.current_char.isspace():
self.advance()
def string(self):
result = ""
self.advance()
while self.current_char is not None and not self.current_char == '"':
if self.current_char == "\\":
... | This method tokenizes input by identifying and returning specific tokens like strings, boolean values, numbers, and punctuation marks, while skipping whitespace and handling errors for unrecognized characters. | def get_next_token(self):
"""Lexical analyzer
This method splits the input into tokens.
"""
while self.current_char is not None:
if self.current_char.isspace():
self.skip_whitespace()
continue
if self.current_char == '"':
... |
def isConstant(char):
return char.isupper() and len(char) == 1
def isVariable(char):
return char.islower() and len(char) == 1
def checkOccurs(var, exp):
if exp.find(var) == -1:
return False
return True
def fetchInitialPredicate(expression):
return expression.split("(")[0]
def getAttributes(e... | The function `UNIFY(exp1, exp2)` performs unification on two logical expressions. It checks if they are identical, handles constants, variables, and predicates. If expressions are constants and unequal, it returns `False`. For variables, it ensures no cyclic substitution occurs. If predicates mismatch, unification fail... | def UNIFY(exp1, exp2):
if exp1 == exp2:
return []
if isConstant(exp1) and isConstant(exp2):
if exp1 != exp2:
return False
if isConstant(exp1):
return [(exp1,'|', exp2)]
if isConstant(exp2):
return [(exp2,'|', exp1)]
if isVariable(exp1):
if chec... |
def setup_root(self):
root = Tk()
root.geometry(geoString)
root.title(TITLE)
root.iconbitmap(icon_path)
root.resizable(0,0)
return root
def load_data(self):
try:
file = open("assets/text/wordbank.txt","r")
except:
messagebox.shower... | This code initializes a game, likely a word guessing game with a GUI. It sets up the game environment by loading data, initializing sound effects, creating widgets, and configuring game variables like the target word, guesses, and difficulty. It also starts background music and prepares the game state for play. | def __init__(self):
self.root = self.setup_root()
self.load_data = self.load_data()
self.pg = pg
self.sfx_list = []
self.load_sfx()
self.word = ""
self.word_sofar = "?"*len(self.word)
self.guess = ""
self.hint = ""
self.trys = -1
se... |
def backward(X, Y, W1, W2, W3):
m = X.shape[0]
Y_hat,Zs,Hs = forward(X, W1, W2, W3)
Z1,Z2,Z3 = Zs
_,H1,H2 = Hs
Delta3 = Y_hat - Y
Delta2 = np.dot(W3.T, Delta3.T) * sigmoid(Z2) * (1 - sigmoid(Z2))
Delta1 = np.dot(W2.T, Delta2) * sigmoid(Z1) * (1 - sigmoid(Z1))
Grad_W3 = np.dot(Delta3.T,... | This function trains a 3-layer neural network using stochastic gradient descent on given data, initializing weights with Xavier (Glorot) initialization then resetting to zeros. It iteratively updates weights via backpropagation, tracks training/test losses and classification errors, and returns optimized weights along ... | def train(X,y,x_test,y_test,lr=0.0002,batch=128,epochs=150):
w_1 = np.random.randn(300, 784) * np.sqrt(1/784)
w_2 = np.random.randn(200, 300) * np.sqrt(1/300)
w_3 = np.random.randn(10, 200) * np.sqrt(1/200)
#Init weights to zeros
w_1 = np.zeros((300, 784))
w_2 = np.zeros((200, 300))
w_3 =... |
def current_order(msg):
return OPC.find_one({"from_num":msg.fro, "to_num":msg.to})
def pricify(price):
if (price/100).is_integer():
resp = "${price}".format(price=int(price/100))
elif (price/10).is_integer():
resp = "${price}0".format(price=price/100)
else:
resp = "${price}".form... | The main task of the code is to generate a formatted string representing a user's order, including item details, add-ons, and calculated costs. It constructs a summary by iterating through items in the order, appending main item names/prices, nested add-ons, and formatting subtotal, tax, and total costs using the `pric... | def stringify_order(msg):
resp = "YOUR ORDER: "
item_list = current_order(msg)["item_list"]
for item in item_list:
item_str = "\n\n1x {main_name} {main_price} ".format(main_name=item["main_item"]["name"], main_price=pricify(item["main_item"]["base_price"]))
if len(item["main_item"][... |
def generate_unique_id():
# Generate a random 4-digit integer ID
unique_id = random.randint(1000, 9999)
return unique_id
def is_robot_available(robot_name):
#
msg_list = kafka_consumer.get_data_from_kafka_topic(KAFKA_SOURCE_TOPIC_ROBOT)
for obj in msg_list:
value = obj.value().deco... | The main task of the code is to assign a task to a robot if it is available, generate a unique task ID, update the robot's status to "busy," insert task details into a PostgreSQL database, and return a JSON response indicating success or robot unavailability. It processes incoming JSON data, checks robot availability, ... | def process_task():
try:
data = request.get_json()
# Extract data from JSON
task_name = data['task_name']
start_timestamp = data['start_timestamp']
end_timestamp = data['end_timestamp']
robot_name = data['robot_name']
task_id = generate_unique_id()
... |
def ALU(x, y, zx, nx, zy, ny, f, no):
# // -----
#
# Mux16(a=x, b=false, sel=zx, out=XafterZX); // if (zx == 1) set x = 0
if zx == 1:
zx = -1
XafterZX = Mux16(x, 0, zx)
# // -----
# Not16( in = XafterZX, out = Notx); // flips x = > Notx
Notx = Not16(XafterZX)
# Mux16(a=Xafte... | This code implements an extended ALU that performs regular or extended operations based on instruction bits. It computes outputs using ALU flags, shifts data left/right, selects results via multiplexers, and determines zero (zr) and negative (ng) flags from the output. | def Extended_ALU(x, y, instruction):
bin_instruction = numTo16Bit(instruction)[-9:]
# And(a=instruction[8], b=instruction[7], out=isRegularOut); // check if needed a regular or extended use
# ALU(x=x, y=y, zx=instruction[5], nx=instruction[4], zy=instruction[3], ny=instruction[2], f=instruction[1],
# ... |
def getBuySellSignals(returns,shortRange,longRange,upperPRange,lowerPRange):
lowerSignals, upperSignals=getSignals(returns,shortRange,longRange,upperPRange,lowerPRange)
return mergeSignals(lowerSignals,upperSignals)
def train(trainingSet,buySellSignals):
index=len(trainingSet)
rows=[]
for sig in buy... | The function generates trading signals based on price changes and specified ranges, splits data into training/test sets, evaluates strategy performance, and returns metrics including training/test returns, benchmarks, and volatility measures for a given trading strategy. | def strategy(pSeries,trainingSize,shortRange,longRange,upperPRange,lowerPRange):
returns=pSeries.pct_change()
buySellSignals=getBuySellSignals(returns,shortRange,longRange,upperPRange,lowerPRange)
trainingCutoff=int(len(pSeries)*trainingSize)
trainingSet=returns[:trainingCutoff]
testSet=returns... |
def _getsrcDest(self, edge: tuple) -> tuple:
"""to get src and dest points for edge"""
graph = self.graphAlgo.get_graph()
src = next(n for n in graph.get_dicNodes().values() if n.get_id() == edge[0])
dest = next(n for n in graph.get_dicNodes().values() if n.get_id() == edge[1])
... | The function `_drawPath` visualizes a TSP (Traveling Salesman Problem) path or shortest path by drawing directed lines and arrows between consecutive points in the provided `path` list. It iterates through each pair of points, retrieves their coordinates, and renders a line with an arrowhead to indicate direction. The ... | def _drawPath(self, path) -> None:
"""to draw TSP path/shortestPath"""
if path is None:
return
i = 0
l = len(path)
while i + 1 < l:
p1 = path[i]
p2 = path[i + 1]
# find the edge nodes
src_x, src_y, dest_x, dest_y = self.... |
def _getsrcDest(self, edge: tuple) -> tuple:
"""to get src and dest points for edge"""
graph = self.graphAlgo.get_graph()
src = next(n for n in graph.get_dicNodes().values() if n.get_id() == edge[0])
dest = next(n for n in graph.get_dicNodes().values() if n.get_id() == edge[1])
... | The main task of the code is to render a graph's nodes and edges on a screen. It draws edges as lines with arrowheads, scales node positions, renders nodes as circles with IDs, and visualizes specific paths (SP/TSP). The function handles coordinate scaling, color formatting, and graphical elements like filled circles, ... | def _drawGraph(self) -> None:
"""draw all nodes and edges"""
graph = self.graphAlgo.get_graph()
for k in graph.get_dicEdges().keys():
src_x, src_y, dest_x, dest_y = self._getsrcDest(k)
# draw the line
p = np.subtract((dest_x, dest_y), segment((src_x, src_y), (... |
def _setCenter(self, id=None) -> None:
self._update()
if id is None:
mb.showerror("ERROR", "The Graph is not connected")
return
self.GC = id
def _selectTSP(self)->None:
"""open dialog window to ask TSP"""
self._update()
window = tk.Tk()
win... | This code initializes a graphical interface for visualizing graph algorithms using Pygame. It sets up a resizable window, creates a menu bar with options to load/save graphs, compute centers, and run shortest path/TSP algorithms. The main loop renders the graph, handles user interactions, and updates the display in rea... | def __init__(self, graphAlgo: GraphAlgoInterface) -> None:
self.graphAlgo = graphAlgo
WIDTH, HEIGHT = 1080, 720
self.screen = display.set_mode((WIDTH, HEIGHT), depth=32, flags=RESIZABLE)
self.GC = None
self.SP = None
self.TSP = None
clock = pg.time.Clock()
... |
def _make_text_dataset(use_full_dataset=False):
if use_full_dataset:
neg_path = constants.NEG_PATH_FULL
pos_path = constants.POS_PATH_FULL
print("Loading full dataset...")
else:
neg_path = constants.NEG_PATH
pos_path = constants.POS_PATH
print("Loading partial da... | The code creates a text dataset, reduces Stanford GloVe embeddings to top 20k words, generates train/test indices, and saves datasets, embeddings, and tweet length statistics. It processes tweets by capping vocabulary size, handling padding/unknown tokens, and visualizing length distribution for NLP tasks. | def make_dataset(use_full_dataset=True):
# Make txt dataset
txt_dataset = _make_text_dataset(use_full_dataset=use_full_dataset)
# Load full stanford embedding from file
stanford = pickle.load(open(constants.GLOVE_EMBEDDING_STANFORD_PATH, "rb"))
# Create vocabulary, cut at top 20k words
wor... |
def display_temp():
print("Temp is {}".format(Temp))
mylcd.lcd_clear()
mylcd.lcd_display_string(" IncuBetter",1)
mylcd.lcd_display_string("Temp: %s" %Temp,2)
def display_time():
print("Time is {}".format(Time))
mylcd.lcd_clear()
mylcd.lcd_display_string(" IncuBetter",1)
mylcd.lcd_dis... | The main task of the code is to manage a state-driven control system for a device (likely an incubator/heater). It continuously checks the current state, executes corresponding actions like displaying temperature/time, starting heater threads, capturing images, or updating LCD screens, and transitions between states (e... | def main():
while True:
if Current_state == States.SET_TEMP:
display_temp()
elif Current_state == States.SET_TIME:
thread_1 = threading.Thread(target=heater, args=())
thread_1.start()
display_time()
elif Current_state == States.SET_INTERV... |
def calc_crc32( fn ):
with open( fn, 'rb' ) as f:
return ( binascii.crc32( f.read()) & 0xFFFFFFFF )
def monitor( st ):
return execute( 'monitor ' + st )
def mem32( addr ):
ret = execute( 'x ' + str( addr ))
try:
return long( ret.splitlines()[ 0 ].split( ':' )[ -1 ].strip(), 16 )
exc... | The main task of the code is to program a microcontroller's EEPROM with a binary file, converting ELF files to BIN if needed. It verifies existing EEPROM content, erases it, writes the binary in blocks using a loader, checks for errors, and optionally writes a CRC-32 checksum. The process includes MCU identification, l... | def program( binary ):
log.info( '%s %s', APP, VERSION )
p, e = os.path.splitext( binary )
if e == '.elf':
log.info( 'ELF to binary converting...' )
elf = binary
binary = p + '.bin'
os.system( '%s -O binary %s %s' % ( OBJCOPY, elf, binary ))
if not os.path.exists( binar... |
def execute( st ):
return gdb.execute( st, to_string=True )
def program( binary ):
log.info( '%s %s', APP, VERSION )
p, e = os.path.splitext( binary )
if e == '.elf':
log.info( 'ELF to binary converting...' )
elf = binary
binary = p + '.bin'
os.system( '%s -O binary %s %... | The code connects to a J-Link GDB Server, programs a specified binary, and monitors execution. It logs status to stdout, handles connection failures by returning False, and cleans up logging handlers. If successful, it executes the programmed binary and returns the result. | def program_from_shell( binary ):
# Output log to stdout
h = logging.StreamHandler( sys.stdout )
h.setFormatter( logging.Formatter( LOG_FORMAT, LOG_TIME ))
log.addHandler( h )
execute( 'set pagination off' )
log.info( 'J-Link GDB Server connecting...' )
try:
execute( 'target remote... |
def fw(sw):
swn = get_swn(sw)
if sw <= S_wr:
return 0.0
if sw >= 1 - S_or:
return 1.0
return lambda_w(swn) / (lambda_w(swn) + lambda_o(swn))
def k_rw(sw_n):
# if np.abs(sw_n - (1 - S_or)) < 0.0001:
# return krw_st
return krw_st * (sw_n ** n_w)
def get_swn(sw):
return ... | The code computes and visualizes fluid flow characteristics in porous media. It generates saturation values (sw), plots fractional flow (fw) and relative permeability (k_rw, k_ro) curves, calculates the shock front saturation (swf), and computes an analytical solution (res) for each saturation using a step size. The re... | def solve_analytical():
sw = np.linspace(S_wr, 1-S_or, 101)
print(f"{sw=}")
plt.plot(sw, [fw(sw_) for sw_ in sw])
plt.show()
plt.plot(sw, [k_rw(get_swn(sw_)) for sw_ in sw])
plt.plot(sw, [k_ro(get_swn(sw_)) for sw_ in sw])
plt.show()
# print(f"{sw=}")
swf = find_s_star()[0]
pri... |
def tune_hyperparameters(self, method='xgboost'):
trials = Trials()
optimal_hyperparameters = fmin(fn = self.methods[method],
space = self.xgb_config,
algo = tpe.suggest,
max_evals = 100,
trials = trials)
... | The code trains and evaluates multiple machine learning models (XGBoost, AdaBoost, Bagging, Random Forest) by tuning hyperparameters, computes their best accuracies, generates a feature importance plot using Random Forest, and returns the accuracies for comparison. | def train(self, method='xgboost'):
print('...Training xgboost...')
self.tune_hyperparameters(method)
xgb_best_accuracy = self.xgb_accuracy
adaboost_best_accuracy = self.adaboost()
bagging_best_accuracy = self.bagging()
randomForest_best_accuracy, rf_model = self.randomFor... |
def five_crop(img, size):
if isinstance(size, numbers.Number):
size = (int(size), int(size))
else:
assert len(size) == 2, "Please provide only two dimensions (h, w) for size."
w, h = img.size
crop_h, crop_w = size
if crop_w > w or crop_h > h:
raise ValueError("Requested crop... | The function generates ten cropped versions of an image by first creating five crops from the original image and then creating another five crops from the image flipped either vertically (if specified) or horizontally. The cropped images are concatenated and returned as a single list. | def ten_crop(img, size, vertical_flip=False):
if isinstance(size, numbers.Number):
size = (int(size), int(size))
else:
assert len(size) == 2, "Please provide only two dimensions (h, w) for size."
first_five = five_crop(img, size)
if vertical_flip:
img = vflip(img)
else:
... |
def _get_num_train_samples(self):
return integer_floor(self.train_ratio * self._get_num_samples())
def _get_num_test_samples(self):
return self._get_num_samples() - self._get_num_train_samples()
def get_num_labels(self):
return len(self._get_label_list()) | The code defines the `__repr__` method to return a string representation of an object, displaying its class name and key statistics: number of training samples, test samples, and labels. This aids in debugging or logging by providing a concise summary of the object's state. | def __repr__(self):
return self.__class__.__name__ + \
f"(n_train_samples: {self._get_num_train_samples()}, " \
f"n_test_samples: {self._get_num_test_samples()}, " \
f"n_labels: {self.get_num_labels()})" |
def config(self):
params = {"JVMRoute": self.uuid,
"Host": self.host,
"Port": self.port,
"StickySessionForce": self.StickySessionForce,
"Type": self.Type
}
data = urllib.parse.urlencode(params)
r = reques... | The code's main task is to continuously monitor and maintain a service by looping while `_runFlag` is active. It checks configuration settings, prints cluster details, enables contexts, and periodically updates status. The loop handles exceptions gracefully, ensuring the service remains operational by sleeping and rech... | def _loop(self):
while self._runFlag:
try:
if self.config():
print("configured modculster, uuid:%s, apache addr: %s, my addr: %s:%s." % (
self.uuid, self.AdvertiseUrl, self.host, self.port))
self._enablecontexts()
... |
def get_description(self):
'''
Get expense description from console
:return: string
'''
print("Enter the expense description (i.e. Restaurant payment)")
description = input()
description = description.strip()
if description:
return description... | The main task of the code is to collect user input for an expense, including description, amount, and category, then return them as a dictionary with today's date added. The function aggregates data from three helper methods and formats the current date as 'YYYY-MM-DD' before returning the structured expense informatio... | def get_input(self):
'''
Get user input from console and return as dict
:return: dict - New expense info
'''
data = {}
data["description"] = self.get_description()
data["amount"] = self.get_amount()
data["category"] = self.get_category()
data["dat... |
def choose_model(content, json_mode=False):
tokens = count_tokens(content)
prompt_start = " ".join(content.split(" ")[:200])
difficulty = estimate_prompt_difficulty(prompt_start)
if not difficulty:
return 'llama3', tokens, difficulty
if difficulty == "easy":
if tokens < 8000 and not... | The main task of the code is to query AI models (e.g., Gemini, Llama3, GPT variants) with given content, manage token limits by truncating inputs if needed, and return responses. It selects a model, checks token counts, truncates content if exceeding thresholds, logs details, and retries with alternative models on fail... | def ask_ai(content, system_role=None, model=False, json_mode=False):
if not model:
model, tokens, difficulty = choose_model(content, json_mode)
else:
tokens = count_tokens(content)
difficulty = None
if tokens > 100000 or (tokens > 10000 and DEBUG):
if prompt(f"The prompt leng... |
def choose_model(self, content, json_mode=False):
"""
Chooses the appropriate language model based on the content and estimated prompt difficulty.
Args:
content (str): The content of the prompt.
json_mode (bool, optional): Indicates whether the output should be in JSON f... | This function routes a query to the most suitable AI model (e.g., Gemini, Llama3, GPT variants) based on input content and parameters. It handles token limit checks, model selection, and response handling, returning the AI's output or False on failure. | def ask(self, content, system_role=None, model="", json_mode=False):
"""
Sends a query to the best fitting AI model and returns the response.
Args:
content (str): The input content or prompt for the AI model.
system_role (str, optional): The system role for the AI model.... |
def preprocess(self):
## INIT ##
self.appData.db_controller.pull(self.appData)
all_courses = self.appData.local
all_courses_objects = []
for document in all_courses:
course = course_class.Course(document)
if course not in all_courses_objects:
... | The main task of the code is to execute a preprocessing step (if required by mode settings), perform optimization, and conclude with the best result. It checks global mode flags to determine data collection behavior, runs preprocessing (showing errors if failed), sets a preprocessing flag, executes optimization, and re... | def run(self):
global PRE_PROCESS,STATISTICS_MODE
status = 0
msg = ""
if (STATISTICS_MODE and not PRE_PROCESS) or not STATISTICS_MODE:
gui.print_title("System collecting data ... please wait")
status,msg = self.preprocess()
if status == 0:
... |
def build_hyperparameter_dict(flags):
"""Simple script for saving hyper parameters. Under the hood the
flags structure isn't a dictionary, so it has to be simplified since we
want to be able to view file as text.
Args:
flags: From tf.app.flags
Returns:
dictionary of hyper parameters (ignoring other... | The main task of the code is to execute various model operations (training, sampling, parameter writing) based on the specified `kind` flag. It loads datasets, configures hyperparameters, sets up a TensorFlow session, and dispatches to corresponding functions (`train`, `write_model_runs`, etc.) to perform the requested... | def main(_):
"""Get this whole shindig off the ground."""
d = build_hyperparameter_dict(FLAGS)
hps = hps_dict_to_obj(d) # hyper parameters
kind = FLAGS.kind
# Read the data, if necessary.
train_set = valid_set = None
if kind in ["train", "posterior_sample_and_average", "posterior_push_mean",
... |
def initialize_with_zeros(dim):
"""
This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.
Argument:
dim -- size of the w vector we want (or number of parameters in this case)
Returns:
w -- initialized vector of shape (dim, 1)
b -- initialized scala... | The code implements a logistic regression model by initializing parameters, performing gradient descent optimization on training data, predicting class labels for both training and test sets, calculating accuracy, and returning a dictionary containing model parameters, costs, and evaluation metrics. | def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, step = 100, print_cost = False):
"""
Builds the logistic regression model by calling the function you've implemented previously
Arguments:
X_train -- training set represented by a numpy array of shape (num_px * ... |
def sigmoid(z):
"""
Compute the sigmoid of z
Arguments:
z -- A scalar or numpy array of any size.
Return:
s -- sigmoid(z)
"""
s = 1. / ( 1 + np.exp(-z))
return s
def initialize_with_zeros(dim):
"""
This function creates a vector of zeros of shape (dim, 1) for w and in... | The code tests a logistic regression implementation by initializing parameters, computing gradients and cost, optimizing them via gradient descent, and evaluating predictions. It verifies the correctness of functions like `sigmoid`, `initialize_with_zeros`, `propagate`, `optimize`, and `predict` using sample data and p... | def test_run():
print ("sigmoid([0, 2]) = " + str(sigmoid(np.array([0,2]))))
dim = 2
w, b = initialize_with_zeros(dim)
print ("w = " + str(w))
print ("b = " + str(b))
w, b, X, Y = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]), np.array([[1,0]])
grads, cost = propagate(w, b, X, Y)
prin... |
def rot_trans_ads(ads, normal, coordinate, h):
"""
Function to rotate the CO molecules along the normal and translate it to the adsorption site
ads = adsorabate molecule
normal = normal to the site to rotate molecule there
coordinate = coodinates of site
h = height of the adsorbing molecule
... | The code generates all possible CO adsorption configurations on symmetric surface sites of a slab, varying coverage between `min_nCO` and `nCO`. It filters out invalid structures (e.g., invalid bond distances, proximity to steps) by checking neighbor interactions and removing problematic sites. Valid configurations are... | def gen_struc(slab, nCO, min_nCO, surf_ndx, island_ndx, trajw):
"""
Function that generates all the possible orderings of CO on various symmetric sites for coverage between [min_nCO and nCO]
"""
bond_range={}
for v in itertools.product(['Pt', 'C', 'O'], repeat=2):
bond_range[v]=[1,10]
# ... |
def openWorkbook():
copyPath = f'c:\\Users\\rlars\Desktop\Knights Baseball\Hitter Chase Report\Hitter Chase Template.xlsx'
wb = load_workbook(copyPath)
return wb.active, wb
def getChaseRate(typePitch, allPitches):
typePitches = [tup for tup in allPitches if getTypePitch(typePitch, tup)]
earlyPitche... | The code writes player data into an Excel workbook, populates specific cells with chase rate statistics for different pitch types (Fastball, Offspeed), and saves the workbook. It uses dictionaries to map pitch types to cell locations, calculates chase rates using helper functions, and adds strike zone data. The main ta... | def writeWorkbook(player, allPitches):
sheet, wb = openWorkbook()
sheet[f'D8'] = player.split(',')[0]
pitchTypes = {'Fastball': 'H33', 'Offspeed': 'O33'}
pitchTypes2k = {'Fastball': 'H36', 'Offspeed': 'O36'}
for typePitch in pitchTypes:
sheet[pitchTypes[typePitch]] = getChaseRate(typePitc... |
def addStrikeZone(imgCount, dbName, player, gamedate, allPitches, sheet, i, tableName, autoTagPitchType):
img = drawStrikezoneFigure(dbName, player, gamedate, tableName, autoTagPitchType, inning=allPitches[i][7], AB=allPitches[i][8])
sheet.add_image(img, f'B{imgCount}')
if imgCount == 1:
imgCount +=... | This function processes pitch data from a database for a specific player and game date, grouping pitches by at-bats. It iterates through fetched records, adjusting counters and calling helper functions to add strike zone visuals, pitch data columns, and layout elements to a spreadsheet. The logic manages batch processi... | def writeAB(abVars, player, gamedate, sheet, cur, dbName, tableName, autoTagPitchType):
cur.execute(f'SELECT {abVars} FROM {tableName} WHERE hitter = ? AND date = ?' , (player, gamedate))
allPitches = cur.fetchall()
count = 10
abCount = 1
num = allPitches[0][0]
imgCount = 1
SynCount = 1... |
def getAllPitches(player):
cur, con = openDatabase()
tableNames = ['June17vYakimaValley', 'June18vYakimaValley', 'June19vYakimaValley', 'June21vWallaWalla', 'June22vWallaWalla', 'June23vWallaWalla', 'June24vBellingham', 'June25vBellingham', 'June26vBellingham', 'June28vSpringfield', 'June29vSpringfield', 'June3... | The main task of the code is to process a list of baseball players by retrieving their pitch data, writing it into a workbook file, and printing the workbook. The function iterates through each player's name, fetches their pitches using `getAllPitches`, saves the data with `writeWorkbook`, and outputs the workbook's pa... | def main():
players = ['Johnstone, Logan', 'Scott, Spencer', 'Advincula, Jonah', 'Kennel, Ely',
'Le, Mason', 'Darby, Zander', 'Lavoie, Brady', 'Dumitru, Titus', 'Quinn, Tyler', 'Romero, Kiko',
'Loveless, Ethan', 'Casperson, Kyle', 'Leitgeb, Jake', 'Becerra, Temo', 'Knight, Briley', 'DiPaolo, Luca']
... |
def openHitterWorkbook(copy = 'Knights Hitter Postgame Template 2.0.xlsx'):
copyPath = f'c:\\Users\\rlars\Desktop\Knights Baseball\Postgame Reports\Templates\{copy}'
wb = load_workbook(copyPath)
return wb.active, wb
def openDatabase(name):
path = "c:\\Users\\rlars\Desktop\Knights Baseball\Postgame Repor... | The main task of the code is to generate a player's baseball report by pulling data from a database and populating an Excel sheet with structured sections (headers, pitch details, at-bats). It formats the workbook, sets print areas, saves the file, and returns the player's name in last-name-first-name format. | def writePlayerReport(dbName, player, gamedate, opponent, tableName, autoTagPitchType):
sheet, wb = openHitterWorkbook()
cur, con = openDatabase(dbName)
saveWorkbookHitter(wb, gamedate, player)
headerVars = 'pitchNum,hitter,date'
writeHeader(headerVars, player, sheet, cur, opponent, tableName)
... |
def getPitchTypeInfo(dbName, pitcher, date, tableName, autoTagPitchType, inning = ''):
pitchTypeInfo = {}
allPitches = getPitcherPitches(dbName, pitcher, date, tableName, autoTagPitchType, inning)
sortedAllPitches = sorted(allPitches, key= lambda tup : tup[7])
pitchTypeInfo['all'] = {'maxVelo' : 0, 've... | This function writes detailed pitch statistics into an Excel sheet, including velocity, break data, usage rates, and performance metrics for each pitch type. It formats cells with colors, handles division errors, and adds charts and sequences. The data is sourced from a database, structured into columns, and includes b... | def writeOverall(sheet, dbName, pitcher, tableName, date, autoTagPitchType):
pitchTypeInfo = getPitchTypeInfo(dbName, pitcher, date, tableName, autoTagPitchType)
sortPitches, totalUsage = sortPitchTypeInfo(pitchTypeInfo)
pitchTypeDic = {'Fastball' : ('FB', 'Red', '00FF0000') , 'Four-Seam': ('FB', 'Red', '00... |
def getPitchTypeInfo(dbName, pitcher, date, tableName, autoTagPitchType, inning = ''):
pitchTypeInfo = {}
allPitches = getPitcherPitches(dbName, pitcher, date, tableName, autoTagPitchType, inning)
sortedAllPitches = sorted(allPitches, key= lambda tup : tup[7])
pitchTypeInfo['all'] = {'maxVelo' : 0, 've... | The function `writeInnings` populates an Excel sheet with detailed pitch statistics for a specific pitcher's inning. It retrieves and sorts pitch data, maps pitch types to formatting rules, writes metrics like velocity, break, usage, and strike rates into designated columns, handles division errors, applies cell colors... | def writeInnings(sheet, dbName, pitcher, inning, inningCount, tableName, date, autoTagPitchType):
pitchTypeInfo = getPitchTypeInfo(dbName, pitcher, date, tableName, autoTagPitchType, inning)
sortPitches, totalUsage = sortPitchTypeInfo(pitchTypeInfo)
pitchTypeDic = {'Fastball' : ('FB', 'Red', '00FF0000') , '... |
def openPitcherWorkbook(copy = 'Knights Pitcher Postgame Template Copy.xlsx'):
copyPath = f'c:\\Users\\rlars\Desktop\Knights Baseball\Postgame Reports\Templates\{copy}'
wb = load_workbook(copyPath)
return wb.active, wb
def getInningsPitched(dbName, pitcher, date, tableName, autoTagPitchType):
allPitches... | This function generates a detailed pitcher performance report by retrieving pitch data, writing overall statistics, inning-by-inning breakdowns, and strike zone visuals into an Excel sheet. It handles potential name mismatches via error handling, adjusts print areas dynamically, and saves the workbook with formatted ou... | def writePitcherReport(dbName, pitcher, date, tableName, opponent, autoTagPitchType):
sheet, wb = openPitcherWorkbook()
try:
innings = getInningsPitched(dbName, pitcher, date, tableName, autoTagPitchType)
writeOverall(sheet, dbName, pitcher, tableName, date, autoTagPitchType)
writeHeade... |
def writeDatabase(name, tableName, path, aX = adjustmentX, aY = adjustmentY):
cur, con = openDatabase(name)
atBats = getAtBats(path)
indexDic = getIndex(path)
cur.execute(f'''CREATE TABLE IF NOT EXISTS {tableName} (pitchNum INTEGER PRIMARY KEY, date TEXT, time TEXT, ab INTEGER, paInning INTEGER, pitchP... | The main task of the code is to generate and send baseball player and pitcher reports by writing data to a database, processing lineup and pitcher inputs, handling errors, and automating window management. It writes hitter/pitcher reports, sends them via functions, closes plots, and uses keyboard shortcuts for window c... | def main(lineup, dbName, gamedate, opponent, tableName, pitchers, autoTagPitchType, path, aX = adjustmentX, aY = adjustmentY):
try:
writeDatabase(dbName, tableName, path, aX, aY)
print('...writing database...')
except sqlite3.IntegrityError:
print('...database already written...')
if... |
def generate_A_Y(num_advantaged=num_advantaged, num_disadvantaged=num_disadvantaged):
num_samples = num_advantaged + num_disadvantaged
Y = np.random.randint(2, size=num_samples)
A = np.array([1]*num_advantaged + [0]*num_disadvantaged)
'''
group 2a + y
a=0, y=0 0
a=0, y=1 1
a=1... | The code generates a synthetic dataset with features X (combining a noisy oracle signal and Gaussian noise), labels Y, group information A, and a function to plot the optimal fair classifier boundary. It constructs X by stacking noisy oracle outputs (x1) and random noise (x2), then defines a visualization function to i... | def dataset_2(num_advantaged=num_advantaged, num_disadvantaged=num_disadvantaged):
'''
x1: noisy oracle
x2: random noise
'''
A, Y, g, g_labels = generate_A_Y(num_advantaged=num_advantaged, num_disadvantaged=num_disadvantaged)
bias = 3
x1 = noisy_oracle(Y, bias, 0.25)
x2 = gaussian_noise(... |
def generate_A_Y(num_advantaged=num_advantaged, num_disadvantaged=num_disadvantaged):
num_samples = num_advantaged + num_disadvantaged
Y = np.random.randint(2, size=num_samples)
A = np.array([1]*num_advantaged + [0]*num_disadvantaged)
'''
group 2a + y
a=0, y=0 0
a=0, y=1 1
a=1... | The code generates a synthetic dataset with features (noisy oracle and proxy), labels (Y), and sensitive attributes (A), while defining a function to plot the optimal fair classifier boundary. It creates two noisy variables (x1, x2) from Y and A, stacks them into a feature matrix X, and returns X, Y, A, and the plottin... | def dataset_3(num_advantaged=num_advantaged, num_disadvantaged=num_disadvantaged):
'''
x1: noisy oracle
x2: noisy proxy
'''
A, Y, g, g_labels = generate_A_Y(num_advantaged=num_advantaged, num_disadvantaged=num_disadvantaged)
bias = 3
x1 = noisy_oracle(Y, bias, 0.25)
x2 = noisy_proxy(A, b... |
def generate_A_Y(num_advantaged=num_advantaged, num_disadvantaged=num_disadvantaged):
num_samples = num_advantaged + num_disadvantaged
Y = np.random.randint(2, size=num_samples)
A = np.array([1]*num_advantaged + [0]*num_disadvantaged)
'''
group 2a + y
a=0, y=0 0
a=0, y=1 1
a=1... | The main task of the code is to generate a synthetic dataset with features x1 (noisy oracle) and x2 (sensitive biased feature), normalized and scaled for analysis. It includes optional histogram visualization of x2 across sensitive groups (A) and outcomes (Y), and returns the dataset along with a function to plot the o... | def dataset_4(num_advantaged=num_advantaged, num_disadvantaged=num_disadvantaged, plt_hist=False):
'''
x1: noisy oracle
x2: sensitive bias feature
'''
A, Y, g, g_labels = generate_A_Y(num_advantaged=num_advantaged, num_disadvantaged=num_disadvantaged)
x2 = sensitive_feature_biased(A, Y, 7, 6.5, ... |
def rowAndColToPiece(self, here):
'''takes tuple of (row,col), returns piece(obj)'''
#returns piece
return self.board[here[0]][here[1]]
def orderPositions(self, place, listOfPlaces):
'''takes a position and a list, returns dictionary of list split in two where place was
removes p... | The function `canMove` determines valid moves for a chess piece at a given position, considering obstacles, piece-specific rules (e.g., pawns, knights), and king safety. It checks possible moves, filters out paths blocked by other pieces, handles en passant and castling for pawns/kings, and ensures moves do not expose ... | def canMove(self, here, turnCount = 0.0):
'''takes location (row,col), checks if the possibilities for moves is not empty, returns list of possible coords'''
#Iterate through all the places on the board and keeps the valid positions
#get moved piece
piece = self.rowAndColToPiece(here)
... |
def getHereCoordinates(self, whiteTurn, board):
'''gets input from user (certain to be a piece that belongs to user)
updates self.thereCoordinates into a tuple of (row,col)
'''
#choose valid coordinates
wrongChoice = True
while wrongChoice:
self.... | This code implements a text-based chess game, handling player turns, move validation, check/checkmate detection, stalemate conditions, and game statistics. It allows users to move pieces, tracks captured pieces, en passant, and checks for threefold repetition. The game loops until checkmate, stalemate, or 50 moves with... | def __init__(self):
print('\nWelcome to Chess')
playAgain = True
while playAgain:
#setup board
self.board = Board()
#setup player's turn
self.whiteTurn = True
self.coordinates = ''
self.gotChecked = False
... |
def filepath(self, filepath_):
''' Set upload filepath '''
self.__filepath = filepath_
self.__fullkey = self._fullkey(filepath_)
self.__check_level = self._key_level(self.__fullkey)
def cleanup(self):
''' Delete old backups in S3 '''
if self.delete == False:
r... | The main task of the code is to perform a backup operation by setting the file path, cleaning up existing data, and uploading the file in a single method. It combines three steps—filepath assignment, cleanup, and upload—into a streamlined backup process. | def backup(self, filepath):
''' Group cleanup and upload in one method '''
self.filepath(filepath)
self.cleanup()
self.upload() |
def get_all_xml_files(filename):
abs_path = os.path.abspath(filename);
return [file for file in os.listdir(abs_path) if file.split(".")[1] =="xml"]
def write_to_file(output , data):
f= open(output , "a")
f.write(data);
f.close()
def parseXML(xmlfile):
info = {}
# create element tree ob... | The code processes XML files from a given directory, extracts data (filename, image dimensions, class labels, and bounding box coordinates), and writes this information into a CSV file. Its main task is to convert XML annotations into a structured CSV format, likely for use in machine learning or object detection tasks... | def process(dir):
files = get_all_xml_files(dir);
write_to_file(OUT_FILE , "filename,width,height,class,xmin,ymin,xmax,ymax\n");
for file in files:
result = parseXML(dir+file);
write_to_file(OUT_FILE , result); |
def parents_choice(population, graph):
p = P(population, graph)
s = 0
for i in range(len(p)):
s += p[i]
if probability(s, 0, len(population) - 1):
first_parent = population[i]
break
s = 0
for i in range(len(p)):
s += p[i]
if probability(s, 0, l... | The main task of the code is to generate a new population in a genetic algorithm by selecting parent pairs, performing crossover to create offspring, and applying mutations to all individuals in the new population based on a given mutation probability. The process involves iterating through half the original population... | def new_population(population, probability_mutation):
new_population = []
for i in range(int(len(population) / 2)):
parents = parents_choice(population, graph)
descendants = crossing(parents[0], parents[1])
new_population.append(descendants[0])
new_population.append(descendants[... |
def controller(self):
v = 5 # Moving 1m/sec
# w = pi/4 # Rotating at (pi/2) rad/sec]
w = pi/2
xPrior = self.state
self.state = self.sample_motion_model_velocity([v,w], xPrior)
self.prevStates.append(xPrior) # Only storing after we have left that state.
# Let's al... | The main task of the code is to animate a bot's movement and particle filter updates. It clears previous plots, updates the bot's position via `controller()`, manages particle prediction with `updateParticles()`, handles time-based events like bot stealing, and redraws the bot, particles, sensor data, and time text for... | def animate(self, i=None):
# Clearing what we previously had
self.bots = [] # For plotting bot
self.sensors = [] # For plotting sensors
self.particleHeadings = [] # Fpr plotting the particle headings
self.line.set_data([],[]) # Fo... |
def controller(self):
v = 5 # Moving 1m/sec
# w = pi/4 # Rotating at (pi/2) rad/sec]
w = pi/2
xPrior = self.state
self.state = self.sample_motion_model_velocity([v,w], xPrior)
self.prevStates.append(xPrior) # Only storing after we have left that state.
# Let's al... | The code's main task is to control a system by updating particle states based on time thresholds and triggering a bot-stealing action at a specified time. It checks if the elapsed measurement time exceeds an update delay to refresh particles, otherwise increments the time. If the bot-stealing flag is active and the cur... | def run(self):
"""
Use this code to run without matplotlib animations.
"""
self.controller()
if self.measureTime > self.updateDelay:
self.updateParticles()
else:
self.measureTime += self.dt
if self.botSteal and self.ti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.