dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_view(data, fname):
# By default treat each new file as a view
view = model['views']
atts, new_views, attr_paths = check_attributes(data)
if atts:
model['order'].append(fname)
view[fname] = { 'label': fname, 'attributes': atts }
create_definitions(atts)
return new_views, attr_paths
def ... | The code processes input files or directories to generate a structured model by creating views, attributes, and parameters from the data. It adjusts the model's order, prioritizing 'Core' if present, and exports the final model as a JSON file in the specified output directory. | def cli(output, directory, file):
"""Accepts a single file, list of files, or directory name."""
files = Path(directory).iterdir() if directory else [Path(f) for f in file]
for f in files:
# Create the views, attributes, and parameters needed
# for each file
fname = f.stem.capitalize()
with open(... |
def display_image(image):
'''Display the provided image in the notebook interface.
This function takes an OpenCV image, converts it to the JPEG format,
and then displays it directly within the Jupyter Notebook or IPython environment.
Args:
image: The input image represented as a numpy array in... | The function converts a chessboard image to a Lichess analysis link by detecting pieces, generating a FEN representation, and creating a URL. It also returns Base64-encoded images of the cropped chessboard and detected pieces. | def image_to_lichess(image_path):
'''
Convert an image of a chessboard to a Lichess board analysis link.
This function reads an image of a chessboard, detects the pieces on it,
converts the detections to a Forsyth-Edwards Notation (FEN) representation,
and then opens a Lichess board analysis p... |
def extract_host(host):
host = re.sub("[<>*]", "", host)
if "|" in host:
host = host.split("|")[1]
if "http" in host:
host = host.split("//")[1]
return host
def uptimecheck_info_msg(text):
uptimecheck_infos = uptime_data.get_uptimecheck_infos()
uptimecheck_info_attatchment_list =... | The main task of the code is to remove a specified host from an uptime check system. It checks if the host exists in the uptime check list, removes it if present, adds it to a removed list, and generates a Slack message confirming success, already removed status, or non-existence. The function returns a payload message... | def remove_uptimecheck_host(host):
removed_host_list = uptime_data.get_removed_host_list()
uptimecheck_infos = uptime_data.get_uptimecheck_infos()
payload = ""
host = extract_host(host)
if host in uptimecheck_infos:
uptime_data.delete_uptimecheck_info(host)
uptime_data.add_removed_h... |
def get_timelapse_filename_folder_pattern(dateToProcess=datetime.datetime.now(), hourly=False):
date_pattern = f"{dateToProcess.year}##{dateToProcess.month}##{dateToProcess.day}"
if hourly:
date_pattern = f"{date_pattern}##{dateToProcess.hour}"
return date_pattern
def get_image_files(dir, fileExt="... | The main task of the code is to generate a timelapse video from a set of images in a specified directory. It checks if the required image folder exists, skips if the video already exists, and processes images to create an MP4 file with defined dimensions. The function avoids redundant processing by verifying folder exi... | def process_timelapse_video(basePath, dateToProcess=datetime.datetime.now(), hourly=False):
filename_pattern = get_timelapse_filename_folder_pattern(dateToProcess, hourly)
image_dir = f"{basePath}/{filename_pattern.replace('##', '/')}"
if not os.path.exists(image_dir):
print(f"Skipping timelaps... |
def lognormal_delay_generation(key: jnp.array, sim_params: SimArgs,
visualize_plot: bool = True) \
-> (jnp.array, jnp.array):
key, hrs = hrs_generation(key, sim_params)
continuous_delays = sim_params.cap * hrs
discrete_delays = jnp.round(continuous_delays * (1 / sim_pa... | The function `delay_generation` generates discrete delays based on a specified distribution (`lognormal`, `uniform`, or `pattern`) using random key `key` and simulation parameters `sim_params`. It computes delay statistics (mean in timesteps and milliseconds), saves the generated delays to a NumPy file at `path_to_save... | def delay_generation(key: jnp.array, sim_params: SimArgs, path_to_save: str,
visualize_plot: bool = False) -> (jnp.array, jnp.array):
if sim_params.delay_distribution == 'lognormal':
key, delays = lognormal_delay_generation(key, sim_params,
... |
def majority(attributes, data, target):
val_freq = {}
index = attributes.index(target)
for point in data:
if (point[index]) in val_freq:
val_freq[point[index]] += 1
else:
val_freq[point[index]] = 1
max_freq = 0
major = ""
for key in val_freq.keys():
... | The function `make_decision_tree` constructs a decision tree by recursively selecting the best attribute to split the data, creating subtrees for each possible value of that attribute, and using majority class as default when no attributes remain or all examples share the same target value. It returns a tree structure ... | def make_decision_tree(data, attributes, target):
"""
Returns a new decision tree based on the examples given.
:param data:
:param attributes:
:param target:
:return:
"""
# Possible values of the target attribute
vals = [record[attributes.index(target)] for record in data]
defau... |
def write_senones(args):
# Read logits and write sphinx data files
if not os.path.exists(args.logits):
print("Error: missing file {}".format(args.logits))
exit(-1)
logits = np.load(args.logits)
write_logits(logits, args)
def run_sphinx(args):
# Run sphinx command line
cmd = SPHIN... | The code processes speech recognition tasks by writing senone data files, executing Sphinx for recognition, and formatting results for Kaggle submission, contingent on command-line arguments that control each step's execution. | def run(args):
# Read logits file and write into sphinx data files
if not args.no_write_senones:
write_senones(args)
# Run sphinx on data files
if not args.no_run_sphinx:
run_sphinx(args)
# Parse results for Kaggle
if not args.no_format_submission:
format_submission(args) |
def _CreateDatabaseConnectionProfile(self):
if self.oracle_cp:
return self._CreateOracleConnectionProfile(self.source_connection_name,
self.oracle_cp)
elif self.mysql_cp:
return self._CreateMysqlConnectionProfile(
self.source_connection_name... | (The main task of the code is to configure and initiate a CDC Datastream by sequentially creating a source Oracle database connection profile, a destination GCS connection profile, a datastream that transfers data between them, and then activating the stream. It logs progress, handles errors via exceptions, and ensures... | def SetUp(self):
"""Create and start all resources for a CDC Datastream.
In this order:
- Create a source Database Connection Profile
- Create a destintation GCS Connection Profile
- Create a stream that reads from source into destination
- Start the stream
"""
logging.info("Setting up ... |
def zerologon(self) -> bool:
logger.info("-" * 55)
logger.info("Starting the ZeroLogon workflow")
if self.brute_forcing_server() is False:
return False
result = None
for _ in range(MAX_ATTEMPTS):
try:
result = self.set_empty_password()
... | The main task of the code is to execute a sequence of attacks exploiting the ZeroLogon vulnerability. It first checks for ZeroLogon success, dumps secrets, attempts password restoration from "Administrator.secrets", retrieves registry hives, and tries restoring another password using the server name in the filename, ha... | def attack_workflow(self: str):
# Firstly
if not self.zerologon():
sys.exit(1)
self.secrets_dumping()
try:
self.__restoring_password(file_name="Administrator.secrets")
except impacket.dcerpc.v5.nrpc.DCERPCSessionError:
logger.error("Impossible... |
def print_colored_prefix(color, prefix, message):
print(f"{color}{prefix}{Color.RESET}", message)
def select_roi(screenshot):
plt.imshow(cv2.cvtColor(screenshot, cv2.COLOR_BGR2RGB))
plt.show(block=False)
print("Please select the region of interest (ROI).")
roi = plt.ginput(n=2)
plt.close()
x... | The main task of the code is to capture and process golf shot data using a launch monitor, sending it to an API. It uses multithreading for screenshot capture, extracts metrics like ball speed and spin rate, validates data integrity, and sends results via a socket. In auto-shot mode, it generates fake data at intervals... | def main():
AUTOSHOT_DELAY = 8 # number of seconds between automatic shots
try:
input("- Press enter after you've hit your first shot. -")
ball_speed_last = total_spin_last = spin_axis_last = hla_last = vla_last = club_speed = None
screenshot_attempts = 0
incomplete_data_display... |
def setup_bootflow_image(cons):
"""Create a 20MB disk image with a single FAT partition"""
mmc_dev = 1
fname, mnt = setup_image(cons, mmc_dev, 0xc, second_part=True)
loop = None
mounted = False
complete = False
try:
loop = mount_image(cons, fname, mnt, 'vfat')
mounted = True... | The main task of the code is to initialize test data for U-Boot bootflow testing by configuring bootflow, bootmenu, cedit, and cros images, then restarting U-Boot to ensure the updated mmc1.img is recognized and applied for subsequent tests. | def test_ut_dm_init_bootstd(u_boot_console):
"""Initialise data for bootflow tests"""
setup_bootflow_image(u_boot_console)
setup_bootmenu_image(u_boot_console)
setup_cedit_file(u_boot_console)
setup_cros_image(u_boot_console)
# Restart so that the new mmc1.img is picked up
u_boot_console.r... |
def process_spectrum(self, target='sample',
apply_envelope=True,
envelope_width=1,
valid_thresh=.01,
smoothing=None,
window=None,
align_phase=True,
... | This function normalizes sample and reference spectra by first processing them (applying envelopes, phase alignment, smoothing) and then normalizing the sample spectrum relative to the reference spectrum. It handles both magnitude and complex spectra, interpolates results, and returns normalized frequency, absolute mag... | def __call__(self,
optimize_BB=False,
align_phase=True,
apply_envelope=True,
envelope_width=1,
valid_thresh=.01,
smoothing=None,window=None,
view_phase_alignment=False,
BB_normalize=Tr... |
def get_update_mapper(feature_name):
"""
Get the appropriate function and class for the feature type
:param feature_name:
:type feature_name:
:return:
:rtype:
"""
update_function_mapper = {
'Mains': [get_watermain_data, WaterMainClass.compare_watermains, WaterMainClass],
... | The function processes updated features by comparing QC data from a file path with SDE data using a mapper. It retrieves feature data, builds SQL queries, identifies differences, and returns them. If no mapper exists, it returns an empty list. | def updated_feature(feature_name, sde_feature, qc_feature_path):
"""
Processes the updated features
:param feature_name:
:type feature_name:
:param sde_feature:
:type sde_feature:
:param qc_feature_path:
:type qc_feature_path:
:return:
:rtype:
"""
mapper = get_update_map... |
def check_gdb_path(geodatabase_path):
"""
Verify if the supplied geodatabase path exists as a geodatabase
:param geodatabase_path:
:type geodatabase_path:
:return:
:rtype:
"""
if os.path.isdir(geodatabase_path):
return True
else:
return False
def get_features(geodatab... | The code processes a geodatabase to identify differences in its features. It checks if the geodatabase path exists, retrieves features, skips "General" features, compares each feature against the geodatabase, and collects non-null differences. The result is a list of changes, or None if the path is invalid. | def process_geodatabase(geodatabase):
logging.info("Feature: {}".format(geodatabase))
if not check_gdb_path(geodatabase):
logging.warning("{} doesn't exist".format(geodatabase))
return None
features = get_features(geodatabase)
differences = []
for feature in features:
if "G... |
def __preprocess_dataset(self, schema_path):
with open(schema_path) as f:
schema = json.load(f)
df, df_eda = self.__get_dataset(self.__args.dataset_name)
columns_names = schema.keys()
df.columns = columns_names
return df, df_eda
def __make_exploratory_analysis(self,... | The main task of the code is to preprocess a dataset using a schema file, perform exploratory data analysis (EDA) on the preprocessed data, and upload the processed datasets along with their column names to a storage system. | def main(self):
df, df_eda = self.__preprocess_dataset(schema_path="./schema_dataset.json")
self.__make_exploratory_analysis(df_eda)
self.__upload_datasets(df, df.columns) |
def get_hint(dict_with_word_color,current_team,similarity_level):
count = 0
while True:
dict_similar_words_for_team = find_semantic_similarities(dict_with_word_color[current_team],similarity_level)
if len(dict_similar_words_for_team) == 0:
similarity_level -= 0.03
count +... | This code simulates an AI vs AI guessing game where teams take turns generating hints and guessing words from a dictionary. The game alternates between RED and BLUE teams, with each team attempting to guess a specified number of words based on hints. The loop continues until a team fails to guess correctly, switching t... | def begin_ai_vs_ai_game(dict_with_word_color):
team_going_first = random.choice(['RED','BLUE'])
dict_prev_hint_check = {"RED":[],"BLUE":[]}
print(team_going_first," team is going first\n")
whose_turn = team_going_first
opposite_team = "BLUE" if whose_turn=="RED" else "RED"
while whose_turn:... |
def select_25_words(word_dataset):
number_of_words = 25
return random.sample(word_dataset,number_of_words)
def arranged_board(words):
board = []
for col in range(5):
row_list = []
for row in range(5):
row_list.append(words[5*col+row])
board.append(row_list)
return... | The code initializes a Codenames game by selecting 25 words, arranging them on a board, assigning colors to keycards, and linking words to colors. It verifies a spymaster password, then lets users choose between human vs human, human vs AI, or AI vs AI gameplay modes, initializing the corresponding game setup with the ... | def game_setup(word_dataset):
words_current_game = select_25_words(word_dataset)
words_in_board_format = arranged_board(words_current_game)
colors_keycard_selection = set_colors_in_keycard()
colors_in_keycard_format = arranged_board(colors_keycard_selection)
dict_with_word_color = associate_word_co... |
def ensure_empty_dir(path):
ensure_remove_dir(path)
os.mkdir(path)
def copy_harness_files(out_js_dir, include_harness):
harness_dir = os.path.join(out_js_dir, 'harness')
ensure_empty_dir(harness_dir)
print('Copying JS test harness to the JS out dir...')
for js_file in glob.glob(os.path.join(HAR... | The main task of the code is to prepare a directory by clearing it, copying harness files, converting WAST files to JavaScript, wrapping each JavaScript file as a single test, and returning the list of generated test files. | def build_html_js(out_dir):
ensure_empty_dir(out_dir)
copy_harness_files(out_dir, True)
tests = convert_wast_to_js(out_dir)
for js_file in tests:
wrap_single_test(js_file)
return tests |
def get_image(path):
global _image_library
image = _image_library.get(path)
if image is None:
image = pygame.image.load(path)
_image_library[path] = image
return image
def create_text(text, size, color):
global _cached_text
key = '|'.join(map(str, (size, color, text)))
image ... | The code renders a poker game interface by drawing the background, game elements (deck, poker chips), player and dealer cards, balance display, scores, and buttons onto the provided screen surface using Pygame. It updates visual components like card positions, formatted balance text, and score indicators for a dynamic ... | def render(self, screen):
# draw background stuff
screen.fill(self.table_colour)
deck_img = get_image('myresources/deckimg.png')
deck_img = pygame.transform.scale(deck_img, (148, 193))
screen.blit(deck_img, (35, 85))
pokerchips1_img = get_image('myresources/pokerchips1.pn... |
def hit(self):
self.cards_player.append(self.deck.deal_card())
self.avail_double = False
self.calculate_scores()
self.check_scores()
def calculate_scores(self):
# calculate scores
self.score_dealer = 0
self.score_dealer_alt = 0
for card in self.cards_deale... | This code handles a player's "double down" action in a Blackjack game by adjusting the bet, revealing the dealer's second card, calculating scores, and determining outcomes. It updates the player's balance, checks for busts, and compares scores against the dealer. If the player doesn't bust, the dealer draws cards unti... | def double(self):
self.bal -= self.bet
self.bet *= 2
self.avail_double = False
self.hit()
self.cards_dealer[1].faceup = True
self.calculate_scores()
if self.score_player < self.score_player_alt and self.score_player_alt <= 21:
self.score_player = self.... |
def stand(self):
self.avail_stand = False
self.avail_hit = False
self.avail_double = False
self.cards_dealer[1].faceup = True
self.calculate_scores()
if self.score_player < self.score_player_alt and self.score_player_alt <= 21:
self.score_player = self.score_p... | This code processes mouse click events to trigger game actions (stand, hit, double, continue) based on button positions and conditions. It checks mouse positions against predefined rectangles, executes corresponding methods if available, and transitions scenes based on balance checks. | def process_input(self, events, pressed_keys):
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = event.pos
if pygame.Rect(600, 265, 175, 60).collidepoint(mouse_pos) and self.avail_stand:
self.stand()
if pygam... |
def measure_memory(name):
p = subprocess.Popen(['python3', name],
stdout=log,
stderr=log,
preexec_fn=os.setpgrp )
PID = p.pid
memory_use = psutil.Process(PID).memory_info().rss / 1024 ** 2
# print(memory_use)
memory_limits = []
for frac in memor... | The code evaluates the impact of varying memory limits on a specified process. It measures memory constraints, executes the process under each limit, logs page faults in a CSV file, computes performance degradation, and generates a visual representation of the results. | def main():
process = sys.argv[1]
file_name = 'output.csv'
if os.path.exists(file_name): os.remove(file_name)
memory_limits = measure_memory(process)
count = 1
for memory in memory_limits:
run_process(process, memory)
populate_page_faults(file_name, count)
count = c... |
def expand_elements_to_isotopes(elements: Union[str, List[str]]):
if elements == "all" or elements == ["all"]:
return ISOTOPE_OPTIONS
if isinstance(elements, str):
return NATURAL_ABUNDANCE[elements]
isotopes = []
for element in elements:
isotopes = isotopes + NATURAL_ABUNDANCE... | This function generates a custom OpenMC cross-section library by compiling isotopes and SAB data from input elements, materials, and XML files, filtering required data, downloading it to a specified destination, and creating a cross-section XML file. It optionally sets the OPENMC_CROSS_SECTIONS environment variable for... | def just_in_time_library_generator(
libraries: List[str] = [],
isotopes: List[str] = [],
elements: List[str] = [],
sab: List[str] = [],
destination: Union[str, Path] = None,
materials_xml: List[Union[str, Path]] = [],
materials: list = [], # also accepts a single openmc.Material
particl... |
def get_data(dir_path,report=False):
r = get_files(dir_path)
super_r = []
for f in r:
if report:
print(f)
super_r.append( process_file(f) )
if report:
print( str(len(super_r)) + " files proceed")
return super_r
def analyze_spectrum(spec,left_border=LEFT_BORDER, ri... | The code processes data from a directory by analyzing each spectrum to extract metrics (energy, start/stop times, duration, amplitude, input power). It computes statistical values (mean, standard deviation, median, correlation) for these metrics, generates a formatted report with timestamps and results, calculates an u... | def process_dir( path_to_dir ):
r = get_data(path_to_dir)
energies = []
starts = []
stops = []
durations = []
gen = []
amp = []
for s in r:
m = analyze_spectrum(s)
energies.append(m[4][0])
starts.append(m[4][3])
stops.append(m[4][4])
... |
def cutQn(Qn, etarange, nsamples):
list = jaclist(etarange)
#list = list.astype(complex)
Qn /= 2 # Qn was calculated in a range of 2 units of rapidity.
Qn *= list[None,:,None,:] # per-rapidity to per-pseudorapidity
Qn /= nsamples[:,None,None,None] # per SMASH sample
# for pt in range(len(ptlist))... | The function `finalmultiplicity` calculates the multiplicity of particles in a specified pseudorapidity (`eta`) and transverse momentum (`pt`) range, applying a jackknife error estimation. It extracts event data, applies cuts to filter events within `etarange` and `ptrange`, normalizes by the number of events (`sevents... | def finalmultiplicity (Qn, sevents, eventlist, etarange, ptrange):
Q0 = Qn[:,0,:,:]
Q0bin = Qn[eventlist]
Q0eta = cutQn(Qnbin, etarange)
Q0etapt = cutpt(Q0eta, ptrange)
Q0etapt /= sevents
# return multplicity(Q0etapt) # without uncertainty
return jackknifeerror(multiplicity, Q0etapt) |
def readevents(design_dir,Nevents,skiplist,STAR_or_ALICE):
# result_dtype = return_result_dtype('ALICE')
result_dtype = return_result_dtype(STAR_or_ALICE)
# This will store all results from all events at 1 design point.
# From this we can pull any desired info, such as the differential Q vectors
# f... | The code processes particle collision data to compute and analyze Qn harmonics (Q0-Q4) across different centrality bins, applying pseudorapidity and transverse momentum cuts. It calculates charged hadron multiplicities, spectra, and weighted observables (dQ0, qQ0) for varying pt ranges, sorting events by multiplicity. ... | def allobservables(design_dir, delta_f_index, Nevents, STAR_or_ALICE):
Nparticles = len(masslist)
#Nparticles = 5
Npt = 56
Nharmonics = 5
# extract raw data from files
alldata = readevents(design_dir,Nevents,[],STAR_or_ALICE)
#
# extract useful information and format as numpy arrays
... |
def wavefront_position_error_estimate_standard_deviation(self):
return wavefront_position_error_estimate_standard_deviation(self.data, self.latitude)
def wavefront_position_error_estimate_width(self, position_choice):
return wavefront_position_error_estimate_width(self.data, self.lat_bin, position_choic... | The code computes a position and its associated error based on specified methods. It selects the position calculation method (e.g., average, maximum, Gaussian fit, weighted center) via `position_choice` and the error estimation method (standard deviation or width) via `error_choice`. It returns both the calculated posi... | def locator(self, position_choice, error_choice):
if error_choice == 'std':
position_error = self.wavefront_position_error_estimate_standard_deviation()
elif error_choice == 'width':
position_error = self.wavefront_position_error_estimate_width(position_choice)
else:
... |
def use_chipset0(self):
"""
Description: This function enables Chipset 1(KS0108 IC1) of GLCD.
:return: None
"""
GPIO.output(self.chip_set0, 1) # Turn ON left controller
GPIO.output(self.chip_set1, 0)
def use_chipset1(self):
"""
Description: This func... | This function sets the cursor position on a GLCD by validating input parameters (chip, line, cursor_pos), enabling the specified chipset (0 or 1), calculating command values for line and column addresses, and sending these as commands to position the cursor for data writing. | def set_cursor(self, chip, line, cursor_pos):
"""
Description: This function is used to specify when data is to be written on the glcd.
:param chip: If 0 data will be written on chipset 0, if 1 data will be written on chipset 1
:param line: Used to specify on when line data is to be writ... |
def use_chipset0(self):
"""
Description: This function enables Chipset 1(KS0108 IC1) of GLCD.
:return: None
"""
GPIO.output(self.chip_set0, 1) # Turn ON left controller
GPIO.output(self.chip_set1, 0)
def use_chipset1(self):
"""
Description: This func... | This function enables chipset 0 or 1 based on the input parameter 'chip' (0 or 1), updates internal state variables (chip_Num, Cursor_Pos), and performs data writes to initialize cursor position (0x40) and line number. It validates the input, selects the appropriate chipset method, and configures system settings for th... | def go_to_chipset(self, chip):
"""
Description: Enables chipset 0 or 1 based on the value given by user or value passed in other function.
:param chip: Chipset 0 is enabled if chip=0, Chipset 1 is enabled if chip=1
:return: None
"""
if (chip == 0) or (chip == 1):
... |
def use_chipset0(self):
"""
Description: This function enables Chipset 1(KS0108 IC1) of GLCD.
:return: None
"""
GPIO.output(self.chip_set0, 1) # Turn ON left controller
GPIO.output(self.chip_set1, 0)
def data_write(self, value, mode):
"""
Description... | The main task of the code is to initialize a GLCD (Graphical Liquid Crystal Display) by sending specific commands to two chipsets. It enables the display using the 0x3F command, sets the start line with 0xC0, and clears the screen. The process involves alternating between chipset0 and chipset1 for configuration, ensuri... | def start(self):
"""
Description: Initialization of GLCD, 0x3F command is used to turn on the GLCD.
0xC0 is start line command
:return: None
"""
self.use_chipset0()
self.data_write(0x3F, 0)
self.use_chipset1()
self.data_write(0x3F, 0)
time.... |
def go_to_nextline(self):
"""
Description: This function shifts the line position by 1 when it is called in other function
or called by user
:return: None
"""
self.Line_Num += 1
if self.Line_Num > 0xBF:
self.Line_Num = 0xB8
self.go_to_chipset(s... | This function prints a character by fetching its corresponding data from a lookup table using its ASCII value. It handles line wrapping when the cursor exceeds line limits and switches between chipsets (0 and 1) based on cursor position. Special handling for newline characters shifts to the next line, while other chara... | def print_chr(self, data):
"""
Description: In this function data received as character and by using the ASCII value of characters the data
is fetched from lookup table and written in the display, if the data exceeds the line limit it is automatically
shifted to the next line.
:p... |
def __W_DBT_RH_P(DBT, RH, P):
if __valid_DBT(DBT):
Pw=RH*__Pws(DBT)
return 0.621945*Pw/(P-Pw)
def __W_DBT_H(DBT, H):
if __valid_DBT(DBT):
DBT=DBT-273.15
return (H-1.006*DBT)/(2501+1.86*DBT)
def __is_positive(x):
if x>0:
return True
else:
return False | The function performs a bisection method to solve for the dry-bulb temperature (DBT) where the psychrometric function __W_DBT_RH_P equals __W_DBT_H, given inputs H (enthalpy), RH (relative humidity), and P (pressure). It iteratively narrows the DBT range [Min_DBT, Max_DBT] until the difference between bounds falls belo... | def __DBT_H_RH_P(H, RH, P):
[DBTa, DBTb]=[Min_DBT, Max_DBT]
DBT=(DBTa+DBTb)/2
while DBTb-DBTa>TOL:
ya=__W_DBT_RH_P(DBTa, RH, P)-__W_DBT_H(DBTa, H)
y=__W_DBT_RH_P(DBT, RH, P)-__W_DBT_H(DBT, H)
if __is_positive(y)==__is_positive(ya):
DBTa=DBT
else:
DBTb=... |
def __W_DBT_RH_P(DBT, RH, P):
if __valid_DBT(DBT):
Pw=RH*__Pws(DBT)
return 0.621945*Pw/(P-Pw)
def __W_DBT_V_P(DBT, V, P):
if __valid_DBT(DBT):
return (P*V-287.042*DBT)/(1.607858*287.042*DBT)
def __is_positive(x):
if x>0:
return True
else:
return False | This code implements a bisection root-finding algorithm to determine the dew point temperature (DBT) where the difference between two functions, __W_DBT_RH_P (dependent on RH and P) and __W_DBT_V_P (dependent on V and P), equals zero. It iteratively adjusts the DBT interval [DBTa, DBTb] until convergence within toleran... | def __DBT_RH_V_P(RH, V, P):
[DBTa, DBTb]=[Min_DBT, Max_DBT]
DBT=(DBTa+DBTb)/2
while DBTb-DBTa>TOL:
ya=__W_DBT_RH_P(DBTa, RH, P)-__W_DBT_V_P(DBTa, V, P)
y=__W_DBT_RH_P(DBT, RH, P)-__W_DBT_V_P(DBT, V, P)
if __is_positive(y)==__is_positive(ya):
DBTa=DBT
else:
... |
def __W_DBT_WBT_P(DBT, WBT, P):
if __valid_DBT(DBT):
DBT=DBT-273.15
WBT=WBT-273.15
return ((2501-2.326*WBT)*__W_DBT_RH_P(WBT+273.15,1,P)-1.006*(DBT-WBT))/\
(2501+1.86*DBT-4.186*WBT)
def __W_DBT_H(DBT, H):
if __valid_DBT(DBT):
DBT=DBT-273.15
return (H-1.006*... | This function uses the bisection method to find the root of an equation involving the difference between two functions, __W_DBT_WBT_P and __W_DBT_H, by iteratively narrowing the interval [DBTa, DBTb] until the tolerance TOL is met. The result is the value of DBT that satisfies the equation. | def __DBT_H_WBT_P(H, WBT, P):
[DBTa, DBTb]=[Min_DBT, Max_DBT]
DBT=(DBTa+DBTb)/2
while DBTb-DBTa>TOL:
ya=__W_DBT_WBT_P(DBTa, WBT, P)-__W_DBT_H(DBTa, H)
y=__W_DBT_WBT_P(DBT, WBT, P)-__W_DBT_H(DBT, H)
if __is_positive(y)==__is_positive(ya):
DBTa=DBT
else:
... |
def __W_DBT_WBT_P(DBT, WBT, P):
if __valid_DBT(DBT):
DBT=DBT-273.15
WBT=WBT-273.15
return ((2501-2.326*WBT)*__W_DBT_RH_P(WBT+273.15,1,P)-1.006*(DBT-WBT))/\
(2501+1.86*DBT-4.186*WBT)
def __W_DBT_RH_P(DBT, RH, P):
if __valid_DBT(DBT):
Pw=RH*__Pws(DBT)
return ... | This code calculates the dry bulb temperature (DBT) using the bisection method to solve the equation where the humidity function derived from wet bulb temperature equals that derived from relative humidity, under a given pressure. It iteratively narrows the DBT range until the difference between upper and lower bounds ... | def __DBT_RH_WBT_P(RH, WBT, P):
[DBTa, DBTb]=[Min_DBT, Max_DBT]
DBT=(DBTa+DBTb)/2
while DBTb-DBTa>TOL:
ya=__W_DBT_WBT_P(DBTa, WBT, P)-__W_DBT_RH_P(DBTa, RH, P)
y=__W_DBT_WBT_P(DBT, WBT, P)-__W_DBT_RH_P(DBT, RH, P)
if __is_positive(y)==__is_positive(ya):
DBTa=DBT
e... |
def __W_DBT_WBT_P(DBT, WBT, P):
if __valid_DBT(DBT):
DBT=DBT-273.15
WBT=WBT-273.15
return ((2501-2.326*WBT)*__W_DBT_RH_P(WBT+273.15,1,P)-1.006*(DBT-WBT))/\
(2501+1.86*DBT-4.186*WBT)
def __W_DBT_V_P(DBT, V, P):
if __valid_DBT(DBT):
return (P*V-287.042*DBT)/(1.607858... | This code performs a bisection root-finding algorithm to determine the equilibrium dry-bulb temperature (DBT) where the difference between two functions, __W_DBT_WBT_P and __W_DBT_V_P, equals zero. It iteratively narrows the interval [DBTa, DBTb] until convergence within tolerance TOL, returning the computed DBT value. | def __DBT_V_WBT_P(V, WBT, P):
[DBTa, DBTb]=[Min_DBT, Max_DBT]
DBT=(DBTa+DBTb)/2
while DBTb-DBTa>TOL:
ya=__W_DBT_WBT_P(DBTa, WBT, P)-__W_DBT_V_P(DBTa, V, P)
y=__W_DBT_WBT_P(DBT, WBT, P)-__W_DBT_V_P(DBT, V, P)
if __is_positive(y)==__is_positive(ya):
DBTa=DBT
else:
... |
def __valid_DBT(DBT):
if Min_DBT<=DBT<=Max_DBT:
return True
else:
return False
def __DPT_Pw(Pw):
Pw=Pw/1000
C14=6.54
C15=14.529
C16=0.7389
C17=0.09486
C18=0.4569
a=m.log(Pw)
return (C14+C15*a+C16*a**2+C17*a**3+C18*Pw**0.1984)+273.15
def __Pw_W_P(W, P):
return ... | This code computes a value WBT by iteratively adjusting WBTa and WBTb based on comparisons with Ws, derived from DBT, W, and P, until the difference between WBTb and WBTa falls within a tolerance threshold TOL. The process involves calculating initial values, refining the estimate through a loop, and returning the conv... | def __WBT_DBT_W_P(DBT, W, P):
if __valid_DBT(DBT):
WBTa=__DPT_Pw(__Pw_W_P(W, P))
WBTb=DBT
WBT=(WBTa+WBTb)/2
while WBTb-WBTa>TOL:
Ws=__W_DBT_WBT_P(DBT, WBT, P)
if W>Ws:
WBTa=WBT
else:
WBTb=WBT
WBT=(WBTa+WB... |
def Evolink_calculation(gene_matrix, trait_matrix, species_list, gene_list, tree_file):
import warnings
warnings.simplefilter(action='ignore', category=RuntimeWarning)
T1_index, T0_index, G1T1, G0T1, G1T0, G0T0 = generate_four_matrix(gene_matrix, trait_matrix)
T1_species = [species_list[i] for i in T1... | The code processes gene-trait association data to identify significant genes using the Evolink index. It calculates this index for each gene, then applies statistical methods (e.g., Isolation Forest, Z-score, permutation tests) based on the specified mode to detect outliers or significant associations. Results are filt... | def pipeline(args):
gene_table = args.gene_table
trait_table = args.trait_table
tree_file = args.tree_file
CN = args.CN
p_threshold = args.p_threshold
mode = args.mode
seed = args.seed
# IsolationForest mode
min_outlier_score_threshold = args.min_outlier_score_threshold
n_e... |
def BuildTree(feats, labels):
(split0, gain0) = FindMaxEntropySplit(feats[:, 0], labels)
(split1, gain1) = FindMaxEntropySplit(feats[:, 1], labels)
# If no entropy gain, make a leaf
if gain0 <= 0 and gain1 <= 0:
ones = np.sum(labels)
if (len(labels) - 1) / 2 >= ones: return Leaf(0)
else:... | The code tests a decision tree implementation by constructing trees from sample data and labels, then classifying specific data points using the tree. It verifies correctness by comparing outputs to expected results, including edge cases like all-zero labels and trees with no splits. | def TestBuildTraverseTree():
TestData = np.array([[0,1,2,3,4,5,6,7,8,9], [0,0,0,0,0,0,0,0,0,0]]).T
TestLabels = np.array( [0,0,0,1,1,1,0,0,1,0])
Tree = BuildTree(TestData, TestLabels)
print("Classifying\n\t1:", TraverseTree([1,0], Tree), "\n\t3:", TraverseTree([3,0], Tree), \
"\n\t6:", Traverse... |
def BuildTree(feats, labels):
(split0, gain0) = FindMaxEntropySplit(feats[:, 0], labels)
(split1, gain1) = FindMaxEntropySplit(feats[:, 1], labels)
# If no entropy gain, make a leaf
if gain0 <= 0 and gain1 <= 0:
ones = np.sum(labels)
if (len(labels) - 1) / 2 >= ones: return Leaf(0)
else:... | The code evaluates decision trees of varying sizes (32, 128, 512, 2048, 8192 training samples) on a dataset, calculating test error rates and node counts for each. It generates decision boundary plots for each tree size and produces a training curve showing error percentage versus training nodes. The goal is to analyze... | def P7():
print("\n----------------------------Problem 7----------------------------")
print("This problem saves images; look for those with the prefix 'P1.7'.")
Data = np.loadtxt("Dbig.txt", dtype=float)
feats = Data[:, :2]
labels = Data[:, 2].astype(int)
(xLo, yLo, xHi, yHi) = (np.min(feats[:,0]), n... |
def swap_stop(self, stop_idx_to_swap):
self.__modify_crawl("bar",stop_idx_to_swap)
def adjust_times(self,stop_idx_to_modify):
self.__modify_crawl("time",stop_idx_to_modify)
def decrement_temperature(self, temperature, method):
if method == 'linear':
return temperature - self.alpha
... | This code implements a local simulated annealing algorithm for optimization. It iterates for a given number of steps, modifying stop positions and adjusting times, tracking improvements in the best solution, and dynamically adjusting the temperature to control exploration/exploitation trade-off during the search for an... | def local_simulated_annealing(self, max_iterations):
for _ in range(max_iterations):
self.innerCounter+=1
# for each stop in crawl, modify bar and times
for stop_idx in range (0,self.number_of_stops):
self.swap_stop(stop_idx)
self.adjust_time... |
def Coordinate(self,x):
if x>=int(WINDOW_H):
x = int(WINDOW_H)-1
return x//BOX_H
def Game_Over(self,res):
if(res=='L'):
answer = tkmb.askquestion(":(","You Lost !! Want to play again ?")
else:
answer = tkmb.askquestion(":)","You Won !! Want to play aga... | This function handles flag placement in a Minesweeper game. It checks if the clicked box is already open or if maximum flags (10) are reached. If valid, it places a mine flag on the box, updates the game state, decrements the flag count, and triggers a win condition if all flags are used. | def Mark_Flag(self,event):
print("for flag: x:",event.x," y:",event.y)
x = self.Coordinate(event.x)
y = self.Coordinate(event.y)
if(self.boxes[y][x].cond==OPEN):
tkmb.showinfo("Attention!!","This box is already flagged")
return
if(self.flag<=0):
... |
def ptgrid(self, pixel_coord):
# ptgrid = pixels_to_grid
# If pixel overflow occurs
if pixel_coord >= WINDOW_SIZE:
pixel_coord = WINDOW_SIZE - 1
grid_coord = int(pixel_coord / CELL_SIZE)
return grid_coord
def new_board(self):
#Clears canvas and game board... | This method handles mouse click events in a Tic-Tac-Toe game. It converts coordinates to grid positions, checks the game state, and updates gameplay: starting a new game, making moves for X/O players, checking win/draw conditions, and transitioning between states like title screen, player turns, and game over. It reset... | def click(self, event):
#Game Logic
x = self.ptgrid(event.x)
y = self.ptgrid(event.y)
if self.gamestate == STATE_TITLE_SCREEN:
self.new_board()
self.gamestate = FIRST_PLAYER
elif (self.gamestate == STATE_X_TURN and
self.board[y][x] == EM... |
def Coordinate(self,x):
if x>=int(WINDOW_H):
x = int(WINDOW_H)-1
return x//BOX_H
def Game_Over(self,res):
if(res=='L'):
answer = tkmb.askquestion(":(","You Lost !! Want to play again ?")
else:
answer = tkmb.askquestion(":)","You Won !! Want to play aga... | This code handles a click event in a game grid, converting mouse coordinates to grid indices. It clears the clicked cell's label and checks if it contains a mine, triggering a game over if true. Otherwise, it initiates a depth-first search (DFS) from the clicked cell to reveal adjacent cells. | def Play(self,event):
x = self.Coordinate(event.x)
y = self.Coordinate(event.y)
self.boxes[y][x].label["text"] = ""
if(self.boxes[y][x].state==MINE):
self.Game_Over('L')
self.Dfs(x,y) |
def readMapFromJsonFile(fName):
'''
Reads a dictionary from a json file.
'''
try:
with open(fName, "rt") as fp:
return json.load(fp)
except Exception:
print(f"{fName} was invlid or empty.")
return {}
def getInfoBlockForNetwork(networkSubnet, cacheFile, useLoc... | The main task of the code is to mine DHCP data from specified subnets by reading network configurations, caching information blocks, authenticating via credentials, categorizing MAC addresses using OUI maps, and generating CSV reports with summaries of MAC classifications (e.g., duplicates, devices) across labs. It opt... | def main():
global OUI_MAP
parser = argparse.ArgumentParser(description='Mice and Men DHCP Miner')
# JSON file listing all the subnets to go mine data for
parser.add_argument("-n", "--networks", help=f'json file listing the lab and subnets to get data for. Default={__defaultNetworkFile}',
... |
def get_sample_dataloader(
model,
eval_batch_size: int,
sample_batch_size: int,
num_samples: int,
channels: int,
img_size: int
):
samples = get_model_samples(model, num_samples, sample_batch_size, channels, img_size)
sample_dataset = SampleDataset(samples)
sample_dataloader = DataLoa... | The function computes evaluation metrics (inception score, FID) for a generative model using a classifier. It handles device placement, EMA, and sample generation, calculating metrics against training/validation feature caches while optimizing memory by moving models between CPU/GPU. | def get_classifier_metrics(
metrics_dict,
config,
gen_model,
ema,
classifier_model,
classifier_preprocess,
cached_train_feats,
cached_valid_feats,
device="cpu",
):
metrics_calculated = ["inception_score", "fid_train", "fid_valid"]
if all(metric not in metrics_dict for metric ... |
def process_summaryfile(summary_csv):
"""process summary dataframe for further analysis
:param
summary_csv: path of summary.csv file
:return
summary_df: preprocessed dataframe of summary csv-file
"""
try:
summary_df = pd.read_csv(summary_csv, h... | The function converts input data into ALPS format for metagenomic assembly. It processes a summary CSV, creates an output directory, generates quality statistics (if enabled), and runs the ALPS assembly process using specified parameters like k-mer size, contig thresholds, and quality cutoffs. The task involves prepari... | def convert_For_ALPS(summary_csv, kmer_ALPS, contigs_ALPS, quality_cutoff_ALPS, create_stats_results):
logger.info("Converting to ALPS started.")
resultdir = summary_csv.rpartition('/')[0] + '/ALPS_Assembly/'
try:
os.makedirs(resultdir)
except FileExistsError:
pass
summary_df = ... |
def _request(self, method: str, endpoint: str, **kwargs) -> Response:
try:
return self.s.request(method, self.url + endpoint, **kwargs)
except Exception as e:
if self.verbose:
self.log_fn(f"{self.project} - retrying request after {e} error...")
sleep(2... | The main task of this code is to initialize a connection to a tracker server by authenticating with a nickname and stage, retrieving session tokens and project details, and configuring logging. It trims the URL, sets up a session, sends a GET request to "/api/new", handles errors, stores response data like token and pr... | def __init__(self, url: str, stage: str, nickname: str, verbose: bool = True) -> None:
if url[-1] == "/":
url = url[:-1]
self.s = session()
self.url = url
self.stage = stage
self.nickname = nickname
self.verbose = verbose
self.token =... |
def _request(self, method: str, endpoint: str, **kwargs) -> Response:
try:
return self.s.request(method, self.url + endpoint, **kwargs)
except Exception as e:
if self.verbose:
self.log_fn(f"{self.project} - retrying request after {e} error...")
sleep(2... | The main task of the code is to retrieve the number of remaining jobs from an API endpoint by sending a GET request with the current stage parameter. It handles potential errors, logs the result if verbose mode is enabled, and returns the job count as an integer. | def job_count(self) -> int:
params = {
"stage": self.stage
}
r = self._request("GET", "/api/jobCount", params=params)
err = self._handle_exceptions(r)
if err:
self.log("Crashed", _err=True)
raise err
count = int(r.text)
... |
def _request(self, method: str, endpoint: str, **kwargs) -> Response:
try:
return self.s.request(method, self.url + endpoint, **kwargs)
except Exception as e:
if self.verbose:
self.log_fn(f"{self.project} - retrying request after {e} error...")
sleep(2... | The main task of the code is to fetch a new job from a remote API by sending a POST request with a token, handle potential errors, parse the JSON response, and store the job data and ID in the instance. It also logs progress and checks for special JSON encoding in the response. | def new_job(self) -> None:
self.log_fn(f"{self.project} - looking for new job...")
body = {
"token": self.token
}
r = self._request("POST", "/api/newJob", json=body)
err = self._handle_exceptions(r)
if err:
self.log("Crashed", _err=True)
... |
def _request(self, method: str, endpoint: str, **kwargs) -> Response:
try:
return self.s.request(method, self.url + endpoint, **kwargs)
except Exception as e:
if self.verbose:
self.log_fn(f"{self.project} - retrying request after {e} error...")
sleep(2... | This method marks a job as complete by sending data to an API endpoint. It validates input data, formats it as JSON if necessary, and sends a POST request with authentication tokens. Upon success, it resets job tracking variables and logs completion if verbose mode is enabled. Errors trigger logging and re-raised excep... | def complete_job(self, data: Union[str, list, dict]) -> None:
if isinstance(data, (dict, list)):
data = "<!json!>" + json.dumps(data)
elif not isinstance(data, str):
raise ValueError("data must be one of: str, list, dict")
body = {
"token": self.token... |
def _request(self, method: str, endpoint: str, **kwargs) -> Response:
try:
return self.s.request(method, self.url + endpoint, **kwargs)
except Exception as e:
if self.verbose:
self.log_fn(f"{self.project} - retrying request after {e} error...")
sleep(2... | The main task of the code is to check if a worker is alive by sending a POST request with a token to the "/api/validateWorker" endpoint. It handles exceptions from the response and returns `True` if the response text contains "True", otherwise returns `False` after logging errors. | def is_alive(self) -> bool:
body = {
"token": self.token
}
r = self._request("POST", "/api/validateWorker", json=body)
err = self._handle_exceptions(r)
if err:
self.log("Crashed", _err=True)
raise err
return ("True" in r.text... |
def _request(self, method: str, endpoint: str, **kwargs) -> Response:
try:
return self.s.request(method, self.url + endpoint, **kwargs)
except Exception as e:
if self.verbose:
self.log_fn(f"{self.project} - retrying request after {e} error...")
sleep(2... | The main task of the code is to send a POST request to an API endpoint ("/api/flagInvalidData") with a token to flag invalid data. It resets job-related attributes (self.job, self.job_id) to None, handles exceptions from the request, and logs errors if they occur. The function returns a boolean, likely indicating succe... | def flag_invalid_data(self) -> bool:
body = {
"token": self.token
}
r = self._request("POST", "/api/flagInvalidData", json=body)
self.job = None
self.job_id = None
err = self._handle_exceptions(r)
if err:
self.log("Crashed", _err=True)
... |
def process_bag_rules(rules):
to_remove = re.compile(r"(bag)(s{0,1})|\.") # removes bag, bags, and '.'
rule_dict = {}
for rule in rules:
stripped_rule = to_remove.sub('', rule)
outer_bag, inner_bags_string = stripped_rule.split("contain")
outer_bag = outer_bag.strip()
inne... | The code reads bag rules from an input file, processes them into a dictionary, and calculates two values: the number of distinct bag types that can contain a shiny gold bag, and the total count of bags required to hold a single shiny gold bag, including nested bags. | def main():
lines = []
# with open("./day07/example.txt", 'r') as infile:
with open("./day07/input.txt", 'r') as infile:
lines = infile.read().splitlines()
rule_dict = process_bag_rules(lines)
count_shiny_gold_bag_options(rule_dict)
count_bags_in_shiny_bag(rule_dict)
return() |
def newGame(self):
obs = self.env.reset()
done = False
if self.isTest:
for _ in range(self.rg.integers(0, self.noop_max)):
# Actions with no-op at the start for a random number of steps
obs, _, done, _ = self.env.step(0)
self.updateBuffer(obs, ... | The main task of the code is to execute a single step in a reinforcement learning environment, handling episode resets, updating a buffer with observations/actions/rewards, and managing counters. It takes an action (random or calculated), processes the environment's response, updates internal state (lives, done status)... | def step(self, dry=False):
"""
Main method to do a step on the environment.
Resets or change environment automatically when
then current environment is done.
Adds the current obsevations to the buffer and
clips the reward if needed.
If dry is True always execute... |
def clearBuffer(self):
self.bufferFull = False
self._i = 0
self.tBuffer[:] = False
self.done = True
self.lastObs = None
def step(self, dry=False):
"""
Main method to do a step on the environment.
Resets or change environment automatically when
then... | The main task of the code is to fill a buffer by first clearing it, then performing a series of simulated steps (dry runs) to populate the buffer, and finally returning the filled buffer. | def fillBuffer(self):
self.clearBuffer()
for _ in range(self.buffer_size):
self.step(dry = True)
return self.getBuffer() |
def simplified(self, sentence):
simple_posArray = []
for word in sentence:
prob_max = -1
pos_max = "pos"
for pos in self.unique_pos.keys():
if word not in self.emission_prob:
x = self.minProb
else:
... | The code's main task is to route a given sentence to different processing algorithms based on the specified model type. If the model is "Simple," it uses a simplified method; "Complex" triggers a Markov Chain Monte Carlo approach; "HMM" applies a Hidden Markov Model with Viterbi algorithm. Unknown models result in an e... | def solve(self, model, sentence):
if model == "Simple":
return self.simplified(sentence)
elif model == "Complex":
return self.complex_mcmc(sentence)
elif model == "HMM":
return self.hmm_viterbi(sentence)
else:
print("Unknown algo!") |
def unit_propagateWL(dict, units, partial_assignment):
units_propagated = [] # Unit literals that have so far been set to true
u_literals = deque(units)
mainLEFV = None # Last encountered free variable in the whole unit prop method
while u_literals:
nextUnit = u_literals.popleft()
# Set... | The main task of the code is to perform backtracking with unit propagation to solve a SAT-like problem. It recursively assigns variables, propagates unit clauses, checks for conflicts, and backtracks when assignments lead to contradictions. The function returns a valid partial assignment if found, otherwise False. | def backtrackWL(dict, partial_assignment, u_literals, orderVars, lefv=None):
if u_literals:
lefv, u_literals = unit_propagateWL(dict, u_literals, partial_assignment)
# If the unit prop returned False then there was a conflict (empty clause generated)
if not u_literals:
return
... |
def setVar(clause_set, var):
new_clause_set = []
for clause in clause_set:
if var not in clause:
clause_copy = clause[:]
if (-1 * var) in clause_copy:
clause_copy.remove(-1 * var)
new_clause_set.append(clause_copy)
return new_clause_set
def s... | The code tests a SAT solver's functionality by validating clause reductions and solution checks. It loads DIMACS clauses from files, verifies `setVar`/`setVars` outputs against expected results, and checks `testDPLLsolution` outcomes for specific assignments on SAT instances. Assertions ensure correctness, while `showR... | def testSuite3(showResult=True):
clauses = load_dimacs('sat_instances/sat.txt')
assert setVar(clauses, 1) == [[-2]]
assert setVar(clauses, -1) == [[]]
assert setVar(clauses, 2) == [[1], [1, -1], [-1]]
assert setVar(clauses, -2) == [[1], [1, -1]]
assert setVars(clauses, [1, -2]) == []
assert... |
def dictify(clause_set):
# Count all literals
most_common_vars = Counter(chain.from_iterable(clause_set)).most_common()
# Order the variables and create watched literal dict
order = orderVars(most_common_vars)
watched_literals = initialiseWatchedLiterals(order)
# Pure literals (if any) can be ... | The function `dpll_sat_solve` solves the Boolean satisfiability problem (SAT) using the DPLL algorithm. It takes a set of clauses and a partial assignment, checks base cases (empty clause set or unsatisfiable clauses), and employs backtracking with variable ordering to find a satisfying assignment. If successful, it re... | def dpll_sat_solve(clause_set, partial_assignment=None):
# Check possible initial conditions
if not clause_set:
return []
if [] in clause_set:
return False
dict, initial_u_literals, orderVars = dictify(clause_set)
partial_assignment = createPartialAssignment(orderVars)
resu... |
def testSuite1(showResult=True):
clauses = load_dimacs('sat_instances/unsat.txt')
result = branching_sat_solve(clauses)
assert result == False
clauses = load_dimacs('sat_instances/sat.txt')
result = branching_sat_solve(clauses)
assert result == [1, -2]
clauses = load_dimacs('sat_instances/s... | The main task of the code is to execute four test suites (testSuite1 to testSuite4) with the parameter `False`, then print a confirmation message that all tests have completed successfully. | def runAllTests():
testSuite1(False)
testSuite2(False)
testSuite3(False)
testSuite4(False)
print("All tests completed successfully") |
def switch_strategy(self, batteryStatus):
currentBatteryStatus = batteryStatus.isCharging
if currentBatteryStatus == self.lastBatteryStatus:
return # battery charging status hasnt change - dont switch fan curve
elif currentBatteryStatus != self.lastBatteryStatus:
self.l... | The main task of the code is to control fan speed based on temperature and battery status. It updates the system temperature, checks if it's time to adjust fan speed (based on a frequency interval), and triggers speed adaptation using the `adapt_speed` method. If the fan curve is switchable, it first updates the strate... | def do_control(self, force, batteryStatus):
if self.switchableFanCurve:
self.switch_strategy(batteryStatus)
self.update_temperature()
# update fan speed every "fanSpeedUpdateFrequency" seconds
if self.tempIndex % self.fanSpeedUpdateFrequency == 0:
self.adapt_speed... |
def does_train_test_file_exist(self)->bool:
try:
logging.info("Checking if training and testing file are available")
does_train_file_exist= False
does_test_file_exist= False
train_file_path= self.data_ingestion_artifact.train_file_path
test_file_path... | The main task of the code is to validate data by checking the existence of train/test files, verifying dataset schema compliance, and detecting data drift. If successful, it generates a DataValidationArtifact with validation status, file paths, and logs the result. Exceptions trigger a SalesException with error details... | def initiate_data_validation(self)-> DataValidationArtifact:
try:
self.does_train_test_file_exist()
self.validate_dataset_schema()
self.check_data_drift()
data_validation_artifact= DataValidationArtifact(schema_file_path= self.data_validation_config.schema_file_... |
def run_script(script_name, script_args):
script_args = [str(arg) for arg in script_args]
try:
result = subprocess.check_output(
[sys.executable, script_name] + script_args,
stderr=subprocess.STDOUT,
)
except subprocess.CalledProcessError as e:
return e.output... | The main task of the code is to repeatedly run a script, check for PEP8 errors using flake8 and black, automatically fix syntax/formatting issues via an AI model if errors occur, apply the fixes, and rerun the script until it executes successfully without errors. It handles both runtime crashes and linting issues throu... | def main(script_name, *script_args, model="gpt-4"):
while True:
output, returncode = run_script(script_name, script_args)
if returncode == 0:
cprint("Script ran successfully.", "blue")
# run flake8 to check for PEP8 errors
run_black(script_name)
fla... |
def align_reads(depth):
reads_1 = BASE_DIR + depth + '/ATCC_35221_Campylobacter_lari/reads_1.fastq.gz'
reads_2 = BASE_DIR + depth + '/ATCC_35221_Campylobacter_lari/reads_2.fastq.gz'
command = f'bwa mem -t 24 {DRAFT} {reads_1} {reads_2} | samtools sort > alignments_{depth}.bam; samtools index alignments_{de... | The main task of the code is to evaluate and optimize parameters for a tool (likely Pilon) across different read depths (05.0, 10.0, 15.0, 20.0) by running alignment and error analysis. It systematically tests parameter sets, tracks the minimum error count, updates the best parameters, and writes results to an output f... | def main():
global BEST_PARAMETERS
for depth in ['05.0', '10.0', '15.0', '20.0']:
align_reads(depth)
with open(OUTPUT, 'at') as f:
f.write(f'tool\tparameters\tdescription\terrors_05\terrors_10\terrors_15\terrors_20\ttotal_errors\n')
tried_parameters = set()
best_errors = float('inf')... |
def align_reads(depth):
reads_1 = BASE_DIR + depth + '/ATCC_35221_Campylobacter_lari/reads_1.fastq.gz'
reads_2 = BASE_DIR + depth + '/ATCC_35221_Campylobacter_lari/reads_2.fastq.gz'
command = f'bwa mem -t 24 {DRAFT} {reads_1} {reads_2} | samtools view --threads 3 -F 0x4 -b - | samtools fixmate -m --threads... | The main task of the code is to evaluate and identify the optimal parameters for alignment by systematically testing different configurations across varying read depths (05.0, 10.0, 15.0, 20.0). It tracks the minimum error rates achieved, updates the best parameters when lower errors are found, and logs results to an o... | def main():
global BEST_PARAMETERS
for depth in ['05.0', '10.0', '15.0', '20.0']:
align_reads(depth)
with open(OUTPUT, 'at') as f:
f.write(f'tool\tparameters\tdescription\terrors_05\terrors_10\terrors_15\terrors_20\ttotal_errors\n')
tried_parameters = set()
best_errors = float('inf')... |
def parse_args():
if len(sys.argv) != 3 and len(sys.argv) != 4:
print(USAGE)
exit(1)
global REDIS_SHAKE_PATH, LUA_FILTER_PATH, toml_template
# 1. check redis-shake path
REDIS_SHAKE_PATH = sys.argv[1]
if not Path(REDIS_SHAKE_PATH).is_file():
print(f"redis-shake path [{REDIS_S... | The code connects to a Redis cluster using credentials from a TOML config, identifies master nodes, creates work directories, generates per-node TOML configs for redis-shake, launches synchronization processes with dynamic ports, and manages signal handling for graceful shutdown. It initializes cluster connections, par... | def main():
parse_args()
# parse args
address = toml_template["source"]["address"]
host, port = address.split(":")
username = toml_template["source"]["username"]
password = toml_template["source"]["password"]
tls = toml_template["source"]["tls"]
print(f"host: {host}, port: {port}, usern... |
def play_offensive(tGrid):
turnPlayed = False
# check if user is winning and stop them if they are
if (tGrid[0] == "2") and (tGrid[1] == "2") and (tGrid[2] == "0"):
main.set_pawn(2,get_pos_string(2))
turnPlayed = True
elif (tGrid[0] == "2") and (tGrid[1] == "0") and (tGrid[2] == "2"):
main.set_pawn(2,get_pos_... | The code's main task is to determine and execute the next move in a game by prioritizing offensive strategies, then defensive if offensive fails, followed by random moves if neither applies, while checking if player 2 has won after each action. | def play():
print("Playing main")
tGrid = main.get_grid()
if (play_offensive(tGrid) == False):
print("No winning moves available. Playing defensively. . . ")
if (play_defensive(tGrid) == False):
print("No need to defend. Playing with calculations. . . ")
play_rnd()
check_if_won(2) |
def get_evaluation(req):
""" asks the human player for an evaluation """
info = req.form
show_current_guess(new_guess[0])
rightly_positioned =int(info['enternumberBlacks'])
permutated = int(info['enternumberWhites'])
#rightly_positioned = int(input("Blacks: "))
#permutated = int(input("Whites: "))... | The main task of the code is to evaluate a current guess by checking its validity, storing it with its evaluation, displaying previous guesses, and generating a new guess if needed. It validates the evaluation, appends the guess-evaluation pair to a list, shows prior guesses, and creates a new guess. If invalid, it ret... | def new_evaluation(current_colour_choices):
""" This funtion gets an evaluation of the current guess, checks
the consistency of this evaluation, adds the guess together with
the evaluation to the list of guesses, shows the previous guesses
and creates a new guess """
rightly_positioned, permutated = get_evaluat... |
def find(self, name):
if not self.contains(name):
new_node = Node(name)
self.nodes.append(new_node)
self.node_names.append(name)
return new_node
else:
return next(node for node in self.nodes if node.name == name)
def add_edge(self, parent, chil... | This function synchronizes the structure of a probing graph with a true graph by recursively adding nodes/edges present in the true graph but missing in the probing graph, and removing nodes/edges in the probing graph that don't exist in the true graph, up to a specified depth. It ensures alignment between the two grap... | def add_node(self, probing_node, true_graph, depth=10):
true_node = true_graph.find(probing_node.name)
for child in true_node.children:
if child.name not in self.node_names and depth > 0:
self.add_node(child, true_graph, depth - 1)
if self.find(child.name) not in... |
def execute_go(direction):
"""
This function, given the direction (e.g. "south") updates the current room
to reflect the movement of the player if the direction is a valid exit
(and prints the name of the room into which the player is
moving). Otherwise, it prints "You cannot go there."
"""
... | This function processes user commands by identifying the action type (e.g., "go", "take", "drop") and executing corresponding functions with the appropriate argument. It validates input length, checks item availability, and provides feedback for invalid commands or missing parameters, ensuring proper interaction with g... | def execute_command(command):
"""This function takes a command (a list of words as returned by
normalise_input) and, depending on the type of action (the first word of
the command: "go", "take", or "drop"), executes either execute_go,
execute_take, or execute_drop, supplying the second word as the argum... |
def game_makers():
"""
This function prints title of the game.
"""
print("\n\n\n\n\t\t\t-=GAME MAKERS=-\n\n\n\n")
print("Press enter to continue...")
input()
def execute_help():
print('''
\t\tSupported commands:
MOVEMENT:
GO NORTH
GO EAST
GO SOUTH
GO WEST
... | The main task of the code is to run a text-based game loop where the player completes goals by interacting with the environment, choosing actions from a menu, and executing commands. It manages game state transitions, room descriptions, and goal progression, ending when all goals are achieved. | def main():
global previous_location
game_makers()
# Instructions for user at first
execute_help()
# Main game loop - keep going whilst there are goals left
while current_goal < len(goals):
# Start higher or lower game straight away if on this goal
if goals[current_goal] == go... |
def get_stock_prices(self) -> int | float:
"""Get stock price for the given tickers
To get a price of a specific date
data = yf.download("AAPL", "2023-08-01", "2023-08-31")
"""
self.collect_tickers()
ticker_symbols = [s.code for s in self.ticker_symbols]
stock... | The main task of the code is to generate a list of `Stock` objects containing stock details like ticker symbol, name, country, purchase price, amount, and current/previous prices. It retrieves stock data from `self.stock_file`, fetches market prices, and constructs each `Stock` instance with relevant attributes before ... | def get_stocks(self) -> List:
close_prices = self.get_stock_prices()
for stock in self.stock_file["stocks"]:
ticker_symbol = self.get_ticker_symbol_by_name(stock["name"])
self.my_stocks.append(
Stock(
code=ticker_symbol,
na... |
def get_stock_prices(self) -> int | float:
"""Get stock price for the given tickers
To get a price of a specific date
data = yf.download("AAPL", "2023-08-01", "2023-08-31")
"""
self.collect_tickers()
ticker_symbols = [s.code for s in self.ticker_symbols]
stock... | The main task of the code is to aggregate stock data by name, summing amounts and purchase prices, calculating total values, and retrieving current/previous prices. It consolidates entries with the same stock name, creates Stock objects with updated attributes, adjusts purchase price per share, and returns a list of ag... | def get_aggregated_stocks(self) -> List:
"""Get an aggregated stocks"""
close_prices = self.get_stock_prices()
my_agg_stocks = {}
for stock in self.stock_file["stocks"]:
name = stock["name"]
ticker_symbol = self.get_ticker_symbol_by_name(name)
if st... |
def register_data(self, key):
if self.generate_data:
self.save_tuples.append((self.tablero,self.current_pieza,key))
def move_current(self, d_x, d_y):
if self.debugMode:
print("move_current: ", self.current_pieza)
can_move = True
res = []
... | This function handles Tetris piece movement and rotation based on key presses. If the game is over, it exits. For valid keys (left, right, rotate), it logs the input and adjusts the current piece's position or rotation. The 'down' key triggers a downward move. The core task is translating user input into game actions w... | def key_pressed(self,key:str):
if self.gameover:
return None
can_move = True
if key == tetris.DERECHA:
self.register_data(key)
self.move_current(1,0)
elif key == tetris.IZQUIERDA:
self.register_data(key)
self.move_curre... |
def get_tealish_list():
return get_contracts_list('../contracts/')
def get_teal_list():
return get_contracts_list('../contracts/build/')
def run_compile():
file_list, complete_file_list = get_tealish_list()
return compile_contracts(file_list, complete_file_list)
def load_teal_file_by_name(teal_file):
... | The main task of the code is to load a specified contract file (.teal) by name, recompiling contracts if needed based on changes detected in their folders. It filters the compiled contract list for a match, returns the file if found, or raises an error if the contract name is invalid. | def load_contract(contract_name, force_compile=True):
tealish_list, _ = get_tealish_list()
teal_list, _ = get_teal_list()
# check changes in contracts folders
if (force_compile or len(tealish_list) != len(teal_list)):
run_compile()
teal_list, _ = get_teal_list()
filtered_list = lis... |
def setup_dataloader(args):
"""
return:
- train_loader: torch.utils.data.Dataloader
- val_loader: torch.utils.data.Dataloader
"""
# ================== TODO: CODE HERE ================== #
# Task: Load the training data from provided json file.
# Perform some preprocessing to toke... | The main task of the code is to train and evaluate a machine learning model for a classification task. It initializes logging, loads data, builds a model, configures optimizer/loss functions, and either runs validation or training based on the `args.eval` flag. The code handles device placement (CPU/GPU), data loading,... | def main(args):
wandb.init(project="hw3", entity="alsayedm")
device = get_device(args.force_cpu)
# get dataloaders
train_loader, val_loader, v2id = setup_dataloader(args)
loaders = {"train": train_loader, "val": val_loader}
# build model
model = setup_model(args, device)
print(model)
... |
def groundtruth_callback(self, data : dict):
"""
Stores the groundtruth from the incoming data.
Parameters
========
data: dict.
The dictionary in which the groundtruth.
"""
lat = np.average(data["groundtruth"]["latitude"])
lon = np.average(dat... | The main task of the code is to process incoming data (odometry, images, GPS, groundtruth) by updating localization algorithms (MCL/GAPPF), appending estimated states to a trajectory, computing metrics, and periodically updating the interface. It handles data input, filters relevant information, triggers callbacks for ... | def spin_once(self):
# Data input
if not self.data_manager.has_next():
return False
data = self.data_manager.next()
# For computing the time metrics purposes
curr_ts = data["timestamp"]
# For computing the error metrics
if data["groundtruth"]... |
def from_disk(self,load_dir : str) -> bool:
flag_loaded_model = False
flag_loaded_params = False
if os.path.isfile(load_dir+"/recognition_model.data"):
with open(load_dir+"/recognition_model.data", "rb") as f_rec_model:
self.recognition_model = pickle.load(f_rec_model)
flag_loaded_model = True
if os.... | This code initializes a detector that combines YOLOv3-tiny for object detection and a KNN-based recognition model for classifying detected objects. It configures parameters like detection threshold, device selection (CPU/GPU), and cache management. The detector loads pre-trained weights, sets up color mappings for clas... | def __init__(self, threshold : float, flag_use_cpu : bool = True, reset_cache : bool = False):
"""
Parameters
==========
threshold: float.
The threshold value for accepting a detection as valid.
flag_use_cpu: bool.
Whether to use the CPU (True) or the GPU (False).
reset_cache : bool.
The recogniti... |
def letterbox(self, img_l : np.array, new_shape : int = 416, color : tuple = (128, 128, 128), mode : str ='auto') -> np.array :
"""
Resize a rectangular image to a 32 pixel multiple rectangle,
https://github.com/ultralytics/yolov3/issues/232
Parameters
==============
img_l : numpy.array.
The image to... | The function detects and recognizes traffic signs in an RGB image by applying object detection (with optional confidence/NMS thresholds), scaling bounding boxes, and classifying detected objects. It returns bounding boxes, their class labels, and an optionally visualized image with annotations. | def detect_and_recognize(
self,
img_rgb : np.array,
conf_thres : float = None,
nms_thres : float = 0.5,
visualize : bool = False
) -> Union[list, list, np.array]:
"""
Detects signs and recognizes which in which class they belong.
Parameters
==============
img_rgb: numpy.array.
The input ima... |
def read_census_shape(area, county=''):
"""
Read California census area shapefile into a GeoDataFrame and return it filtered to a county if specified
area: 'blockgroup', 'block', 'pop'
county: 'LA', 'Fresno'
"""
if area == 'blockgroup':
area = gpd.read_file('data/ca_blockgroup/tl... | This function aggregates values from a specified pollution column in facility data into geographic areas (blockgroups, blocks, grids) by summing values within each polygon. It returns a geopandas DataFrame with either actual sums or percentage shares of total values, adjusting for county-specific damages if enabled. Re... | def agg_facilities_column(area, county, column, output='percent', damages=False, save=False):
"""
Return geopandas dataframe with values of column added up for all facilities in each polygon
area: 'blockgroup', 'block', 'grid'
county: 'LA', 'Fresno'
column: 'PM2.5T', 'PM10T', 'PMT', 'SOX... |
def agg_pmeds_column(county, column, scc='', output='percent', updated=True, damages=False, save=False):
"""
Return geodataframe of PMEDS column added up for each grid cell
county: 'LA', 'Fresno'
column: 'PM2.5T', 'PMT', 'SOXT', 'NOXT', 'COT', 'NH3', 'TOGT'
scc: 'LD', 'HD', '' for all
... | The function `combine_pmeds_facilities` merges PMEDS and facility data into a geospatial grid, aggregating values by grid cell (`i`, `j`). It calculates either **percent** (normalized to total) or **actual** values of a specified pollutant column (e.g., PM2.5T) for each cell, optionally applying 2015 updates or damage ... | def combine_pmeds_facilities(county, column, scc='', output='percent', updated=True, damages=False, save=False):
"""
Return geodataframe of column added from PMEDS and facilities for each grid cell
county: 'LA', 'Fresno'
column: 'PM2.5T', 'PMT', 'SOXT', 'NOXT', 'COT', 'TOGT'
scc: 'LD', '... |
def shape_pop(area, save=False):
"""
Return geodataframe of population in each polygon of area added up. Uses centroids of original population blocks to match to new area.
area: 'blockgroup', 'grid'
county: 'LA', 'Fresno'
save: Whether to save frame to shapefile
"""
if area == 'b... | The function combines population and pollution data for specified geographic areas (blockgroups or grids) by spatially joining/merging datasets, multiplying pollution values by population counts, and returning a geodataframe. It supports saving results as shapefiles with appropriate projections. Input parameters define... | def pop_emissions(area, county, column, save=False):
"""
Return geodataframe of population in each polygon of area added up and multiplied by pollution
area: 'blockgroup', 'grid'
county: 'LA', 'Fresno'
column: 'PM2.5T', 'PMT', 'SOXT', 'NOXT', 'COT', 'TOGT'
save: Whether to save f... |
def shape_income(county, save=False):
"""
Return geodataframe of percentile of poverty in shape
area: 'block', 'grid'
county: 'Los Angeles', 'Fresno'
save: Whether to save frame to shapefile
"""
gdf = gpd.read_file('data/ces3shp/CES3Results.shp').to_crs(epsg=4326)
gdf = gdf[g... | This function combines poverty data with emissions data for specified counties, aggregates emissions values within poverty zones, and optionally saves the result as a shapefile. It processes spatial data by converting emissions grids to points, performs spatial joins, sums emissions per zone, and returns a merged dataf... | def poverty_emissions(county, column, save=False):
"""
county: 'Los Angeles', 'Fresno'
column: 'PM2.5T', 'PMT', 'SOXT', 'NOXT', 'COT', 'TOGT'
save: Whether to save frame to shapefile
"""
pov = shape_income(county)
# county = 'LA' if county == 'Los Angeles'
em = combine_pmeds_... |
def load(file):
f = open(file)
data = f.readlines()
f.close()
return data
def two_sums(total, expenses):
global answer
if len(expenses) == 1:
return False, []
left = expenses[0]
rest = expenses[1:]
found = False
for x in rest:
if left + x == total:
ans... | The code calculates whether two or three numbers in a list of expenses sum to a given total. It loads expenses from a file, checks combinations based on the 'operators' parameter (2 or 3), and returns the product of a boolean result and the matching values. | def calc(filename, total, operators):
values = []
result = False
the_list = load(filename)
expenses = [int(x) for x in the_list]
if operators == 2:
result, values = two_sums(total, expenses)
if operators == 3:
result, values = three_sums(total, expenses)
return mult(result, v... |
def startmqtt():
if RAISE_NOTICE and MQTT_HOST != "" and MQTT_HOST != None and not mqttclient.is_connected():
mqttclient.on_log = on_log
mqttclient.connect(host=MQTT_HOST, port=MQTT_PORT ,keepalive=300)
def process_msg(msg):
planeloc = (msg.get("lat"), msg.get("lon"))
dist = distance.distanc... | The main task of the code is to establish a socket connection to receive JSON-formatted messages, process them using `process_msg()`, and periodically clean up expired flight data via `expireflights()` based on a time limit. It also initializes MQTT, handles connection errors, and maintains a socket for continuous data... | def __main__():
i = 0
lastCleanup = datetime.datetime.now()
startmqtt()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
f = s.makefile(mode="r",buffering=2048,encoding='ascii')
while True:
try:
line = f.readli... |
def wait_click_css(css, driver, timeout, task_id):
element = wait_css(css, driver, timeout, task_id)
if element is not None:
try:
element.click()
except ElementClickInterceptedException:
driver.execute_script("arguments[0].click();", element)
except Exception as e... | The code automates the checkout process by identifying stages (address selection, credit card input, security code, final order confirmation) using CSS selectors. It delegates to `checkout_starting_from` with stage numbers when elements are detected, logging progress. If the initial checkout button isn't clicked, it re... | def checkout(self, driver, timeout, task_id):
# Click 'I'm ready to checkout' button
if wait_click_css('button[class="Button__ButtonWithStyles-y45r97-0 gmmYfU"][data-test="checkout-button"]', driver, timeout, task_id) is None:
return False
while True:
# Select address
... |
def Generalize(Table_original,hierarchy):
# The contents of hierarchy is Sex, Race, Marital status, Age respectively
Table = copy.deepcopy(Table_original)
'''
Note!!!
In python, when applying '=', e.g. a = b, we will change the value of b if we change a
That is, if we do nothing abo... | The main task of the code is to find the optimal "ReleaseVector" from a lattice structure that minimizes a loss metric while ensuring data releasability. It performs a binary search on lattice levels, generalizing data with candidate vectors, checking releasability via clustering, and tracking the vector with the lowes... | def Samarati(data,Lattice,LM,HV): # Hierarchy Vector
low = 0
high = 8
while (low < high):
mid = int((low + high)/2)
for VECTOR in Lattice[mid]:
GTC = Generalize(data, VECTOR) # Generalized table candidate
if Releasable(Cluster(GTC)) == 0:
low = mid + ... |
def corr_graph1():
return st.header('Stock and Economic Data Correlation'), st.plotly_chart(bound_bar_plot())
def stock_graphs():
return st.header('Data Graphs'), st.plotly_chart(px.line(stock_analysis_df, y= stock_graph_multi_select(), width = 1000, height = 600))
def ml_results_tab():
return st.title('Ban... | The main task of the code is to create a multi-tabbed Streamlit application with four sections: "App instructions" (displaying a description), "Correlation" (showing correlation graphs), "Stock Graphs" (visualizing stock data), and "Machine Learning Results" (presenting ML outcomes). Each tab is populated with specific... | def app_tabs_application():
tab01, tab1, tab2, tab4 =st.tabs([ "App instructions", "Correlation", "Stock Graphs", "Machine Learning Results"])
with tab01:
st.markdown(app_description , unsafe_allow_html=True)
with tab1:
corr_graph1()
with tab2:
stock_graphs()
#with ta... |
def predict_show(self):
"""Preprocess and predict digits in a raw image.
Then show predictions drawn as boxes with confidence levels"""
# preprocess image
processed_image = self.preprocess_image()
# find contour boxes
boxes = self.find_contour_boxes(processed_image)
... | This code defines a Paint application interface with a canvas for drawing, two buttons ("Guess" and "Clear"), and event handling for real-time drawing. It initializes screen regions, manages mouse input for drawing, updates UI elements, and maintains a loop for rendering the interface until the user exits. | def paint_page(self):
"""the page that paint runs"""
# image
self.prediction = None
self.proba_prediction = None
self.is_predicted = False
# screen, frames and canvas
self.screen_rect = self.screen.get_rect()
self.background_color = self.CREAM
se... |
def find_confusion_matrix(test_data, tree):
""" Compute the confusion matrix based on predictions from the tree.
In the resulting matrix:
- Rows represent the actual classes.
- Columns represent the predicted classes.
Args:
test_data (np.array): Array of testing examples. Each instance is
... | The code evaluates a trained decision tree's performance on test data by computing key metrics: confusion matrix, accuracy, precision, recall, and F1 score per class. It uses helper functions to derive these metrics from the test data and trained tree, then returns them as a tuple. The primary goal is to quantify the m... | def evaluate(test_data, trained_tree):
""" Evaluate the trained tree's performance on the test data.
Compute the evaluation metrics based on the trained tree and the test
data. These metrics are: the confusion matrix, the accuracy, the precision
per class, the recall per class, and the f1 measure per c... |
def find_split(data):
""" Chooses the attribute and the value that result in the highest
information gain.
Args:
data (np.array): dataset
Returns:
tuple: best feature and value to split the dataset
"""
best_gain = 0
best_split = None
for feature in range(data.shape[1] ... | The main task of the code is to recursively construct a decision tree by splitting the dataset based on features. It checks if all labels in the current data are identical to create a leaf node, otherwise finds the optimal split, recursively builds left and right subtrees, and combines them into an internal node with t... | def decision_tree_learning(data, depth=0):
""" Recursive Decision Tree Algorithm.
Args:
data (np.array): dataset
depth (int): the depth of the node. Defaults to 0
Returns:
dict: A recursive dictionary representing the decision tree.
Each node in the tree is either a l... |
def isReady(self):
return self._i2c.read(self.PN532_ADDRESS, 1) == b"\x01"
def writeCommand(self, command, params=[]):
data = bytearray(2 + len(params))
data[0] = self.HOSTTOPN532
data[1] = command & 0xFF
for i, val in enumerate(params):
data[2 + i] = val
self... | This code manages RFID communication states, sends configuration and tag-detection commands, processes responses, updates tag tracking, triggers robot actions on tag detection, and updates scores. It ensures proper timing between commands, handles ACKs/responses, and maintains system state transitions for RFID operatio... | def handleRFID(self, globals):
try:
currentRFIDTime = running_time()
if currentRFIDTime < (self.previousCommandTime + self.I2C_DELAY):
return None
if self.previousCommand == self.COMMAND_INLISTPASSIVETARGET:
if (
currentRFI... |
def turnLeft(self):
if self.state == DriveState.READY:
if self.getLinesensorStatus() & self.LEFT_LF:
self.linesPassed = 0
self.isOnLine = True
else:
self.linesPassed = 1
self.isOnLine = False
self.state = DriveSt... | This code processes drive commands based on the current state. If in the READY state, it dequeues and executes commands like turning or moving forward. If in other states (e.g., turning, moving), it continues executing the current action. Returns True if a command was processed, False if no commands remain. | def handleDrive(self):
if self.state is DriveState.READY:
if not len(self.globals.commands):
return False
command = self.globals.commands[0]
self.globals.commands = self.globals.commands[1:]
if command == "S":
self.globals.tags.clea... |
def get_default_hyperparameter_space(self):
if "mlp" in str(self.model).lower():
solver_list = ['adam', 'sgd']
learning_rate_list = [0.00001, 0.0001, 0.001, 0.005, 0.01, 0.05, 0.1]
alpha_list = [0.00001, 0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 3, 10]
layer_... | This code performs hyperparameter tuning with conformal prediction for model optimization. It iterates through hyperparameter combinations, evaluates validation loss, and uses conformal quantiles to ensure confidence intervals. It handles regression/classification, applies early stopping, outlier removal, and logs perf... | def fit(self,
X,
y,
hyper_reg_model,
custom_loss_function='accuracy_score',
min_training_iterations=20,
tolerance=20,
early_stop=60,
early_timeout=3600,
train_val_split=0.6,
validating_framework='trai... |
def get_default_hyperparameter_space(self):
if "mlp" in str(self.model).lower():
solver_list = ['adam', 'sgd']
learning_rate_list = [0.00001, 0.0001, 0.001, 0.005, 0.01, 0.05, 0.1]
alpha_list = [0.00001, 0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 3, 10]
layer_... | The code performs a **random search over hyperparameter combinations** to optimize model performance using cross-validation. It evaluates each hyperparameter set by calculating validation loss, tracks metrics like accuracy and variance, and logs results. The search terminates early if the maximum runtime or iteration l... | def fit_random_search(self, X, y, custom_loss_function=None, n_searches=60, max_runtime=3600,
train_val_split=0.6,
validating_framework='train_test_split', k_fold_splits=None,
prediction_type="classification",
prespl... |
def __start__(self):
""" Issue bus start sequence """
wiringpi.pinMode(2, self.OUTPUT) # SDA Low
self.__delay__()
def __write_byte__(self, val):
""" Write a byte """
for b in range(8):
wiringpi.pinMode(3, self.OUTPUT) # SCL Low
if (0x80 >> b) & val:
... | This function writes bytes to an I2C device by sending an address followed by data bytes, managing bus start/stop conditions, and handling errors like NACK or clock/data stretch timeouts. It prepares the I2C address, transmits each byte, checks for transmission success, and issues a restart or stop condition based on t... | def __write__(self, addr, outArr, restart = False):
""" Write bytes """
outBuffer = [(addr << 1)] # left-shift I2C address and clear read bit
outBuffer.extend(outArr) # outBuffer now contains the address and outArr
self.__start__() # issue bus start
for b in range(len(outBuffer)... |
def __start__(self):
""" Issue bus start sequence """
wiringpi.pinMode(2, self.OUTPUT) # SDA Low
self.__delay__()
def __write_byte__(self, val):
""" Write a byte """
for b in range(8):
wiringpi.pinMode(3, self.OUTPUT) # SCL Low
if (0x80 >> b) & val:
... | The main task of this code is to read multiple bytes from an I2C device. It sends a start condition, writes the device address with a read bit, reads specified bytes with ACK/NACK handling, and manages errors like NACK or timeouts by resetting pins. It returns the result status and a buffer containing the read bytes, e... | def __read__(self, addr, inBytes):
""" Read bytes """
addr = (addr << 1) | 0x01 # left-shift I2C address and set read bit
inBuffer = []
self.__start__() # issue bus start
result = self.__write_byte__(addr) # write the address and read bit
if result != self.SUCCESS: # ch... |
def __set_gpio_pins__(self):
""" Set pins as GPIO """
self.BusActive = True
wiringpi.pinMode(3, self.INPUT) # set SCL pin as input
wiringpi.pinMode(2, self.INPUT)
def __write__(self, addr, outArr, restart = False):
""" Write bytes """
outBuffer = [(addr << 1)] # left-sh... | The main task of the code is to perform I2C communication by writing data to a device (if `outArr` is non-empty) and/or reading data (if `inBytes` > 0), while managing GPIO pins and handling errors. It ensures proper pin restoration after operations and raises an I/O error on failure. | def transfer(self, addr, outArr, inBytes):
""" Write and/or read I2C """
self.__set_gpio_pins__()
if(len(outArr) > 0): # bytes to write?
if self.__write__(addr, outArr, inBytes) != self.SUCCESS:
self.__restore_gpio_pins__()
raise IOError("[Errno 5] I... |
def munchClustering(iter, matrix, numberOfClasses):
cycles = 50
startingSolution = generateSolution(matrix, numberOfClasses)
bestSolution = startingSolution
bestEVM = EVMFitness(startingSolution, matrix)
for cycle in range(1,cycles+1):
# Generates new Solution for each cycle
... | The code processes each file in the 'Systems\MDGs' directory by extracting class information, generating a matrix, performing clustering, and saving results to CSV files while tracking the best clustering evaluation metric (EVM). | def directoryNavigation():
location = pathlib.Path('Systems\MDGs')
for mdg in tqdm(location.iterdir()):
numberOfClasses = len(he.classNames(mdg))-1
matrix = he.bitmapStripper(mdg)
clusterOutput, bestEVM = munchClustering(1000,matrix, numberOfClasses)
saveCluster2CSV(clusterOutput... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.