dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def convertDigitsToHex(self, raw_data: list=None) -> str:
"""
Converts the digits from underscores and pipes to integers.
"""
if raw_data is None:
raw_data = self.raw_data
account_number = ""
for nth_term in range(round(len(raw_data[0])/4)):
for index in range(len(digit_matrix)+1):
if self.get... | This code initializes an object to process and validate account numbers. It stores input data, converts digits to hexadecimal, checks validity, and determines a status (None, "ILL", or "ERR"). If invalid, it generates possible corrections via guessILL() or guessERR(), updating the account number and possibilities accor... | def __init__(self, line0: list, line1: list, line2: list):
self.raw_data = [
line0,
line1,
line2
]
self.possibilities = []
self.account_number = self.convertDigitsToHex()
if self.isValid() and '?' not in self.account_number:
self.status = None
elif not self.isValid() and '?' in self.account_n... |
def print_info(text: str, *, color: str = "blue", prefix: str = "⚙️ ", **kwargs: Any) -> None:
if len(prefix) > 0:
text = f"{prefix} {text}"
_cprint(text, color=color, **kwargs)
def using_tmp_envs(env: Dict[str, Any]) -> Generator:
prev_values = {k: os.environ.get(k) for k in env.keys()}
for k,... | The function executes a shell command, optionally printing it if verbose. It runs the command in a temporary environment and exits with an error if the command fails (non-zero return code). | def exec_or_bail(cmd: str, *, verbose: bool = False, env: Optional[Dict[str, Any]] = None) -> None:
if verbose:
print_info(f"Executing command '{cmd}' ...\n")
with using_tmp_envs(env or {}):
code = subprocess.call(shlex.split(cmd))
if code != 0:
bail() |
def print_info(text: str, *, color: str = "blue", prefix: str = "⚙️ ", **kwargs: Any) -> None:
if len(prefix) > 0:
text = f"{prefix} {text}"
_cprint(text, color=color, **kwargs)
def exec_or_bail(cmd: str, *, verbose: bool = False, env: Optional[Dict[str, Any]] = None) -> None:
if verbose:
pr... | The main task of the code is to execute a command, print informational messages, and exit the program with a success status if the command completes without errors. It uses `exec_or_bail` to run the command, handles verbosity and environment settings, and outputs a green "✅ Success" message before terminating via `sys.... | def exec_and_quit(msg: str, cmd: str, *, verbose: bool = False, env: Optional[Dict[str, Any]] = None) -> None:
print_info(msg)
exec_or_bail(cmd, verbose=verbose, env=env)
cprint("✅ Success.", color="green")
sys.exit(0) |
def __parser_midi(midi_file):
midi_data = converter.parse(midi_file)
_elements_of_midi_file = midi_data[1]
stream_1, stream_2 = _elements_of_midi_file.getElementsByClass(stream.Voice)
for j in stream_2:
stream_1.insert(j.offset, j)
_stream = stream_1
for i in _stream:
if i.quarte... | This function converts a MIDI file into structured data for machine learning. It parses MIDI measures and chords, processes them into sequences, extracts musical features, and returns processed data (X, Y, number), chord information, dictionaries, and the original corpus for training or analysis. | def midi_to_data(midi_file):
_measures, _chords = __parser_midi(midi_file)
_structure = []
for ix in range(1, len(_measures)):
_stream = stream.Voice()
for i in _measures[ix]:
_stream.insert(i.offset, i)
c = stream.Voice()
try:
for j in _chords[ix]:
... |
def _download_dataset(self):
"""Download dataset files if not already present.
`self.dataset_url` is expected to point to a YAML file with the
following structure:
```
n_parts: <number of parts>
md5_hash_parts:
- <md5 hash of part 1>
- <md... | The main task of the code is to load and preprocess a reinforcement learning dataset from a Zarr store, returning a structured dictionary containing observations, actions, rewards, terminals, timeouts, and images. It handles parameters like clipping observations, specifying data ranges, and decompressing images, ensuri... | def get_dataset(
self,
zarr_path: Union[str, os.PathLike] = None,
clip: bool = True,
rng: Optional[Tuple[int, int]] = None,
indices: Optional[np.ndarray] = None,
n_threads: Optional[int] = None,
) -> Dict[str, Any]:
"""Get the dataset.
When called for... |
def sample_all_categories(sess, ops, config, num_samples, sub_dir):
categories = [i for i in range(Arch.num_cat)]
for category in categories:
sample_category(sess, ops, config, category, num_samples, sub_dir)
def expand_labels(labels):
one_hot_labels = one_hot(labels)
M = one_hot_labels.shape[0]... | This code trains a Generative Adversarial Network (GAN) using TensorFlow. It loads a dataset, iterates over epochs and batches, runs discriminator and generator training operations, logs losses, and saves checkpoints. The training loop uses feed dicts with images, labels, and random codes, updating model parameters and... | def train(sess, ops, config):
writer = tf.summary.FileWriter(config.summary_dir, graph=tf.get_default_graph())
saver = tf.train.Saver()
# prepare data
loader = DatasetLoader()
dataset, num_batches = loader.load_dataset(config)
iterator = dataset.make_initializable_iterator()
next_batch = it... |
def initialPopulation(populationSize, genes):
population = []
for i in range(0, populationSize):
population.append(createChromosome(genes))
return population
def rankChromosomes(population):
fitnessResults = {}
for i in range(0,len(population)):
fitnessResults[i] = Fitness(populatio... | The code implements a genetic algorithm to optimize a population of chromosomes (page sequences) over generations. It initializes a population, ranks chromosomes by fitness, evolves them via selection, elitism, and mutation, tracks progress, and returns the best chromosome and final time. The goal is to minimize time, ... | def geneticAlgorithm(genes, popSize, eliteSize, mutationRate, generations):
population = initialPopulation(popSize, genes)
pop = []
for a in population:
temp=[]
for b in range(0, len(a)):
temp.append(a[b]['pageName'])
pop.append(temp)
print(pop)
firstRankedChromo... |
def select_parents(self):
"""
Selects parents based on fitness proportionate selection.
Performs a windowing on fitness beforehand to increase
the chance for better solutions to be picked. If there
is to little diversity in the population, population is forced
to evolve, ... | The code evolves a population by selecting parents, generating offspring via PMX crossover, applying mutation, and replacing the current population with the new offspring. | def evolve(self):
"""
Evolves the population
Ends by replacing the population with the new
one.
:return:
"""
# Evolve population
self.parents = self.select_parents() # Parents selection
self.offsprings = self.pmx(self.pmx_prob) # Create offspring... |
def is_valid_hit(self, dir):
return (self.is_in_beat_window() and not self.hit_this_beat
and self.current_beat < self.beatmap.len
and self.beatmap.angles_abs[self.current_beat] == dir)
def delta(self):
if self.current_beat < self.beatmap.len:
tol = self._current_beat... | The code evaluates a hit's validity and timing, returning scores based on accuracy: 1000 for perfect hits, 1000*(1-delta) for near hits, -200 for invalid hits, and -1000 for misses. It also sets `hit_this_beat` to True when a valid hit occurs. | def register_hit(self, dir):
if not self.is_valid_hit(dir):
return -200
delta = abs(self.delta())
if self.is_in_perfect_window():
self.hit_this_beat = True
return 1000
elif self.is_in_beat_window():
self.hit_this_beat = True
re... |
def test_data(self):
# Load for Sample code
infile = open('./resource/script.tor', 'r')
self.qt.textEdit.setPlainText(infile.read())
abs_path = os.path.abspath('./resource/')
self.qt.lineEdit.setText(abs_path)
self.list_image_load_on(abs_path)
def action_menu_save(self):
... | The code initializes a main window GUI by setting up menu actions (save, exit, help) and buttons (capture, run script), along with workspace configuration, using PyQt/PySide framework. | def __init__(self, MainWindow, qt_windows):
self.qt = qt_windows
self.test_data()
self.action_menu_save()
self.action_menu_exit()
self.action_menu_help()
self.action_button_capture()
self.action_button_run_script()
self.action_set_workspace() |
def generate_cropped_tiles(self, output_dir):
"""
Two-stage generation:
1. Use convert's -crop function to write tilesets at each of the scaling factors appropriate for the image (e.g. tiles at 256, 512, 1024 px on a side, etc.) Stores intermediate files to a temporary directory
"""
... | The main task of the code is to generate an IIIF-compliant image output by creating a directory structure, generating cropped tiles for different zoom levels, producing reduced-resolution image versions, and writing an info.json file that describes the image and its tiles. This prepares the image for use in online view... | def create_iiif_0(self, output_dir):
"""
Run the tiling, resizes, and info.json generation all together
"""
os.makedirs(output_dir)
self.generate_cropped_tiles(output_dir)
self.generate_reduced_versions(output_dir)
self.write_info(output_dir) |
def game_page():
st.write('# Who is the boss? 👑 Who sucks? 🤮 ')
df = state.time_df.copy().reset_index(drop=True)
df.Date = pd.to_datetime(df.Date)
get_winner_and_looser_percentage_change_for_timeframe(df.copy(), 'Daily')
st.markdown('---')
get_winner_and_looser_percentage_change_for_timeframe(... | The main task of the code is to display a main page with navigation buttons for "Game," "Your Portfolio," "Edit Portfolio," and "Logout." It uses state management to track the current page (game, portfolio, or edit) and renders the corresponding page function based on user interactions. The "Logout" button triggers a l... | def main_page():
if 'main_page' not in state:
state.main_page = 'game'
st.markdown(f'## Welcome, {state.user}')
cols = st.columns(4)
game_button = cols[0].button('Game')
portfolio_button = cols[1].button('Your Portfolio')
edit_button = cols[2].button('Edit Portfolio')
cols[3].button(... |
def set_cool_game_vibe_camera_position(self):
default_camera_view = pb.getDebugVisualizerCamera()
cam_dist = default_camera_view[10]
"""
cam_target = default_camera_view[11]
cam_yaw = default_camera_view[8]
cam_pitch = default_camera_view[9]
pb.resetDebugVisualize... | The code runs a simulation where an agent navigates a lane, capturing images, steering angles, and velocities while avoiding collisions. It continuously updates the agent's pose, moves obstacles, and saves training data. The loop stops when a collision or lane exit occurs. Post-simulation, it prompts to save trajectori... | def gather_data(self):
""" run the simulaton and save data """
enough_data_created = False
can_proceed = True
while can_proceed: # not enough_data_created:
# if agent in collision then stop the game
can_proceed = not self.agent.is_collision_detected() and self.a... |
def spawn_random_obstacles_cars(self):
dir_with_cars = os.path.join(os.getcwd(), 'urdfs/real_cars')
for i, file in enumerate(os.listdir(dir_with_cars)):
print("file=", file)
if file.endswith('.urdf'):
# obs_id = pb.loadURDF(os.path.join(dir_with_cars, file), self.... | This code runs a simulation by either generating random obstacles or an evaluation course, then gathers data via keyboard input or evaluates an AI model based on flags. It manages object movement, resets positions, and ensures image saving, terminating with a "Simulation stopped" message. | def run(self, keyboard_steering, ai_steering, eval_run=False, **kwargs):
""" whole procedure of creating a simulation
moves objects, resets their position and makes sure that agent saves images"""
if not eval_run:
self.spawn_random_obstacles_cars()
else:
# do eva... |
def date_converter(start_date, end_date, max_period = 7):
"""
The court website limits search of records to up to 7 days. This function
breaks a given time period into several, smaller time periods containing up to max_period days.
Inputs:
start_date (str): format should be mmddyyyy
end_dat... | The code scrapes eviction court cases from Hamilton County's Clerk of Courts website using Selenium, iterating over date ranges converted from input strings. It handles timeouts by restarting the browser, processes each period, scrapes data, and returns a normalized pandas DataFrame of results. | def run_scraper(self, start_date, end_date):
"""
Scrapes eviction court cases from the Hamilton County
Clerk of Courts website, using "Selenium" package:
https://www.courtclerk.org/records-search/municipal-civil-listing-by-classification/.
Inputs:
start_date (str): mu... |
def get_component_season_patch(self, chip_identifier, chip_geometry, component, season = None):
"""
extracts a geometry from a component/season
"""
is_ascending = lambda x: x[-1]>x[0]
coords = np.r_[chip_geometry.boundary.coords]
minlon, minlat = coords.m... | The function `get_chip` compiles multi-season SAR data into a structured xarray Dataset, combining polarimetric, coherence, fit, and geometry components. It reads patches, verifies coordinate consistency, aggregates data arrays, defines geospatial coordinates, constructs a raster transform, and writes metadata. The out... | def get_chip(self, chip_identifier, chip_geometry):
et = timer['t']
# read all chip geometry in all files
with et('getting patches'):
ppol = [[self.get_component_season_patch(chip_identifier, chip_geometry, c, s) \
for c in self.pol_components_names] for s in... |
def select_starttime_most_frequent_any_direction(zz):
tile_granules = select_starttime_most_frequent(zz, direction='asc')
if len(tile_granules)==0:
tile_granules = select_starttime_most_frequent(zz, direction='desc')
return tile_granules
def select_deltadays_lte_48(zz):
return zz[zz['Days in Pai... | The function downloads and processes SAR data granules containing a specified tile geometry, combines them into a NetCDF file, and handles retries/skips. It filters granules, selects based on mode, downloads data, aligns dimensions, merges datasets, and saves results if successful. | def download_job( chip,
tiles_folder,
granules_download_folder,
global_asf_query_result,
username,
password,
mode='most-frequent',
no_retry = False... |
def get_option_values(self, data):
options = []
# Using numeric selection values, used for list indices after verification
selections = [f'{i+1}' for i in range(len(data))]
# Add each option to the list
for i in range(len(data)):
current_option = f'{i + 1}: {data[i].... | This function displays a game screen with left and right combatants, presents selectable options, captures and validates user input, then returns the selected option value. | def display_game_screen(self, options_name, options, left_combatants, right_combatants, screen_title="BATTLEFIELD", left_cell_title="ROBOTS", right_cell_title="DINOSAURS"):
# Turn data into displayable options and selection values
formatted_options = self.get_option_values(options)
valid_selecti... |
def mask_indicies(mask):
nonzero = np.nonzero(mask)
return zip(nonzero[0], nonzero[1])
def poisson_sparse_matrix(points):
# N = number of points in mask
N = len(list(points))
A = lil_matrix((N,N))
# Set up row for each point in mask
for i,index in enumerate(points):
# Should hav... | The code solves a Poisson equation to blend a source image into a target image using boundary constraints. It constructs a sparse matrix $ A $, computes a right-hand side vector $ b $ incorporating Laplacian values from the source and target boundary conditions, solves $ Ax = b $ via Conjugate Gradient, then replaces t... | def process(source, target, mask):
indicies = list(mask_indicies(mask))
N = len(indicies)
# Create poisson A matrix. Contains mostly 0's, some -4's and 1's
A = poisson_sparse_matrix(indicies)
# Create B matrix
b = np.zeros(N)
for i,index in enumerate(indicies):
# Start with left ha... |
def _forecast_(i, j, med_occ, forecast_date):
arbor_surge_index = surge_index(med_occ[0])
golf_surge_index = surge_index(med_occ[1])
cyber_surge_index = surge_index(med_occ[2])
_perch_arbor_suites_(i, j, arbor_surge_index, forecast_date)
_golf_course_(i, j, golf_surge_index, fo... | This function processes a spreadsheet to identify rows matching the current and upcoming months (today, tomorrow, day after tomorrow). It then checks each row's date against today's date, and if matched, calls forecast functions for the current day, next day, and day after tomorrow using specific cell positions and med... | def _forecast_data_(sheet, med_occ):
for i in sheet:
i_str = str(i)
sheet_month = re.findall(r"'(.*?)'", i_str)
sheet_month = sheet_month[0]
sheet_month = sheet_month[:3]
if str(sheet_month).strip() == str(todays_date_month).stri... |
def get_connection(self):
if self._connection is None:
extra_args = {}
if self._tmp_credentials is not None:
extra_args['aws_access_key_id'] = self._tmp_credentials['AccessKeyId'],
extra_args['aws_secret_access_key'] = self._tmp_credentials['SecretAccess... | This method retrieves an item from a specified database table using a given key. It serializes the key, queries the table via a connection, checks if the response contains valid item data, and returns the deserialized item if found. If the response is invalid or empty, it returns None. | def get_item(self, table_name, key, **kwargs):
response = self.get_connection().get_item(TableName=table_name, Key=self.type_serialize(key), **kwargs)
if response is None or len(response) == 0 or 'Item' not in response:
return None
return self.type_deserializer(response['Item']) |
def get_connection(self):
if self._connection is None:
extra_args = {}
if self._tmp_credentials is not None:
extra_args['aws_access_key_id'] = self._tmp_credentials['AccessKeyId'],
extra_args['aws_secret_access_key'] = self._tmp_credentials['SecretAccess... | This function retrieves multiple items from a DynamoDB table in batches of up to 99 keys, handling pagination for unprocessed keys. It constructs batch requests with optional projection expressions, deserializes responses, converts Decimal values using a factory function, and aggregates results into a list for return. | def batch_get_items(self, table_name, keys, projection_expression=None, expression_attribute_names=None,
decimal_factory=decimal_to_number, **kwargs) -> list:
conn = self.get_connection()
ret = []
while len(keys) > 0:
batch_keys = keys[:99]
keys = ... |
def getallfiles(list_df):
file_df=list_df[3]
filecolumns=list(file_df.columns)[1:]
# print(filecolumns)
total_files=[]
for col in filecolumns:
total_files=total_files+list(file_df[col])
# print(total_files)
total_files=list(dict.fromkeys(total_files))
# print(total_files)
return total_files
def load_file_dic... | The main task of the code is to preprocess multiple files (including an input Word file) by loading file data, replacing specific tags in each document based on a list and file dictionary, and saving the modified documents. It iterates through files, handles the last file separately, and repeatedly replaces tags until ... | def preprocess_files(input_wordfile,list_df,i):
files=getallfiles(list_df)
files_dict=load_file_dict(list_df,files)
files.append(input_wordfile)
for i in range(len(files)):
file=files[i]
if i==len(files)-1:
files_dict=load_file_dict(list_df,files)
# ll
find_and_replaceiftags(list_df,file,i)
# ll
do... |
def identify_unique_filepaths_from_all_file_tags(ordered_dataframes): # Confirmed3
"""
Determine a list of unique filepaths, for all FILE tags, for all
iterator values in the FILE worksheet. This function reflects
an optimization to parse Word files at these filepaths once
up front rather than par... | The function processes [[IF...]] and [[FILE...]] tags in a Word document by identifying and resolving filepaths from FILE tags, generating unformatted content strings, replacing IF tags (conditionally) and FILE tags (with content from other files) iteratively, and saving the modified document. It ensures circular refer... | def preprocess_files(input_word_filepath, dataframes,iterator): # CONFIRMED3
"""
Handles [[IF...]] and [[FILE...]] tag processing within
input_word_filepath, so that [[IMAGE...]] and [[TEXT...]]
content can be inserted in the process_files() function.
:param input_word_filepath: (string) filepath f... |
def getallfiles(list_df):
"""
Determine a list of all filepaths, for all FILE tags, for all
iterator values in the FILE worksheet. This function reflects
an optimization to parse Word files at these filepaths once
up front rather than parsing those files potentially many times
:param list_df: (list of strings) (... | The function preprocesses a Word document by resolving conditional [[IF...]] tags and replacing [[FILE...]] tags with content from other Word files. It first collects all required filepaths, loads their content into a dictionary, and ensures no circular dependencies. It then iterates through each file, processes tags, ... | def preprocess_files(input_wordfile,list_df):
"""
Begins by conditionally including or excluding content, based on
resolving GLOBAL values for [[IF...]] tags. Continues by replacing
[[FILE...]] tags with content from corresponding Word files. Returns
a Document instance reflecting such changes
:param input_word... |
def textCheckGenerator ( myRun ):
pth = myRun["Path"]
textName = os.path.join(pth, "bcl2fastqCheck.txt")
"""
slashIndex = [i for i, char in enumerate(pth) if char == "/"]
weirdID = pth[slashIndex[-1]+1:]
myRun["folderName"] = weirdID
"""
weirdID = myRun["folderName"]
nowTime = datetime.now()
date_time =... | The main task of the code is to process a sequencing run by archiving its data, converting BCL files to FASTQ format using bcl2fastq, handling potential errors by rerunning with adjusted parameters, and returning the operation's success status. It includes steps for directory creation, data backup via scp, library-type... | def bcl2fastqRun ( myRun ):
myRun = textCheckGenerator(myRun)
myRun = sampleSheetReader(myRun)
myRun = runInfoReader(myRun)
archiveFolderPath = os.path.join(archivePath, myRun["runInstrument"], myRun["runName"])
try:
os.mkdir(archiveFolderPath)
except OSError as exc:
if exc.errno != errno.EEXI... |
def make_instance_files():
gum_file_list = glob.glob("dep/*.conllu")
inst_df = pd.DataFrame()
pair_df = pd.DataFrame()
#mult_tot = 0
for file in gum_file_list:
file_name = file.split("/")[-1].split(".")[0]
print(file_name)
genre = file_name.split("_")[1]
with open(fil... | The main task of the code is to prepare and partition datasets by generating instance files, splitting training data into "train.csv", combining development and test data into "dev.csv", and joining processed data. It organizes data for machine learning tasks like training and evaluation. | def main():
make_instance_files()
make_data_partition(gum_train, "train.csv")
make_data_partition(gum_dev+gum_test, "dev.csv")
join_data()
return |
def drawOnWindow():
global win
global pointer
drawBoard()
drawGridLines()
if startSolving == False:
drawSideButs()
else:
x,y = win.get_size()
if x == 600:
win = pg.display.set_mode((540,540))
if pointer != None:
pg.draw.rect(win,(0,200,0),(pointer[... | The main task of the code is to implement an interactive Sudoku-like puzzle game with Pygame. It handles user input for placing/clearing numbers, saves/load game states, and includes an automatic solving feature using a recursive backtracking algorithm. The game loop manages rendering, event handling, and puzzle-solvin... | def main():
global board
global run
global select
global startSolving
global ret
while run:
win.fill((238,238,238))
drawOnWindow()
if startSolving:
if type(ret) == list:
board = ret[:]
if ret == -1:
ret = solve(*... |
def noOfBusyServer():
busy=0
for i in range(3):
if s[i]==1:
busy=1+busy
return busy
def getfreeServer():
serverid=-1
for i in range(3):
if s[i]==0:
return i
def setServerBusy(n):
setBusy(n)
def cToken():
currentToken =q.get()
return currentToken
de... | The main task of the code is to manage a queue system by checking server availability, assigning free servers to incoming requests, and handling cases where no servers are free. It iterates through the queue size, determines busy servers, allocates free counters, updates server status, and prints token-counter assignme... | def server():
for i in range( q.qsize()):
b=noOfBusyServer()
# print(b)
#print (s)
print("--------------------------------------")
s1=getfreeServer()
if b==3:
print("No free counter kindly wait")
else:
s1=getfreeServer()
... |
def __read_user_hot():
users={}
gender_dict={'M':1,'F':0}
occupation_dict = __read_occupation_hot()
with open(user_path,'r') as f:
for line in f.readlines():
d=line.strip().split('|')
a=np.array([int(d[1]), gender_dict[d[2]]])
users[int(d[0])]=np.append(a,occu... | The main task of the code is to read user and item data, then split them into training and test datasets (trainX, trainY, testX, testY) using the `read_dataSet` function, preparing data for model training and evaluation. | def read_data():
user_dict = __read_user_hot()
item_dict=__read_item_hot()
trainX,trainY=read_dataSet(user_dict,item_dict,train_path)
testX,testY=read_dataSet(user_dict,item_dict,test_path)
return trainX,trainY,testX,testY |
def _init_each_stage(self):
for c in self.clusters:
self.clusters[c].checks = {i: False for i in self.clusters[c].users}
self.clusters[c].checked = False
def recommend(self, i, items, t):
cluster = self.clusters[self.cluster_inds[i]]
# print(cluster.users)
bonus =... | The code executes a multi-stage clustering process with iterative refinement. It initializes each stage, generates user-item interactions, recommends items using a tau-based strategy, collects feedback, stores interaction data, splits clusters, and merges them. The process iterates over increasing stages and time steps... | def run(self, envir):
for s in range(self.num_stages):
self._init_each_stage()
for t in range(2 ** s):
if t % 5000 == 0:
print(t // 5000, end=' ')
tau = 2 ** s + t - 1
I = envir.generate_users()
for i i... |
def list_anime(data: dict):
table = cTable()
table.add_column(cColumn(header='id', width=TABLE_WIDTH_ID, justify=ConsoleTable.JUSTIFY_RIGHT))
table.add_column(cColumn(header='Name', width=TABLE_WIDTH_NAME))
table.add_column(cColumn(header='D/R', width=TABLE_WIDTH_DR))
table.add_column(cColumn(header... | The code processes command-line arguments to perform actions on an anime database, such as listing anime, viewing details, searching MyAnimeList.net, adding/removing/updating entries, syncing data, cleaning finished anime, and setting options. It uses a JSON file for storage, validates inputs, and handles errors for in... | def execute(options: optparse.OptionParser):
(options, args) = parser.parse_args()
# Set verbose logging state.
global verbose
verbose = options.verbose
if verbose:
print(f'Verbose logging enabled.')
# Default to listing if no arguments provided.
if len(args) == 0 or args[0].lo... |
def create_choice(num, string):
return f"\t\t{str(num)}. {string}"
def create_recipe(conn, cursor):
# Ask for name of recipe
name = str(input("\nName of the recipe: "))
# Ask for cooking time of recipe
cooking_time = int(input("\nCooking time (minutes): "))
# Ask for ingredients of recipe
ingredients = ... | The main task of the code is to present a menu-driven interface for managing recipes via a database. It loops until the user types 'quit', offering options to create, search, update, delete, or view recipes. Each choice triggers corresponding functions, using the provided database connection and cursor to execute opera... | def main_menu(conn, cursor):
choice = ""
while (choice != 'quit'):
print("Main Menu" + '\n' + 20*'=')
print("Pick a choice:")
print(create_choice(1, 'Create a new recipe'))
print(create_choice(2, 'Search for a recipe by ingredient'))
print(create_choice(3, 'Update an existing recipe'))
print... |
def load_doc_id(self):
# loads in document id mapping
with open("doc_id.pickle", "rb") as myFile:
self.doc_id = pickle.load(myFile)
def load_index(self):
#loads in inverted index
with open("merged_index_final.pickle", "rb") as myFile:
self.inverted_index = pickle.... | The code's main task is to determine the user's preferred search tool (console or GUI) by prompting input, validate the choice, and execute the corresponding method (`run_text` for console or `run_tkinter` for GUI) after loading necessary data (document IDs and index). It ensures valid input through a loop and handles ... | def run(self):
# figures out which search tool to use
self.load_doc_id()
self.load_index()
which_one = input('0 - use console\n'
'1 - use local GUI\n'
'Pick one of these numbers to proceed:')
print()
while which_one not ... |
def create_index(self):
#opens up the directory with all the pages
target_pages = os.getcwd()
target_pages += '\\DEV'
#gets all the pages and attaches it with correct path names
for root, dirs, files in os.walk(target_pages):
for file in files:
file =... | The code's main task is to build an inverted index by creating and merging partial indexes. It computes scores, saves partial indexes using pickle, merges them into a final index, saves document IDs, and generates a report. The process involves iterative creation, storage, and consolidation of index data for efficient ... | def run(self):
self.create_index()
self.compute_score()
file_name = "inverted_index" + str(self.currentPartial)+ ".pickle"
self.partial_files.append(file_name)
self.pickle_index(file_name) #remember to add last pickle_index with file name of last partial index
self.merge_... |
def ingresarSucursal(self):
nombreSu = ""
nombreSu = input("Digite la ubicacion de la sucursal\n")
sucursal = Sucursal(nombreSu, self.cont)
ciclo = ''
ciclo2 = ''
ciclo3 = ''
ciclo = input("cuantas secciones desea agregar: ")
i = 0
if not ciclo.is... | This code presents an administrative menu loop allowing users to add/view/delete branches and add hardware store items, calling corresponding methods based on input until "salir" is entered. | def menuAdministrativo(self):
opc = ""
while opc != "salir":
print('\n\n1 - Agregar una sucursal')
print('2 - Ver las sucursales')
print('3 - Eliminar')
print('4 - Agregar elementos en ferreteria')
print('Para salir digite "salir"')
... |
def get_newscast_dict(newscast_file):
time_header = 'AM Newscasts'
df = pd.read_excel(newscast_file, 'Page 3', header=1, dtype={time_header: str})
header_list = [
date_to_string(header) if not header == time_header else header
for header in df.columns.to_list()
]
df[time_head... | The function creates a dictionary mapping time intervals to cut IDs by processing news and newscast files. It generates sub-dictionaries for newscasts ('NC') and two shows ('ME', 'ATC'), merges them, and returns a sorted combined dictionary for structured data analysis or output. | def get_time_to_cutid_converter(input_file_news, input_file_newscasts):
out_dict = {}
out_dict['NC'] = get_newscast_dict(input_file_newscasts)
for show in ['ME', 'ATC']:
out_dict[show] = get_show_dict(show, input_file_news)
# merge all three sub-dictionaries in out_dict
dict_for_dataframe... |
def populate_file_share():
"""
Populate File Share
Generates a new file share if one doesn't exist and sets all the files
into place.
"""
file_share = file_service.FileService(account_name=STORAGE_ACCOUNT_NAME,
account_key=STORAGE_ACCOUNT_KEY... | The code's main task is to configure and execute batch processing jobs using a batch client. It creates processing and commit pools, initializes jobs, generates tasks from input datasets/parameters, and adds them to the processing job. Error handling is included for batch operations. | def run(datasets, production, flags):
populate_file_share()
batch_client = get_batch_client()
try:
create_processing_pool(batch_client, generate_pool_start_task())
create_commit_pool(batch_client)
create_job(batch_client, PROCESSING_JOB_ID, PROCESSING_POOL_ID)
create_job(ba... |
def generate_real_samples(dataset, n_samples):
# choose random instances
ix = randint(0, dataset.shape[0], n_samples)
# retrieve selected images
X = dataset[ix]
# generate 'real' class labels (1)
y = ones((n_samples, 1))
return X, y
def generate_fake_samples(g_model, latent_dim, n_samples):
# generate points in... | This function trains a GAN by alternatingly updating the discriminator and generator. It iterates over epochs and batches, generating real/fake samples, training the discriminator on combined data, and training the generator via the GAN model. Losses are printed, and performance is summarized every 10 epochs. | def train(g_model, d_model, gan_model, dataset, latent_dim, n_epochs=2000, n_batch=64):
bat_per_epo = int(dataset.shape[0] / n_batch)
half_batch = int(n_batch / 2)
for i in range(n_epochs):
for j in range(bat_per_epo):
X_real, y_real = generate_real_samples(dataset, half_batch)
X_fake, y_fake = ge... |
def jpeg_encoder(
img_path: str,
block_size: int,
num_coefficients: int,
color: bool,
) -> (
list[np.ndarray[np.int32]]
| tuple[
list[np.ndarray[np.int32]],
list[np.ndarray[np.int32]],
list[np.ndarray[np.int32]],
]
):
"""
Encodes an image using JPEG compressio... | The function `analyze_image` compresses an input image using JPEG encoding/decoding, compares the original and compressed images via PSNR and compression ratio, and returns these metrics alongside the images and encoded data for quality analysis. It reads the image (color/grayscale), applies JPEG compression with speci... | def analyze_image(
img_path: str, block_size: int, num_coefficients: int, color: bool
) -> tuple[
np.ndarray[np.uint8],
np.ndarray[np.uint8],
float,
float,
list[np.ndarray[np.int32]]
| tuple[
list[np.ndarray[np.int32]],
list[np.ndarray[np.int32]],
list[np.ndarray[np.i... |
def ray_cast_player_npc(self):
if self.game.player.map_pos == self.map_pos:
return True
wall_dist_v, wall_dist_h = 0, 0
player_dist_v, player_dist_h = 0, 0
ox, oy = self.game.player.pos
x_map, y_map = self.game.player.map_pos
ray_angle = self.theta
... | This method handles an entity's AI logic by checking its alive status, performing raycasting to detect targets, triggering attacks or movement based on player proximity, animating actions like damage, idle, walking, or attacking, and playing a death animation if the entity is no longer alive. | def run_logic(self):
if self.alive:
self.ray_cast_value = self.ray_cast_player_npc()
self.check_hit_npc()
if self.damage:
self.animate_damage()
elif self.ray_cast_value:
self.player_search_trigger = True
if self.di... |
def _dataflow(self, locations: LineMapping,
inputs: tuple[Input, ...],
output_var: Variable,
output_val: Optional[Value] = None) -> z3.BoolRef:
"""
Return a simplified `z3.BoolRef` predicate logic expression
that represents the dataflow seman... | This function constructs a simplified Z3 boolean expression representing the functional constraint of synthesized programs by combining dataflow, component, and well-formedness conditions. It applies existential quantifiers to component variables and returns the simplified predicate ensuring program correctness under g... | def _functional(self, locations: LineMapping,
inputs: tuple[Input, ...],
output_var: Variable,
output_val: Optional[Value] = None) -> z3.BoolRef:
"""
Return a simplified `z3.BoolRef` predicate logic expression
that represents the functi... |
def _locations(self, prefix: str, output_var: Variable) -> LineMapping:
"""
Return a dictionary that maps each Z3 variable to either its
corresponding integer-valued location variable or its
predetermined integer value.
Map component inputs and outputs to integer-valued location... | The main task of the code is to generate a simplified Z3 boolean expression representing the distinguishing constraint between two synthesized programs. It combines behavioral and functional constraints using existential quantifiers over location variables for two distinct programs, ensuring their outputs differ while ... | def _distinct(self) -> z3.BoolRef:
"""
Return a simplified `z3.BoolRef` predicate logic expression
that represents the distinguishing constraint of synthesized
programs.
Build an existential predicate expression using calls to the
`_behaves` and `_functional` functions. ... |
def challenge_response(self, targetUser: str) -> None:
response = None
response = input(f"{targetUser} challenged you!\nDo you accept? (y/n): ")
while (response != 'y' and response != 'n'):
response = input("Invalid response\nDo you accept? (y/n): ")
self._socket.send(json.... | This method receives and processes game data from a socket, updating the game state based on actions like 'challenge', 'attack', 'win', or 'game_over'. It handles user interactions, health changes, challenge responses, and UI updates, ensuring proper state transitions and error handling for network or input issues. | def receive(self):
try:
data = self._socket.recv(1024)
if not data:
return
data = json.loads(data.decode())
if (data['action'] == 'challenge'):
self.state = 'challenged'
self.challenge_response(data['username'])
... |
def _check_step(self, step):
if step is not None and not isinstance(step, six.integer_types):
raise TypeError('"step" should be an integer, got {}'
.format(type(step)))
def _ensure_tf_name(self, name):
if not isinstance(name, six.string_types):
raise T... | The main task of the code is to log a scalar value under a specified name and step in TensorFlow. It validates the input value is a number, converts it to a float, ensures the step is valid, generates a TensorFlow-compatible summary name, creates a scalar summary, and logs it for visualization. | def log_value(self, name, value, step=None):
"""Log new value for given name on given step.
Args:
name (str): name of the variable (it will be converted to a valid
tensorflow summary name).
value (float): this is a real number to be logged as a scalar.
... |
def _check_step(self, step):
if step is not None and not isinstance(step, six.integer_types):
raise TypeError('"step" should be an integer, got {}'
.format(type(step)))
def _ensure_tf_name(self, name):
if not isinstance(name, six.string_types):
raise T... | This function logs a histogram using TensorFlow, accepting a name, value (as a list of numbers or bin edges/count tuple), and step. It validates inputs, converts the name to a TensorFlow-compatible format, generates a histogram summary, and logs it for visualization. | def log_histogram(self, name, value, step=None):
"""Log a histogram for given name on given step.
Args:
name (str): name of the variable (it will be converted to a valid
tensorflow summary name).
value (tuple or list): either list of numbers
to be... |
def _check_step(self, step):
if step is not None and not isinstance(step, six.integer_types):
raise TypeError('"step" should be an integer, got {}'
.format(type(step)))
def _ensure_tf_name(self, name):
if not isinstance(name, six.string_types):
raise T... | This function logs images as a TensorFlow summary for visualization, converting the provided name to a valid TensorFlow format, validating inputs, and generating a summary with the specified step. It ensures the images are a list of ndarrays, checks the step's validity, and uses helper methods to create and log the ima... | def log_images(self, name, images, step=None):
"""Log new images for given name on given step.
Args:
name (str): name of the variable (it will be converted to a valid
tensorflow summary name).
images (list): list of images to visualize
step (int): non... |
def match(self, x):
if self.stream[self.cur_lexeme_pos][0] == x:
node = AST(self.stream[self.cur_lexeme_pos][1], self.stream[self.cur_lexeme_pos][0])
self.NodePtr.addNode(node)
self.consume()
else:
a = 1/0
def evalVar(self):
i... | This method parses a variable expression enclosed in parentheses, creates an AST node for the variable, evaluates it, and transitions to parsing an equation. It matches parentheses, constructs a VAR node, navigates the AST, and invokes equation parsing. | def prob(self):
self.match(LexTokens.L_Paren)
var = AST("VAR")
self.NodePtr.addNode(var)
self.NodePtr = var
self.evalVar()
self.NodePtr = self.NodePtr.get_parent()
self.match(LexTokens.R_Paren)
self.equation() |
def getTrucksPerTypeNames(self):
trucksPerTypeNames = []
for i in range(self.numberOfTruckTypes):
for j in range(self.numberOfTrucksPerType[i]):
truckPerTypeName = f"Truck_{str(i + 1)}_{str(j + 1)}"
trucksPerTypeNames.append(truckPerTypeName)
return tr... | This code sets constraints in a linear programming model. It enforces truck capacity limits by ensuring each truck's load does not exceed its capacity, and guarantees product demand is met by requiring the total quantity transported for each product equals its required demand. Constraints are named for identification, ... | def setConstraints(self, x, y):
for truckPerType in self.getTrucksPerTypeNames():
truckTypeName = truckPerType.split("_")[0] + "_" + truckPerType.split("_")[1]
self.prob += (
lpSum(self.getTruckLoad(x, truckPerType)) <= self.getTruckCapacityIfUsed(y, truckTypeName, truckP... |
def handle_pre_game_state(response):
op, *args = struct.unpack(PACKET_STRUCT, response)
if op == OP_REJECT:
exit("You are rejected by the server.")
elif op == OP_WAIT:
print("Waiting to play against the server.")
return STATE_PRE_GAME
elif op == OP_START:
print("Now you a... | The function processes incoming data based on the current game state, transitioning between states by calling appropriate handlers. It manages pre-game setup, receives game state requests, prints responses, prompts user input for moves, and handles move responses, returning the next state accordingly. | def handle_read(recv_buffer, state):
if state == STATE_PRE_GAME:
return handle_pre_game_state(recv_buffer)
elif state == STATE_RECV_GAME_STATE_REQ:
print_game_state_response(recv_buffer)
print("Your turn: ", end='', flush=True)
return STATE_SEND_MOVE
elif state == STATE_REC... |
def handle_new_connection(self, client_soc):
self.soc_to_msg_recv[client_soc] = b''
self.soc_to_msg_send[client_soc] = b''
if len(self.active_players) < self.num_players:
self.client_start(client_soc)
elif len(self.waiting_queue) < self.wait_list_size:
self.client_wait(client_soc)
else:
self.client... | This code starts a server that listens for incoming connections on a specified port. It uses the `select` system call to monitor multiple sockets (active players, waiting queue, rejected players, and the listening socket) for readability and writability. When a new connection is detected, it accepts the client, handles... | def start(self):
print("[debug] Server started!")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listen_soc:
listen_soc.bind(('', self.port))
listen_soc.listen()
while True:
Readable, Writable, _ = select([*self.active_players, *self.waiting_queue, *self.rejected_players, listen_soc],
... |
def is_plugin_changed(directory):
filepath = os.path.join(PLUGIN_DIR_PATH, directory + '/www/' + directory + '.ts');
if os.path.isfile(filepath):
modify_time_1 = os.stat(filepath).st_mtime;
plugin_path = os.path.join(PLUGIN_DIR_PATH, directory)
pluginId = get_pluginId(plugin_path);
... | The main task of the code is to scan plugin directories, check if plugins have changed, reinstall changed plugins, handle errors during the process, and finally restore configuration settings. It iterates through each directory in PLUGIN_DIR_PATH, verifies changes via is_plugin_changed(), triggers reinstallation if nee... | def plugin_update():
dirs = os.listdir(PLUGIN_DIR_PATH)
for dir in dirs:
filepath = os.path.join(PLUGIN_DIR_PATH, dir)
if os.path.isdir(filepath):
try:
is_changed = is_plugin_changed(dir);
if is_changed:
print('reinstall plugin ' + ... |
def get_env_params_values(self):
try:
self.mdc['SYSTEM_NAME'] = os.environ['SYSTEM_NAME']
except:
self.mdc['SYSTEM_NAME'] = ""
try:
self.mdc['HOST_NAME'] = os.environ['HOST_NAME']
except:
self.mdc['HOST_NAME'] = ""
try:
... | The main task of the code is to initialize a logging context (mdc) with environment-derived parameters and optionally set up configuration map monitoring. It populates a dictionary with system identifiers, retrieves environment values, processes a config map file, and registers change notifications if enabled, handling... | def mdclog_format_init(self,configmap_monitor=False):
self.mdc = {"PID":"","SYSTEM_NAME":"","HOST_NAME":"","SERVICE_NAME":"","CONTAINER_NAME":"","POD_NAME":""}
self.get_env_params_values()
try:
self.filename = os.environ['CONFIG_MAP_NAME']
self.dirname = str(self.filenam... |
def alt(left, right):
if isinstance(right, Empty):
left, right = right, left
if isinstance(left, Empty):
return right
if isinstance(right, Epsilon):
left, right = right, left
if isinstance(left, Epsilon):
if nullable(right):
return right
else:
... | This function computes the derivative of a regular expression with respect to a given character, returning a new expression representing strings that match after removing the first character. It handles various expression types (Char, Alt, Seq, Star) by recursively applying derivative rules, using Empty for failure, Ep... | def derivative(char, exp):
if isinstance(exp, Empty):
return Empty()
if isinstance(exp, Epsilon):
return Empty()
if isinstance(exp, Char):
if char == exp.arg:
return Epsilon()
else:
return Empty()
if isinstance(exp, Alt):
return alt(deriv... |
def train_episode(self, epoch_t: int, train_frames: int):
"""Do a single training episode.
Args:
epoch_t (int): The total number of frames seen in this epoch, relevant for early stopping of
the training episode.
train_frames (int): How many frames we ... | The main task of the code is to perform a single training epoch by iterating through episodes, collecting statistics such as rewards, frames, losses, and Q-values, and returning aggregated epoch statistics in a dictionary. It tracks training progress, terminates episodes when necessary, and computes final metrics inclu... | def train_epoch(self) -> Dict:
"""Do a single training epoch.
Returns:
Dict: dictionary containing the statistics of the training epoch.
"""
self.logger.info(f"Starting training epoch at t = {self.t}")
epoch_t = 0
policy_trained_times = 0
target_train... |
def train_epoch(self) -> Dict:
"""Do a single training epoch.
Returns:
Dict: dictionary containing the statistics of the training epoch.
"""
self.logger.info(f"Starting training epoch at t = {self.t}")
epoch_t = 0
policy_trained_times = 0
target_train... | The main task of the code is to execute the training loop for a DQN Agent over a specified number of epochs, handling resumption from previous training, collecting training/validation statistics, performing validation if enabled, saving checkpoints, and logging progress. It ensures the agent trains for the required epo... | def train(self, train_epochs: int) -> True:
"""The main call for the training loop of the DQN Agent.
Args:
train_epochs (int): Represent the number of epochs we want to train for.
Note: if the training is resumed, then the number of training epochs that will be d... |
def match(token):
global lookahead
if lookahead == token:
lookahead = lexan()
else:
error('Syntax error')
def rest1():
if lookahead == "F3":
stmt()
elif lookahead in ["WORD", "RESW", "BYTE", "RESB"]:
data()
def stmt():
global symtable, locctr, lookahead, inst, pas... | This code processes tokens sequentially, handling "ID" by calling rest1() and "F3" by calling stmt(), until encountering "END" to terminate the loop. It uses global variables to track state and parse input according to token types. | def body():
global locctr, lookahead, startLine, idx
while True:
if lookahead == "ID":
match("ID")
rest1()
elif lookahead == "F3":
stmt()
elif lookahead == "END":
break |
def is_empty(self, string: str) -> bool:
""" Check if the string is not empty """
if len(string) == 0:
return True
return False
def contains_illegal_characters(self, string: str, illegal_characters: str) -> bool:
""" Check if there are no forbidden characters in a string dest... | The main task of the code is to validate user input against expected answer types, ensuring it is non-empty, printable, and free of illegal characters. It checks input through three validation stages, returning a success status if valid, or an error message specifying the required response format if invalid, with optio... | def test_input(self, input_answer: str, answer_type: str, is_tui: bool = False) -> Union[str, int, float, bool, list]:
""" The function in charge of ensuring that the user's response corresponds to the programmer's expectations """
if self.is_empty(input_answer) is False and input_answer.isspace() is Fa... |
def jump_to_entry(self, stdscr):
"""
Asks the user for an entry number to jump to, then changes the current entry accordingly.
:param stdscr: The curses window object to be used to display the editor in
:type stdscr: curses.Window
"""
input = self.get_input(stdscr, "Plea... | This function processes user input in a curses-based editor, handling arrow keys for navigation between entries and binding lowercase/uppercase letters to actions like jumping, previewing alternatives, searching, writing files, validation, and displaying help. It updates the editor's state based on key presses, ensurin... | def handle_input(self, stdscr, ch):
"""
Handles input in the editor's main loop, i.e. processes and forwards any entered commands.
:param stdscr: The curses window object to be used to display the editor in
:type stdscr: curses.Window
:param ch: The key which was pressed
... |
def clear_screen(self, stdscr):
"""
Clears the terminal screen.
:param stdscr: The curses window object to be used to display the editor in
:type stdscr: curses.Window
"""
stdscr.clear()
stdscr.move(0, 0)
def render_current_entry(self, stdscr):
"""
... | The code's main task is to run an editor's main loop using curses, displaying the current entry and processing user commands. It initializes color pairs, continuously clears the screen, renders the current entry, waits for input via getch(), and delegates command handling to handle_input() until the loop stops. | def run(self, stdscr):
"""
Runs the editor's main loop by showing the current entry and waiting for the next command.
:param stdscr: The curses window object to be used to display the editor in
:type stdscr: curses.Window
"""
curses.use_default_colors()
curses.in... |
def create_dominos(self):
seen = set()
for i in range(7):
for j in range(7):
if j == 0 and i > 0: continue
if (j, i) in seen: continue
self.white_set.append(Domino(i, j, 'W'))
self.black_set.append(Domino(i, j, 'B'))
... | The main task of the code is to initialize and start a new round of a domino game. It resets player domino sets, creates and shuffles dominos, places initial dominos on the board, and proceeds to play the round while updating the round count. | def start_new_round(self):
self.white_set = []
self.black_set = []
self.create_dominos() # Create the dominos, gives them to each player
self.shuffle_dominos() # Shuffles the dominos
self.add_to_empty_board() # Adds the first 6 dominos (from each player) to the board
... |
def generate_group_options(professors, courses, groups, group_idx, day, hour):
'''Generates the sessions a group can take that day at that hour, taking in
account that professors teaching those sessions are avaliable at that time
and only one session of a course can be scheduled for a group that day'''
... | The code recursively schedules sessions for groups by checking available time slots, attempting each option, and backtracking if no valid schedule is found. It marks sessions, proceeds to the next group, and returns True if all groups are scheduled successfully. If no options work, it unmarks and backtracks, returning ... | def schedule_session(group_idx, day, hour):
'''Tries recursively to schedule a session. Return True if a solution has been found.
Return False to trigger backtracking'''
# print(f'CURRENTLY IN GROUP_IDX={group_idx} W/ {day}/{hour}')
options = generate_group_options(professors, courses, g... |
def setHead(self, node):
if self.head is None:
self.head = node
self.tail = node
else:
self.insertBefore(self.head, node)
def insertBefore(self, node, nodeToInsert):
# If we're dealing with linked list with one node, there's
# nothing to do...
... | This method inserts a node at a specified position in a linked list. If the position is 1, it sets the node as the new head. Otherwise, it traverses the list to the target position, then inserts the node before the current node. If the position exceeds the list length, it sets the node as the new tail. | def insertAtPosition(self, position, nodeToInsert):
if position == 1:
self.setHead(nodeToInsert)
return
node = self.head
currentPosition = 1
while node is not None and currentPosition != position:
node = node.next
currentPosition += 1
... |
def _parse_scopes(self, scope: list[str]) -> str:
"""
parses the list of scopes into a space seperated string of scopes
"""
return " ".join(scope)
def _check_cache(self) -> bool:
"""
checks with the CacheHandler if the credentials associated with the
client info ... | This code initializes a SpotifyAuthCode object with credentials, cache settings, and authentication flow. It sets up client details, cache handling, and checks for valid tokens. If cache validation fails, it prompts user login to obtain new tokens, managing session and token expiration tracking for Spotify API access. | def __init__(
self,
client_id: str,
client_secret: str,
redirect_uri: str,
cache_handler: CacheHandler,
scope: list[str] = ALL_SCOPES,
check_cache: bool = True,
update_cache: bool = True):
"""
constru... |
def make_log_message_f(filename = 'log.log'):
"""Returns a function to be used instead of 'print'
which prints on both the standard output
and to the log file (appends to the end)."""
def log_message_f(*args):
with open(filename,'a') as f:
print(*args, file=f)
print(*args)
... | This function analyzes a pickled dataset by loading it, processing it with optional parameters, and saving results to a specified output file while logging progress. It handles default filename generation, uses a log directory, and passes configuration parameters to the analysis routine. | def analyzePickledDataset(input_filename, output_filename = True, log_filename = True,
extra_obs_to_calculate = extra_obs_default, save_period = 5,
update = False):
if output_filename is True:
_output_filename = input_filename # + ".analyzed"
else: # s... |
def clean(self):
out, err = self.runcmd("rm init 1 rst."+self.ctrl+" mixm."+self.ctrl+" wkp."+self.ctrl+" basp*"
+ " atm."+self.ctrl+" save."+self.ctrl+" init."+self.ctrl+" hssn."+self.ctrl+" -r")
print("rm init 1 rst."+self.ctrl+" mixm."+self.ctrl+" wkp."+self.ctrl+" basp... | The main task of the code is to generate and run a control file for a computational simulation using atomic data. It copies atomic positions, cell, and boundary conditions, cleans previous data, writes input files, executes the `lmfa` command via MPI, and copies output files if successful. The function handles simulati... | def make_ctrl(self, atoms):
self.positions = atoms.get_positions().copy()
self.cell = atoms.get_cell().copy()
self.pbc = atoms.get_pbc().copy()
self.clean()
self.write_infile(atoms)
temp_cmd = self.mpi()+" lmfa ctrl."+self.ctrl
print("running "+temp_cmd+"......")
... |
def clean(self):
out, err = self.runcmd("rm init 1 rst."+self.ctrl+" mixm."+self.ctrl+" wkp."+self.ctrl+" basp*"
+ " atm."+self.ctrl+" save."+self.ctrl+" init."+self.ctrl+" hssn."+self.ctrl+" -r")
print("rm init 1 rst."+self.ctrl+" mixm."+self.ctrl+" wkp."+self.ctrl+" basp... | This code performs a series of computational steps for electronic structure calculations using the LMTO method. It initializes atomic data, runs LMFA and LMF executables with control parameters, checks for convergence by analyzing output files, and extracts forces, potential, and Fermi energy if the calculation converg... | def calculate(self, atoms):
self.positions = atoms.get_positions().copy()
self.cell = atoms.get_cell().copy()
self.pbc = atoms.get_pbc().copy()
self.clean()
self.write_infile(atoms)
temp_cmd = self.mpi()+" lmfa ctrl."+self.ctrl
print("running "+temp_cmd+"......")
... |
def update(self, atoms):
if (not self.converged or
len(self.numbers) != len(atoms) or
(self.numbers != atoms.get_atomic_numbers()).any()):
self.initialize(atoms)
self.calculate(atoms)
if self.converged == False:
raise RuntimeError('... | The code generates and plots electronic band structures using the LMF (Linear Muffin-Tin Orbital) method. It updates atomic data, computes k-points, runs LMF for band calculations, checks for output files, verifies the presence of the `plotquestaal.py` tool, and executes it to create a band structure plot saved as `plo... | def plot_bands(self, atoms, kpts=41):
self.update(atoms)
self.mksyml(kpts)
temp_cmd = self.mpi(self.p)+" lmf -vnit=1 --band~mq~fn=syml "+self.ctrl
print("running "+temp_cmd+"......")
out, err = self.runcmd(temp_cmd)
print("done\n")
import os.path
if os.pa... |
def __migrate_schema(self, file_path: str) -> MySQLTable:
"""
Migrate IDMS schema file to a new MySQL table.
:param file_path: IDMS schema file path.
:return: MySQL table object.
"""
file_contents = open(file_path).read()
# Create MySQL table object
idm... | The code migrates IDMS schemas and data to MySQL tables, generating SQL scripts and COBOL copybooks. It downloads IDMS files from S3, processes schemas into MySQL structures, migrates data if available, handles foreign key sets, and uploads results to S3. The function returns S3 paths for the output SQL file and COBOL ... | def migrate(self) -> dict:
"""
Migrate all IDMS records (tables) to new MySQL tables.
Includes schemas and data.
:return: Output file path in S3.
"""
self.start_job()
# Reinitialize state
self.mysql_out_file = None
self.mysql_tables = list()
... |
def choose_task(url, userId):
sorted_tasks = view_all_tasks(url, userId)
if len(sorted_tasks) > 0:
sorted_task_ids = tuple(task["id"] for task in sorted_tasks)
task_id = None
while True:
task_id = input("Please input a Task ID from above: ")
try:
... | This function allows a user to update specific fields (name, description, completion status) of a task retrieved via a URL and user ID. It constructs a PUT request with user-provided updates, validates input, and sends the modified data to update the task. If successful, it confirms the update and displays the revised ... | def update_task(url, userId):
task = choose_task(url, userId)
if task is not None:
task_url = url + str(task["id"])
update_dict = {"userId": userId, "name": task["name"], "description": task["description"], "completed": task["completed"]}
while True:
upda... |
def fit(self, x: np.ndarray, y: np.ndarray) -> None:
self.x = x
self.y = y
self.num_classes = len(np.unique(self.y))
def predict(self, x: np.ndarray) -> np.ndarray:
n_idxs = self.kneibors(x)
y_nns = self.y[n_idxs]
y_pred = np.array([int(np.round(np.mean(y))) for y in y_nn... | The function optimizes the number of nearest neighbors (nns) in a model by first training on a subset of data (fraction `p`), then evaluating different `nns` values (3–19) on a conjugate dataset. It selects the `nns` value with the best score (closest to 1/num_classes) and re-trains the model on the full dataset for op... | def optimize_nns(self, p: np.ScalarType = 0.8) -> None:
x, y = self.x, self.y
ridxs = np.random.choice(len(x), int(p * len(x)))
# fit only a fraction p of the total data, rest is used to optimize nns
x_slice, y_slice = x[ridxs], y[ridxs]
self.fit(x_slice, y_slice)
# con... |
def get_query_relevances(query_path):
header_list = ["query_id", "column2", "table_id", "relevance"]
df = pd.read_csv(query_path, sep='\t', header=None, names=header_list)
return df
def get_statistics_of_tables(df, table_stats_dir):
'''
Get the statistics of the query relevant tables and update the ... | The main task of the code is to process query-relevant tables by loading and cleaning data, extracting entity tuples from highly relevant tables, and generating output files. It loads known entity embeddings if specified, filters tables based on row/column thresholds, extracts tuples per query, and creates query JSON f... | def main(args):
# If the `embeddings_path` is specified then ensure all selected query tuples map to entities in `known_entity_embeddings`
known_entity_embeddings = None
if args.embeddings_path:
print("Loading the known embeddings file...")
with open(args.embeddings_path) as json_file:
... |
def _check_inputs(self, opened_inputs):
pass
def _check_output(self, da):
# x -> `xt` or `xm` mapping, similar for other dims
dims = dict([(d.replace("t", "").replace("m", ""), d) for d in da.dims])
# check that we've aggregated enough bits and have the expected shape
nx_b, ny_b... | The code processes input data by opening and validating files, then concatenates or merges them based on the class type (ExtractByStrips/ExtractByBlocks). It constructs a xarray DataArray, validates the output, creates the output directory, and saves the result as a NetCDF file. | def run(self):
opened_inputs = dict([(inp, inp.open()) for inp in self.input()["parts"]])
self._check_inputs(opened_inputs)
class_name = self.__class__.__name__
if class_name == "ExtractByStrips":
# when extracting by strips we need to use `xr.concat` instead of
... |
def _cdo_has_command(cmd):
output = _call_cdo([cmd], verbose=False, return_output_on_error=True)
has_op = "Operator >gather< not found!" not in output
return has_op
def output(self):
p = _build_path(
file_prefix=self.file_prefix,
data_stage="strip_variable",
data_... | This method executes CDO commands to process input files, selecting 'gather' or 'collgrid' based on availability and appending a dimension modifier if the dimension is 'x'. It constructs and runs a CDO command with input/output paths, or falls back to xarray processing if CDO is not used. | def run(self):
if self.use_cdo:
if _cdo_has_command("gather"):
cdo_command = "gather"
else:
cdo_command = "collgrid"
# if we're concatenating in the x-direction we need to tell cdo to
# add an extra dimension for y
if s... |
def get_private_key_from_mnemonic(mn) :
private_key = mnemonic.to_private_key(mn)
return private_key
def approval_program():
on_creation = Seq(
[
App.globalPut(Bytes("Creator"), Txn.sender()),
# Assert(Txn.application_args.length() == Int(5)),
# App.globalPut(Byte... | The code creates and manages a voting application on Algorand blockchain. It compiles TEAL programs, initializes app state schemas, and deploys the app with parameters like registration/voting periods and contract addresses. It supports opt-in, voting, proposal submission, and global state reads, handling transactions ... | def main(args) :
# initialize an algodClient
algod_client = algod.AlgodClient(algod_token, algod_add_c1ress, headers=purestake_token)
if args[0] == 'create':
# declare application state storage (immutable)
# initialize an algodClient
creator_private_key = get_private_key_from_mn... |
def thumbprint_public(private_key):
'''
Make thumbpring of public key.
https://tools.ietf.org/html/rfc8555#section-8.1
Returns:
str: thumbprint of public key
'''
# make JWK representation of public key
key = jwk_public(private_key)
# encode to compact JSON
key = compact_json... | This function prepares and initiates an ACME domain validation challenge by collecting authorization parameters, selecting a validation method, and sending a challenge request to the specified URL, returning the challenge details for tracking and verification. | def _setup_authz(self, authz_url):
'''
Setup authorization for given authz_url.
Return challange_sent dict.
'''
authz_status = self.state['authz_statuses'][authz_url]
# collect authorization methods and parameters
authz_params = dict() # {challenge_type: {token:... |
def private_key_from_pem(key_bytes):
'''
Return private key object from `key_bytes` in PEM format.
'''
return serialization.load_pem_private_key(key_bytes, None)
def jwk_public(private_key):
'''
Make JWK representation of public key.
'''
public_numbers = private_key.public_key().public_n... | This function performs an account key rollover by signing the old key with the new private key and sending it to the ACME server's key change endpoint, then updates the object's account key to the new one. | def change_account_key(self, new_account_key):
'''
Account key rollover. Set new account key for this object on success.
Before calling this function ``new_account_key`` should be saved somewhere to avoid losing it on failure.
'''
old_account_key = self._account_key
new_a... |
def _rate_limit_delay(self, identifier):
'''
Calculate delay value from number of attempts and delay execution by calling `self.acme.delay`.
Args:
identifier: name of the data structure in `self.state`
'''
now = time.time()
data = self.state.setdefault(identi... | This function processes ACME authorization for a given URL by checking its status, managing challenges, and handling cleanup. It returns True if authorization succeeds (status 'valid'), False otherwise. It maintains state variables for tracking statuses, sent challenges, and cleanup needs, looping until the authorizati... | def _process_authz(self, authz_url):
'''
Process authorization for given URL.
Return True if authorization is succeeded, False if not.
'''
logger.debug('Processing authorization %s', authz_url)
authz_statuses = self.state.setdefault('authz_statuses', dict())
chall... |
def get_valid_locations(self) -> list:
"""
Get a list of possible valid locations, list is used by the AI
:return: list of integers
"""
valid_locations = []
for col in range(self.col_size):
if self.is_valid_location(col):
valid_locations.append... | This function implements the minimax algorithm with alpha-beta pruning to determine the optimal move for a game AI. It recursively evaluates all possible future moves up to a given depth, maximizing the AI's score while minimizing the opponent's. Terminal states (win/loss/draw) are checked, and alpha-beta pruning optim... | def minimax(self, board, depth, alpha, beta, maximizing_player):
valid_locations = self.get_valid_locations()
is_terminal = self.is_terminal_node()
if depth == 0 or is_terminal:
if is_terminal:
if self.winning_move(self.ai_piece):
return None, 1000... |
def make_move(self, player_value: int, col: int) -> None:
"""
Takes player value and column and calls the generate next row method to allow placing of the value in the
selected column
:param player_value: determined by the player object value( either 1 or 2)
:param col: the colum... | This code handles a player's turn in a game, accepting human input or using AI (via minimax algorithm) to select a move. It updates the game board, checks for a winning condition, and exits if a player wins. It also manages invalid inputs for humans and alternates turns between players. | def turn(self, player) -> None:
"""
Invokes a turn based system to allow either user input or AI input
:param player:
:return:
"""
try:
if player.is_human:
col: int = player.get_move()
self.make_move(col=col, player_value=player... |
def turn(self, player) -> list:
move = ()
if player == "human":
place_x = int(input("place x Axis: "))
place_y = int(input("place y Axis: "))
move = (place_x, place_y)
elif player == "computer":
best_move = self.find_best_move()
move =... | The main task of the code is to execute a single round of a game. It prints the round number, processes each player's turn, updates the game board, evaluates the score, checks for a winner, and increments the round counter. The function orchestrates gameplay for two players, displaying the board state and determining i... | def round(self):
print(f"Round {self.no_rounds}")
players = [self.player1, self.player2]
for player in players:
self.turn(player)
pprint(self.board)
score = self.evaluate()
self.is_winner(score=score)
self.no_rounds += 1 |
def getLength(self):
"""Find length of collection and return int."""
return len(self.values)
def mergeMatch(self, match):
"""Add merged Fragment and remove unmerged Fragments.
Argument:
match (Match) -- contains Fragments to merge
"""
self.__addFragment(match.getMerge())
self.__removeFragment(match... | The method greedily merges the entire collection by iteratively identifying and merging the pair of elements with the longest overlap, reducing the collection size by one in each of (length - 1) rounds until all elements are merged. | def greedyMatchAndMerge(self):
"""Merge entire collection."""
# Greedy match and merge only needs one less round
# than length of collection
for i in range(self.getLength() - 1):
self.mergeMatch(
self.getMatchWithLongestOverlapInCollection()) |
def generate_scenarios(pices: list[int]) -> list[Scenario]:
scenarios: list[Scenario] = []
for i in range(0, len(pices)):
current_pices = []
current_pices.append(pices[i])
append_scenario(current_pices, scenarios)
for j in range(0, len(pices)):
if i == j:
continue
current_pice... | The main task of the code is to optimize cutting required pieces from available supplier lengths by iteratively generating and selecting the best cutting scenarios, removing processed pieces, and combining scenarios to minimize waste. It processes all required pieces, ensures valid removal of used pieces, and finalizes... | def main():
resulting_scenarios: list[Scenario] = []
print(f'Required pices: {required_pices} ({sum(required_pices)} total)')
print(f'Accepted supplier lengths: {accepted_supplier_lengths}')
print(f'Cut width: {cut_width}')
print()
while len(required_pices) > 0:
scenarios = generate_scenarios(required... |
def _train_step(self):
with tf.GradientTape() as tape:
loss = self._custom_loss()
trainable_variables = list(self.weights.values()) + list(self.biases.values())
gradients = tape.gradient(loss, trainable_variables)
self.optimizer.apply_gradients(zip(gradients, trainable_variables))
def _train_step_tf(self):
... | The main task of the code is to train a machine learning model for a specified number of steps (`self.training_steps`), using either a base training method (`_train_step`) or a "TF" mode training method (`_train_step_tf`), depending on the `self.train_mode` setting. Every `self.display_step` iterations, it prints the c... | def train_model(self):
for i in range(self.training_steps):
if self.train_mode == 'BASE':
self._train_step()
elif self.train_mode == 'TF':
self._train_step_tf()
else:
raise ValueError("[ERROR]: Other TRAIN_MODES are not yet considered.")
if i % self.display_step == 0:
print("Loss: %f " % ... |
def check_gyro_tremor(obs_gyrowindows_all): #for each sub
labels=np.zeros(len(obs_gyrowindows_all)) #zeros for initializing
for i in range(len(obs_gyrowindows_all)): #for each row
test_row=obs_gyrowindows_all[i,:]
row_correctmean = test_row - np.mean(test_row)
#Filter as the EMG
low=1.5/(20... | The function identifies the first non-zero label index in processed gyroscope data for a given ID, but only if the bagged label indicates tremor presence (bag_label_tremor=1). It returns this index or NaN otherwise. | def window_dupli_PD(ID):
labels=check_gyro_tremor(sub_windows_gyro(ID))
bag_label_tremor=bag_label(labels)
index=float("nan")
if bag_label_tremor==1:
i=0
while labels[i]==0:
i+=1
index=i
return index |
def get_max_restwindows():
nwindows_rest_all=[]
#itr = iter(range(1,17))
for ID in range(1,17):
#print(ID)
if ID==8:
ID=ID+1
else:
#print(ID)
window_labels=get_window_labels(ID, 1)
nwindows_rest=[]
for j ... | The main task of the code is to construct a 3D data matrix by processing EMG signal windows for 16 subjects (ID 1-16), skipping ID 8, and combining filled windows using different indexing rules for IDs <12 and ≥12. It uses `sub_windows_EMG` to extract windows, `fill_windows` to handle rest windows, and `np.dstack` to c... | def get_data_matrix():
data=[]
max_restwindows= get_max_restwindows()
for ID in range(1,17):
obs_windows_all=[]
print(ID)
if ID==8:
ID=ID+1
else:
if ID >=12:
obs_windows=[]
obs_windows_filled=[]
... |
def log(message, prefix_newline=False):
"""Logging function, provides a hook to suppress or redirect log messages."""
print(('\n' if prefix_newline else '') + '{0:.2f}'.format(time.time()) + ': ' + str(message))
sys.stdout.flush()
def run_checkM(self, subcommand, options, dropOutput=False):
'''
... | The main task of the code is to execute the CheckM lineage workflow for analyzing binned contigs, including input validation, data staging, workflow execution with optional parameters, bin quality filtering, plot generation, result packaging, HTML reporting, and returning a KBaseReport with outputs and filtered contig ... | def run_checkM_lineage_wf(self, params):
'''
Main entry point for running the lineage_wf as a KBase App
'''
# 0) validate basic parameters
if 'input_ref' not in params:
raise ValueError('input_ref field was not set in params for run_checkM_lineage_wf')
if 'wo... |
def from_cvs(self, data, column=None):
if column is None:
raise ValueError('Pass a column index as int')
with open(data) as file:
reader = csv.reader(file)
self.data = np.array([row[column] for row in reader])
def from_txt(self, data, encoding):
with open(data... | This code loads data from a list, CSV, or TXT file, preprocesses it, tokenizes text, builds a vocabulary, computes term frequencies, inverse document frequencies, and finally calculates TF-IDF values for the input data, returning the resulting TF-IDF matrix. | def __call__(self, data, encoding='utf-8', column=None, preprocess=[], symbols=[], keep_raw_in_mem=True):
if isinstance(data, list):
self.data = data
elif data.endswith('csv'):
self.from_cvs(data, column)
elif data.endswith('txt'):
self.from_txt(data, encoding... |
def preprocess(self, options=[], symbols=[]):
use_data = []
if len(options) == 0:
options = self.preprocess_opts
if self.is_query:
if len(self.last_preproc_opts[0]) == 0:
raise ValueError('Cannot use stored options, please provide preprocessing options to ... | The code processes a query by tokenizing it, converting it into a vector weighted by IDF values, normalizing the vector, and computing cosine similarity with documents to retrieve results. The 'get' parameter controls output: 'best_only' returns the top result, an integer returns top-n results, and None returns all res... | def query(self, query, get='best_only'):
"""Paramenters:
- "best_only" - returns highest score, incl. document
- as type int - returns best n scores, incl. documents
- None = - returns all scores, incl. documents
"""
self.query_mode = get
self.is_quer... |
def reset_decoder(self, hmm=None, lm=None, vocab_dict=None):
self._last_utterance = None
hmm = hmm or self.hmm
lm = lm or self.lm
vocab_dict = vocab_dict or self.vocab_dict
LOG.info("resetting decoder")
self.config = Decoder.default_config()
self.config.set_string... | This code implements continuous listening for speech recognition. It starts a stream, processes incoming audio buffers, detects speech activity, and yields recognized utterances once speech ends. The decoder handles audio processing, tracks speech status, and outputs transcribed text when a complete utterance is detect... | def listen(self):
self.reset_decoder()
self.handle_record_begin()
self.stream.start_stream()
self.listening = True
in_speech_bf = False
self.decoder.start_utt()
LOG.info("continuous listening")
while self.listening:
buf = self.stream.read(1024)... |
def reset_decoder(self, hmm=None, lm=None, vocab_dict=None):
self._last_utterance = None
hmm = hmm or self.hmm
lm = lm or self.lm
vocab_dict = vocab_dict or self.vocab_dict
LOG.info("resetting decoder")
self.config = Decoder.default_config()
self.config.set_string... | The main task of the code is to listen for speech input once, process the audio stream using a decoder, detect when speech ends, and yield the recognized utterance. It starts the audio stream, processes incoming data in a loop, checks for speech end, extracts the hypothesis, and stops listening after a valid utterance ... | def _listen_once(self):
self.reset_decoder()
self.handle_record_begin()
self.stream.start_stream()
self.listening = True
in_speech_bf = False
self.decoder.start_utt()
LOG.info("listening once")
while self.listening:
buf = self.stream.read(1024)... |
def reset_decoder(self, hmm=None, lm=None, vocab_dict=None):
self._last_utterance = None
hmm = hmm or self.hmm
lm = lm or self.lm
vocab_dict = vocab_dict or self.vocab_dict
LOG.info("resetting decoder")
self.config = Decoder.default_config()
self.config.set_string... | This function enables continuous speech recognition using a custom vocabulary. It initializes a decoder with a specified or default configuration, processes audio streams, and yields recognized utterances. The function handles dynamic vocabulary creation by generating phonemes for provided words, updates the decoder's ... | def listen_specialized(self, word_list=None, vocab_dict=None, config=None):
self.reset_decoder()
if config is None:
config = self.config
else:
LOG.info("loading custom decoder config")
if word_list:
vocab_dict = vocab_dict or {}
for word in... |
def reset_decoder(self, hmm=None, lm=None, vocab_dict=None):
self._last_utterance = None
hmm = hmm or self.hmm
lm = lm or self.lm
vocab_dict = vocab_dict or self.vocab_dict
LOG.info("resetting decoder")
self.config = Decoder.default_config()
self.config.set_string... | This function initializes and manages a speech recognition decoder to listen for and process audio input once. It configures the decoder with optional custom settings and vocabulary, starts an audio stream, detects speech activity, and yields recognized text when speech ends. The process continues until the stream ends... | def _listen_once_specialized(self, vocab_dict=None, config=None):
self.reset_decoder()
if config is None:
config = self.config
else:
LOG.info("loading custom decoder config")
if vocab_dict is not None:
LOG.info("loading custom dictionary")
... |
def filter_by_list(sample_or_otu, filter_file, metadata, otu_table, meta_out, otu_out, prefilter=False, col1=None,
filter_by=None, col2=None, filter_by2=None, ):
"""
:param sample_or_otu:
:param filter_file:
:param metadata:
:param otu_table:
:param meta_out:
:param otu_out:... | The main task of the code is to parse command-line arguments for filtering an OTU (Operational Taxonomic Unit) table or combined OTU/taxonomy table using metadata criteria or sample/OTU lists. It selects between three filtering methods (`--filt_vars`, `--filt_list`, `--filt_combined`) based on user input, applies the c... | def main():
"""
parse cli arguments and write output to file
:return:
"""
parser = argparse.ArgumentParser(description="DESCRIPTION\n"
"Filter an OTU table or combined OTU table by metadata or filter using"
... |
def debug(self, text):
if self.debug_mode:
print(text)
def _reset(self):
filename = "E:\\Snake\\new\\" + str(self.learningStep) + ".txt"
self.logFile = open(filename, "w+")
self.done = False
self.direction = Direction.east
self.init_snake()
self.random... | The main task of the code is to process a given action in a snake game environment, update the game state by checking collisions, calculate rewards, log observations, and return either a termination or transition based on game status. It handles direction changes, collision detection, state tracking, and reinforcement ... | def _step(self, action):
self.debug("--------------------------------------------")
self.debug("Action: " + str(action))
if(self.done): # if true, it means that snake had a crash in previous step and game needs to be restarted
self.debug("--- RESET ---")
return self._res... |
def reflect(self):
_reflected_board = Board(self.rotator, self.size)
for _edge in self.__get_edges_coordinates():
_reflected_edge = self.rotator.reflect_edge(_edge)
_reflected_board.edges[self.get_board_position(*_reflected_edge)] = self.edges[self.get_board_position(*_edge)]
... | The code generates all unique rotations and reflections of a board. It starts with the original board and its reflection, then iteratively creates three rotated versions by applying rotation transformations to edges, updating a new board each time. Each rotation is followed by its reflection, yielding all possible orie... | def rotations(self):
yield self
yield self.reflect()
_prev_rotated_board = self
for _ in range(3): # just rate
_rotate_board = Board(self.rotator, self.size)
for _actual_edge in self.__get_edges_coordinates():
_rotated_edge = self.rotator.rotat... |
def random_position_out_of_view():
"""Returns a random (x, y) position that is within the active zone, but not in view of the camera"""
# Keeps generating random points until it finds one not in the active zone
inside_camera_view = True
x_pos, y_pos = 0, 0
while inside_camera_view:
x_pos, y_... | This code initializes a star object with attributes like location, size, type, and color. It sets the star's position based on the 'on_screen' flag, using random positions either outside the view or within the active zone if no location is provided. It calculates dimensions, updates coordinates, and registers the star ... | def __init__(self, location=None, size=0, type=DOT, color=color.THECOLORS['white'], on_screen=False):
self.location = location
if self.location is None:
if not on_screen:
self.location = random_position_out_of_view()
else:
self.location = random_po... |
def get_cursor_pos():
xPos, yPos = pygame.mouse.get_pos()
return xPos, yPos
def divide_screen():
screen_size = get_screen_size()
screen_ratio_x = 0.8
screen_ratio_y = (screen_size[1] - 40) / screen_size[1]
main_window_x = int(screen_size[0] * screen_ratio_x)
main_window_y = int(screen_size[... | This function tracks cursor positions within divided screen regions, appending adjusted coordinates to the 'rubber' list based on mouse state and flip flags. It conditionally updates 'rubber' when mouse events occur, and when mouse_state is 0, it deletes a line from 'line_array' and clears 'rubber' after appending fina... | def current_rubber(rubber, mouse_flip, mouse_state, line_array):
x, y = get_cursor_pos()
window_info = divide_screen()
if mouse_state == 1 and mouse_flip == 1 and window_info[0][0] <= x and window_info[0][1] <= y:
rubber.append([x - window_info[0][0], y - window_info[0][1]])
elif mouse_state == ... |
def platform():
if 'ANDROID_ARGUMENT' in environ:
return "android"
elif _sys_platform in ('linux', 'linux2', 'linux3'):
return "linux"
elif _sys_platform in ('win32', 'cygwin'):
return 'win'
def divide_screen():
screen_size = get_screen_size()
screen_ratio_x = 0.8
screen_... | This code initializes a Pygame application for a note-taking interface with multi-page support, handling window resizing, mouse interactions, and UI elements. It manages screen regions for drawing, navigation, and page management, updating the display dynamically based on user input and events. | def main():
if platform() == "win":
import ctypes
ctypes.windll.user32.SetProcessDPIAware()
pg.init()
pg.font.init()
pg.mouse.set_visible(True)
pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP, K_ESCAPE, VIDEORESIZE, MOUSEBUTTONDOWN, MOUSEBUTTONDOWN])
path = os.path.dirname(os.p... |
def platform():
if 'ANDROID_ARGUMENT' in environ:
return "android"
elif _sys_platform in ('linux', 'linux2', 'linux3'):
return "linux"
elif _sys_platform in ('win32', 'cygwin'):
return 'win'
def divide_screen():
screen_size = get_screen_size()
screen_ratio_x = 0.8
screen_... | The main task of the code is to create a multi-page drawing application using Pygame. It initializes a window with resizable features, manages mouse and keyboard input for drawing (line tool) or erasing (rubber tool), handles page navigation (previous/next), and displays the current page number. The application support... | def main():
if platform() == "win":
import ctypes
ctypes.windll.user32.SetProcessDPIAware()
pg.init()
pg.font.init()
pg.mouse.set_visible(True)
pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP, K_ESCAPE, VIDEORESIZE, MOUSEBUTTONDOWN, MOUSEBUTTONDOWN, K_s])
path = os.path.dirname... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.