dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def RANSAC(features):
n_iterations = 1000
error_thresh = 0.02
inliers_thresh = 0
chosen_indices = []
F_matrix = 0
for i in range(0, n_iterations):
indices = []
#select 8 points randomly
n_rows = features.shape[0]
random_indices = np.random.choice(n_rows, size=8)
... | The code performs camera calibration by estimating the fundamental matrix, rotation, and translation between two images using SIFT feature matching and RANSAC. It detects keypoints, matches descriptors, filters inliers, computes the essential matrix with the camera matrix K, and derives the relative rotation and transl... | def Calibration(img1, img2, K):
#apply sift
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
#find match point
bf = cv2.BFMatcher()
matches = bf.match(des1,des2)
matches = sorted(matches, key = lambda x :x.distance)
ch... |
def Calibration(img1, img2, K):
#apply sift
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
#find match point
bf = cv2.BFMatcher()
matches = bf.match(des1,des2)
matches = sorted(matches, key = lambda x :x.distance)
ch... | The main task of the code is to process stereo image pairs (curule, octagon, or pendulum) by calibrating, rectifying, finding correspondences via disparity, and computing depth maps using camera parameters and baseline distances. It allows user selection of image types, applies specific settings for each, and generates... | def main():
#default image
img1 = cv2.imread('data/curule/im0.png')
img2 = cv2.imread('data/curule/im1.png')
K = np.array([[1758.23, 0, 977.42], [0, 1758.23, 552.15], [0, 0 ,1]])
baseline = 88.39
ndisp = 220
image_type = input("Choose input image, curule:1, octagon:2, pendulum:3 ")
if im... |
def get_valid_moves(self) -> List[str]:
"""Return the moves which won't immediately get the snake killed."""
moves = self.get_valid_moves_helper(True)
if not moves or not len(moves):
moves = self.get_valid_moves_helper(False)
return moves
def get_foods_sorted_by_proximity(se... | The main task of the code is to determine the snake's next move by prioritizing food acquisition when the snake is not the longest or is hungry, following the tail if no valid moves exist, and defaulting to the first valid move if all else fails. It uses pathfinding to approach food, checks valid moves, and ensures the... | def get_decision(self) -> str:
"""Get the move which the snake will make this turn."""
valid_moves = self.get_valid_moves()
decision = None
tail = self.me.coordinates[-1]
sorted_foods = self.get_foods_sorted_by_proximity()
# in case the head is right next to the tail, if... |
def _processCommand(self, command):
if command["command"] == "getGlobal":
return self.processGetGlobal(command)
elif command["command"] == "getattr":
return self.processGetAttr(command)
elif command["command"] == "getitem":
return self.processGetItem(command)
... | The main task of the code is to process a given command by invoking the internal `_processCommand` method. If an exception occurs during processing, it returns an error response containing the exception details. Regardless of success or failure, it ensures garbage collection is performed to manage resources. The method... | def processCommand(self, command):
try:
return self._processCommand(command)
except Exception as e:
return {
"status": "error",
"message": "Runner Error",
"exception": self.serializeValue(e),
}
finally:
... |
def greet(self):
self.say(self.getGreetingText())
def sayTime(self):
# get current time
currentTime = datetime.datetime.now()
time = self.findTime(currentTime)
self.say("It is "+ time +'.')
def deploy(self):
assistant = GitAssistant(self)
self.say("Deploying...")
... | The main task of the code is to analyze a query to determine its command type (e.g., "greet," "time," "deploy") and execute the corresponding action, such as returning a greeting, providing the current time, or deploying a system. If the query matches an unrecognized command, it delegates execution to a general query h... | def think(self, query) :
# self.query = query
# ada = Davinci()
# completion = ada.analyze(query)
# if(completion == False):
# return False
# else:
# # completion = self.json_from_s(completion)
# print(completion)
# print(type(compl... |
def get_mask(ts1, ts2, constrained_path_search, sakoe_chiba_radius, itakura_max_slope):
"""
Compute the mask (region constraint)
Parameters
------------
:param ts1: A time series or integer
:param ts2: Another time series or integer
:param constrained_path_search: type constraint (None, sak... | The function computes the Dynamic Time Warping (DTW) distance between two time series (or multiple time series) with customizable constraints (e.g., Sakoe-Chiba, Itakura). It handles univariate/multivariate inputs, irregular time series, parallelization, and visualization. It returns the DTW distance matrix, optionally... | def dtw(ts1, ts2=None, type_dtw="d", constrained_path_search=None, local_dissimilarity=distance.euclidean, MTS=False, get_visualization=False, check_errors=False, regular_flag=0, n_threads=-1, dtw_to_kernel=False, sigma_kernel=1, itakura_max_slope=None, sakoe_chiba_radius=None, term_exec=False):
if check_errors:
... |
def StartApps(experiment: Experiment, throughput: int):
"""Starts the applications for the experiment.
Args:
experiment: The experiment.
throughput: The RocksDB throughput.
Returns:
The application handles.
"""
# True if we set a nice value for RocksDB and (if it exists) the antagonist.
set_ni... | The code executes an experiment by initializing applications with a specified RocksDB throughput, waiting for their completion, and then processing and saving the results to designated output files. | def RunExperiment(experiment: Experiment, outputs: OutputFiles,
throughput: int):
"""Runs the experiment and writes the results to the output files.
Args:
experiment: The experiment.
outputs: The output files.
throughput: The RocksDB throughput to generate in this experiment.
"""
... |
def DisableCStates():
"""Disables deep C-states."""
# Loop through all CPUs
cpu_prefix: str = "/sys/devices/system/cpu/cpu"
cpu: int = 0
while True:
cpu_path: str = f"{cpu_prefix}{str(cpu)}"
if not os.path.exists(cpu_path):
break
# Loop through all states
state_prefix: str = os.path.join... | The main task of the code is to prepare a machine for experiments by disabling C-states and profiling, mounting a tmpfs filesystem backed by hugepages for high-performance I/O, and copying specified binaries to the tmpfs. This setup ensures optimal system configuration for running experiments with minimal overhead and ... | def SetUp(binaries: Paths):
"""Set up the machine for the experiments.
This includes disabling C-states, disabling profiling, mounting a tmpfs
backed by hugepages, and copying the experiment binaries (included as data
dependencies) to the tmpfs mount.
Args:
binaries: The paths to copy the binaries to.
... |
def CheckBinaries(experiment: Experiment) -> bool:
"""Checks that all binaries need for the experiment exist.
If the experiment does not require a binary (e.g., non-Antagonist
experiments do not need the Antagonist binary), that binary is not checked.
Args:
experiment: The experiment.
Returns:
True... | The code executes an experiment by first determining if it's a ghOSt or CFS type, setting up binaries, validating their existence, configuring output directories, opening files, dumping experiment options, running all experiments, and closing files. It ensures proper initialization, error checking, and resource managem... | def Run(experiment: Experiment):
"""Run the experiment.
Args:
experiment: The experiment.
"""
if experiment.ghost:
print("Running ghOSt experiments...")
else:
print("Running CFS experiments...")
SetUp(experiment.binaries)
if not CheckBinaries(experiment):
raise ValueError("One or more of... |
def send_html(self, event):
"""Event: Send html to client"""
data = {
"selector": event["selector"],
"html": event["html"],
}
self.send_json(data)
def add_client_to_room(self, room_name=None, is_group=False):
"""Add customer to a room within Channels and s... | The code handles a client connection by accepting it, authenticating a random unlogged user, updating the session, displaying the username, recording the client in the database, assigning them to the "hi" room, and listing room messages to initialize the user's interaction in the application. | def connect(self):
"""Event when client connects"""
# Accept the connection
self.accept()
# Gets a random user not logged in
user = User.objects.exclude(
id__in=Client.objects.all().values("user")
).order_by("?").first()
# Login
async_to_sync(l... |
def add_client_to_room(self, room_name=None, is_group=False):
"""Add customer to a room within Channels and save the reference in the Room model."""
# Get the user client
client = Client.objects.get(user=self.scope["user"])
# Remove the client from the previous room
self.remove_c... | The code processes incoming JSON data to handle two main actions: "Change group" and "New message". For "Change group", it adds users to group or private rooms, creating new rooms if needed. For "New message", it saves messages and retrieves room messages. The function manages user subscriptions, room creation, and mes... | def receive_json(self, data_received):
"""
Event when data is received
All information will arrive in 2 variables:
"action", with the action to be taken
"data" with the information
"""
# Get the data
data = data_received["data"]
# D... |
def process_discovery_scans():
"""Process the set of discovery scans set up to find CIDRS in use"""
LOGGER.debug("Discovery scans")
dscan_url = RADAR_URL + "discoveryscans/any"
resp = requests.get(dscan_url, headers=RADAR_HEADERS)
if resp.status_code != HTTPStatus.OK:
LOGGER.error(resp.text... | (The main task of the code is to connect to ACT (Automated Compliance Tooling) and publish vulnerability data fetched from the Elements VM API. It redirects output to a file if configured, sets up an ACT data origin if needed, processes network/IP allocation data, gathers host details, and fetches vulnerability informa... | def main():
"""Connect to ACT and publish data fetched from Elements VM API"""
# Use the below setting to save output to a file
if SETTINGS["general"]["outfile"]:
sys.stdout = sys.stderr = open(SETTINGS["general"]["outfile"], "a")
# If needed set up ACT data origin details: this is only neede... |
def _add_solution(self, elements, cube=None):
if cube is None:
cube = self.cube
cube.loc[elements] = 1
elements = {self.keys[i] : [elements[i]] for i in range(len(self.keys))}
#####
elements_bu = elements.copy()
powerset = self._powerset(self.keys)
... | This function recursively explores possible solutions by iterating through indices of a cube structure, using a specified order of keys. It checks for non-negative values in the cube, generates candidate indices, and attempts to solve the cube at each step. If a solution is found (solution == 1), it stores the result; ... | def _recursive_iteration(self, order, cube):
cube_bu = cube.copy()
key = list(order.keys())[0]
order.pop(key)
print(f'new iteration. use key "{key}"')
n = np.count_nonzero(cube[key] >= 0)
if n == 0:
return -1
else:
in... |
def check_cache(genre, page):
# return False
val = scraperwiki.sqlite.get_var(genre+str(page))
print("checking cache: " + str(val))
if val == None or val == 1:
return False
else:
try:
d = datetime.strptime(val, "%c")
return (datetime.now() - d).days < GENRE_CA... | This code scrapes movie/genre data from a web API, handling pagination and caching. It constructs URLs for each genre, retrieves JSON responses, calculates required pages, and processes each page only if not already cached. The function ensures efficient data collection by avoiding redundant scrapes and logging status ... | def scrape_genre(genre):
print("scraping genre ", genre)
suffix = genre + '/json/?sEcho=1&iDisplayStart=0'
r = requests.get(genre_root + suffix, headers=headers)
print(r)
page = json.loads(r.text)
count = page['iTotalRecords']
pages = count // 500
if not count % 500:
pages -= 1
... |
def load_data(filename):
"""
Load gene and trait data from a file into a dictionary.
File assumed to be a CSV containing fields name, mother, father, trait.
mother, father must both be blank, or both be valid names in the CSV.
trait should be 0 or 1 if trait is known, blank otherwise.
"""
da... | The main task of the code is to calculate and update the probabilities of gene counts (0, 1, 2) and trait presence (True/False) for each person in a dataset. It iterates through all possible combinations of individuals with traits and genes, computes joint probabilities using a `joint_probability` function, updates a p... | def main():
# Check for proper usage
if len(sys.argv) != 2:
sys.exit("Usage: python heredity.py data.csv")
people = load_data(sys.argv[1])
# Keep track of gene and trait probabilities for each person
probabilities = {
person: {
"gene": {
2: 0,
... |
def init_sell(self):
self.order = None
return self.wait_state
def start_screen(self):
sg.theme('Purple')
layout = [ [sg.Text("Welcome to the coffe vending machine at Metaforum, floor 6")],
[sg.Text("This is our menu today: ")]
]
for k,v in self.catalogue... | This code manages a state machine for selling coffee by transitioning through predefined states (init, wait, confirm, prepare, deliver) until reaching an exit state. It processes each state by calling corresponding methods to handle initialization, user interaction, payment confirmation, order preparation, and delivery... | def sell_coffee(self):
while self.state != self.exit_state:
match self.state:
case self.init_state:
self.state = self.init_sell()
case self.wait_state:
self.state = self.start_screen()
case self.confirm_state:
... |
def logged_in() -> bool:
if g_credentialsDB is None:
checkCreateCredentialsDB()
return g_credentialsDB.isLoggedIn()
def getCurrentUser() -> SecurityOfficer:
if g_credentialsDB is None:
checkCreateCredentialsDB()
if not logged_in(): # I hope this is the debug mode :) should check maybe i... | This function displays a sidebar for logged-in users, showing their profile picture, name, and key metrics like expertise, technical scores, teamwork factors, and risk indicators. It includes a logout button and validates the user's login status before rendering the sidebar content. | def showLoggedUserSidebar():
assert logged_in(), "Not logged in"
user: SecurityOfficer = getCurrentUser()
user_profile_pic_path = getCachedImgPathForUsername(user.username)
st.sidebar.markdown(f"## <span style='color:green'>Hi, {user.name}! Let's work.</span>", unsafe_allow_html=True)
st.sidebar.ima... |
def send_update(self):
self.send_packet(StatusPacket(
self.version,
self.rssi,
bytes(self.connected_bssid),
self.gpio_state,
self.gpio_trigger,
self.gpio_down,
self.led_power,
self.battery_voltage,
self.u... | The code initializes and manages a running loop for a device or service, sending periodic updates, handling scan requests, and simulating random button presses. It starts a receiving thread if enabled, maintains operational status, and gracefully stops on exception, ensuring thread cleanup. | def run(self):
self.running = True
if self._receive:
self._recv_thread = threading.Thread(target=self.listen)
self._recv_thread.start()
self.send_update()
try:
#self.sleep(random.randrange(30))
print("{!s}: Initialized".format(self.mac))... |
def get_max_rows(cat_code):
url = get_link(cat_code)
try:
prox = random_proxy()
head = random_header()
logger.info("Using {} as proxy".format(prox["http"]))
response = requests.get(url=url, headers=head, proxies=prox)
response.raise_for_status() # raise an error if the r... | The code gathers government deal listings by first determining the maximum rows for each category, then retrieving and processing those rows into a GovDeals object. It optionally filters results to Ohio if specified, returning the populated object with collected data. | def gather_listings():
cat_code_dict = copy.deepcopy(GOVDEALS_CODES)
# Get max rows for all categories in a single HTTP request
cat_max_rows = {k: get_max_rows(v) for k, v in cat_code_dict.items()}
obj = GovDeals()
for key, cat_code in cat_code_dict.items():
rows = get_rows(cat_code, cat_ma... |
def add_flow(self, datapath, hard_timeout, priority, match, actions):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
actions)]
mod = parser.OFPFlowMod(dat... | This function processes incoming packets in an OpenFlow switch, handling ARP, IPv4, and IPv6 traffic. It performs MAC address learning, checks network slices for traffic classification, and applies flow rules with specific match fields (e.g., TCP/ICMP ports) to direct packets. If no slice match is found, it floods pack... | def _packet_in_handler(self, ev):
msg = ev.msg
datapath = msg.datapath
dpid = datapath.id
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
in_port = msg.match['in_port']
pkt = packet.Packet(msg.data)
eth = pkt.get_protocols(ethernet.et... |
def parseCommandlineArgs():
global appName, appDescription
global optionRegexPatternAlert, optionRegexPatternCancel
parser = argparse.ArgumentParser(prog = appName, description = appDescription)
parser.add_argument('-v', '--videoid', required=True)
parser.add_argument('-o', '--outfile', default = F... | The code initializes a YouTube chat application by parsing command-line arguments, setting up regex patterns, configuring blink/hotkey handlers, initializing the Pytchat module with a video ID, preparing an output file, registering signal handlers for graceful shutdown, and launching a keyboard thread to manage input e... | def setup():
global youtubeVideoId
#
parseCommandlineArgs()
setupRegex();
#
setupBlink()
setupHotkeys()
setupPytchat(youtubeVideoId, False)
#
setupOutputFile()
#
# attempt to catch kill signals
signal.signal(signal.SIGINT, lambda a, b: abortApplication())
#signal.... |
def myprint(*args, **kwargs):
global appPrintPrefix
print( appPrintPrefix + " ".join(map(str,args)), **kwargs)
def shutdownPytchat():
global chat
if (chat):
chat.terminate()
def blinkDrawAttentionProblem():
global blinkColorNetworkIssue
blinkSetColor(blinkColorNetworkIssue)
clearBlin... | This function continuously fetches and displays YouTube chat messages in a loop, handling reconnections, duplicate detection, logging to files, and trigger processing. It monitors chat status, manages sleep intervals between requests, and gracefully exits on user interruption or disconnection. | def loopDisplayAllChatMessages():
global chat
global defSleepTimeBetweenChatGets, defSleepTimeBetweenChatProcess, defSleepTimeBetweenReconnect
global wantsQuit
global optionReconnect
global ytChatStreamContinuation
global youtubeVideoId
global outFile
global optionUseContinuationOnReconn... |
def myprint(*args, **kwargs):
global appPrintPrefix
print( appPrintPrefix + " ".join(map(str,args)), **kwargs)
def setup():
global youtubeVideoId
#
parseCommandlineArgs()
setupRegex();
#
setupBlink()
setupHotkeys()
setupPytchat(youtubeVideoId, False)
#
setupOutputFile()
... | The main task of the code is to execute a program's lifecycle: print the application name and version, initialize setup, optionally loop to display all chat messages if enabled, perform shutdown procedures, and exit. The function handles application initialization, chat interaction (if active), and termination. | def main():
myprint(appName + " v"+ appVersion)
setup()
# pytchat debug
if (chat):
loopDisplayAllChatMessages()
#myprint("Done. Exiting.")
shutdown()
exit() |
def get_status(self, status):
error = False
if status is None:
error = True
elif status > 204:
error = True
if not error:
self.status_label.config(text='Status: ok', bg='blue')
self.status_frame.config(bg='blue')
else:
... | This method handles post-thread completion tasks based on HTTP request types. It updates UI elements like lists, input fields, and buttons according to the request method (get/post/put/delete), manages data display states, and triggers subsequent operations like reloading data or resetting forms. | def on_thread_finished(self, data):
self.get_status(self.status)
self.status = None
request_method = data[2]
if request_method == 'get':
if self.todos:
self.show_list(self.todos)
self.current_todos = self.todos
self.todos = Non... |
def gibbs_sampling():
global doc_topic_distributions, eta_list, gamma_list, st, ed, total_time
st = 0
ed = 0
total_time = 0
for d in range(0, len(docs_list)):
st = time.time()
for w in range(0, len(docs_list[d])):
new_pdf = recompute_w_topic_distribution(d, w)
# ... | The code performs parameter estimation for a probabilistic model via Gibbs sampling. It iterates `iteration_num` times, updating topic-word and document-topic distributions, recomputing perplexity metrics, and storing them in `per_list`. The model name is printed at each iteration, tracking progress and time. The main ... | def parameter_estimation():
per_list.clear()
print(model_name)
for i in range(0, iteration_num):
gibbs_sampling()
print(model_name + "_Iteration" , i, " time: ", total_time)
recompute_distributions()
compute_doc_topic()
compute_topic_word()
per_list.... |
def create_dictionary(data):
global word_index, index_word
for doc in data:
for w in doc:
if w not in word_index:
word_index[w] = len(word_index)
index_word = dict(zip(word_index.values(), word_index.keys()))
def initialize():
global topic_word, doc_topic, topic_word_... | This function runs an LDA topic model with varying topic numbers (starting from 'start' and increasing by 2 per iteration) for a specified number of iterations. It initializes model parameters, estimates topic-word and document-topic distributions, saves results to a file, and records runtime data. The process uses inp... | def run(t_data, start, end_iter, iterations, save_p, clip, c_len, palpha, pbeta, pgamma):
global topic_num, iteration_num, data_clip, data, docs_num, topic_num, words_num, context_len, alpha, beta, gamma
data=t_data
alpha = palpha
beta = pbeta
gamma = pgamma
context_len = c_len
save_path =... |
def closeModals():
client.find_element_by_xpath(
'//*[@id="SearchBoxContainer"]/div/div/div[2]'
).click()
time.sleep(2)
def openImageSection():
try:
client.find_element_by_xpath(
'//*[@id="property-critical-root"]/div/div[3]/div[2]/div[2]/div[1]/di... | The code initializes a class to capture images from specific webpage sections by defining XPaths and image counts for categories like 'rooms', 'property', etc. It then closes modals, opens the image section, and captures images based on the predefined configurations. | def __init__(self):
self.categories = {
"rooms": {
"xpath": "/html/body/div[26]/div/div/div[1]/div[5]/div[2]",
"imgCount": 7,
},
"property": {
"xpath": "/html/body/div[26]/div/div/div[1]/div[5]/div[3]",
"imgCount... |
def run_setup(args):
if args.setup_action == cli.ACTION_SETUP_CONFIG:
run_config(args)
def configure_runner(args):
"""Initialize runcli according to provided CLI arguments
:param args: CLI arguments
"""
if getattr(args, 'min_config', False):
configuration = {}
else:
conf... | The code defines a function `run_app` that parses command-line arguments, checks the specified action, and either executes a setup process or configures and runs a command based on the parsed arguments. | def run_app(args):
args_parsed = cli.parse_args(args)
if args_parsed.action == ACTION_SETUP:
run_setup(args_parsed)
else:
configure_runner(args_parsed)
run_command(args_parsed) |
def load_data(self, dataset_path):
"""
Args :
dataset_path : The path to the dataset json from the dataset
Returns :
dataset list with the lines from the subtitle files
"""
dataset = []
for subtitle in os.listdir(dataset_path):
subtit... | This code initializes a class to process a dataset by loading data from a specified path, parsing it into input-target pairs, and writing the parsed results to a target path. The main task involves data loading, parsing, and outputting structured data for further use. | def __init__(self, dataset_path, target_path):
"""
Args :
dataset_path : The path to the dataset.
target_path : The path for the parsed dataset.
"""
# Root directory / Target directory
self.dataset_path = dataset_path
self.target_path = target_pat... |
def randomize(self, zeros = False, seed = 1):
#Store seed
np.random.seed(seed)
#Set size of list storing synapses (weights)
self.syn = [0 for i in range(self.nlayers - 1)]
#Set size of list for bias neurons
self.bias = [0 for i in range(self.nlayers - 1)]
#Set ... | This function trains a neural network model using specified optimization methods (e.g., gradient descent, Adam) on input data (x, y) over multiple epochs. It supports batch processing, customizable learning rates, momentum, and adaptive learning techniques. The training process includes forward propagation, error calcu... | def train(self, x, y, step_size = 0.01, epochs = 1000, seed = 1, method = 'gradient_descent', batch_size = None, batch_ratio = 1, momentum = 0.9, discount = 0.9, b1 = 0.9, b2 = 0.999, smoothing = np.exp(-8), notification_frequency = None):
self.randomize(seed = seed)
loc = 0
if batch_size is No... |
def get_parameter_types(self, request):
"""Return the parameter list for this solution."""
parameter_types = []
# import heat template to obtain its parameters
f, url_parts = self._open(self.heat_template, self.basedir)
template = yaml.load(f.read().decode('utf-8'))
para... | This code launches a heat template by preparing parameters, constructing stack fields, and invoking the Heat API to create a stack with specified configurations like timeout, disable rollback, and environment data. | def launch(self, request, params={}):
"""Launch the solution's heat template."""
if not api or not api.heat:
raise RuntimeError('Heat API is not available.')
parameter_types = self.get_parameter_types(request)
mapped_params = dict(
(name, self.map_parameter(param... |
def _load_image(image: Union[Image.Image, os.PathLike, str]) -> Image.Image:
if isinstance(image, (os.PathLike, str)):
if not os.path.exists(image):
raise ValueError("Error loading image. Image path not found.")
image = Image.open(image)
return image
def _process(image: Image.Image, ... | The function converts an image into a Rubik's cube color-mapped Excel spreadsheet by reducing its size, mapping each pixel to the closest Rubik's color, and saving the result as an `.xlsx` file with adjustable spreadsheet parameters. It returns the number of Rubik's cubes required to represent the image. | def to_rubiks(
image: Union[Image.Image, os.PathLike],
path: Union[os.PathLike, str],
lower_image_size_by: int = 10,
**spreadsheet_kwargs,
) -> None:
"""
Saves an image as a `.xlsx` file by mapping its colors to the closest of the standard colors of a rubik's cube, then coloring its cells accord... |
def deal_to_players(self):
"""Deal two cards to each player."""
for player in self.players:
hole = []
for _ in range(2):
card = self.deal_card(player.id)
hole.append(card)
player.hole = sorted(hole, reverse=True)
def deal_flop(self):
... | The main task of the code is to deal cards to all players and community cards to the board in a poker game. It sequentially calls methods to distribute player cards, followed by the flop, turn, and river community cards, completing a full round of dealing. | def deal_full_round(self):
"""Deal to all players, deal all community cards to the board."""
self.deal_to_players()
self.deal_flop()
self.deal_turn()
self.deal_river() |
def sample_architecture(self):
if self.sample_binomial:
self.sampled_nodes = []
self.sample_nodes(self.cluster_root)
return self.sample_idx, self.search_space[str(self.sample_idx)]
# TODO: Implement sampling with maximum probability, not likely
else:... | The main task of the code is to train a neural network with dynamically sampled architectures, evaluate their performance on training/validation/test sets, update sampling probabilities based on results, and track metrics like accuracy and loss. It supports both epoch-based and batch-based architecture updates, visuali... | def train(self):
sample_idx, initial_model_config = self.sample_architecture()
model = BaseModel(self.model_name, initial_model_config, num_classes = self.num_classes, init_weights = self.init_weights,
dropout = self.dropout, batch_norm = self.batch_norm, weights = self.weight... |
def debug(self, value):
if self.is_debug_mode:
print(value)
def create_connection(self, check_same_thread=True):
"""create a database connection to a SQLite database"""
conn = None
try:
conn = sqlite3.connect(self.DB_PATH, check_same_thread=check_same_thread)
... | The code initializes a class by loading environment variables, setting debug mode based on the RUN_ENV, creating directories for images and removed images, configuring a database path, retrieving the SHOW_TAG variable, and establishing a database connection while creating the database if it doesn't exist. | def __init__(self, check_same_thread=True):
dotenv_path = os.path.join(BASE_DIR, ".env")
load_dotenv(dotenv_path)
run_env = os.environ.get("RUN_ENV")
self.is_debug_mode = False
if run_env == "test":
self.is_debug_mode = True
self.IMAGES_PATH = os.path.join(B... |
def get_current_image(self):
if self.count < 0:
self.debug("No images in database.")
return None
elif self.count < self.current_id:
self.debug("Count, id mismatch, getting first image.")
return self.get_image(1)
elif self.current_id < 1:
... | The main task of the code is to remove an image file from a database and move it to a designated directory. It checks if the image exists, deletes its database entry using SQL, updates the image count, logs the action, and moves the file to a "removed" folder. Special handling ensures the current image is replaced if n... | def remove_image(self, image):
if not os.path.exists(image):
print("File does not exist.")
return
cur = self.conn.cursor()
try:
image = os.path.abspath(image)
if not os.path.exists(image):
print("File does not exist in images.")
... |
def check_disabled():
if DISABLE_START_TIME is None or DISABLE_END_TIME is None:
return
dt_now = datetime.datetime.now()
dt_st = datetime.datetime(
dt_now.year,
dt_now.month,
dt_now.day,
DISABLE_START_TIME[0],
DISABLE_START_TIME[1],
)
dt_et = datetime... | The main task of the code is to periodically change images with a delay determined by the `change_after` parameter. It first checks if `change_after` is less than 1.0, exits early if so, then sleeps for 5 seconds. It creates a time delta, enters an infinite loop to check if the system is disabled, waits for reactivatio... | def picture_frame_thread_main(change_after):
print("picture")
print(change_after)
if change_after < 1.0:
return
time.sleep(5)
d = datetime.timedelta(minutes=change_after)
while True:
check_disabled()
if DISABLED:
wait_until_enable()
change_image()... |
def local_search(self):
"""Local search loop, including pattern move."""
# Holds delta f values for each dimension's proposed move (increment and decrement)
self.delta_fs = np.empty(2*self.DIMS)
# Selection of which dimensions to change
if len(self.to_change) == 0:
di... | The main task of the code is to iteratively optimize a solution using local search, updating grids, memories, and archives while monitoring function evaluations. It adjusts search strategies (intensification, diversification, step size reduction) based on triggers, resets counters upon finding better solutions, and ult... | def main_search(self):
"""Main search loop"""
while self.STEP_SIZE > self.CONV_SS and self.f_evals < 15000:
new_sol = self.local_search()
if new_sol:
self.update_grid()
self.update_memories()
self.archive()
self.hi... |
def check_id_exists(video_id):
for filename in os.listdir(output_directory):
if video_id in filename:
return True
return False
def get_video_id(url):
url_data = urllib.parse.urlparse(url)
query = urllib.parse.parse_qs(url_data.query)
return query["v"][0]
def download_video(url):
... | The main task of the code is to process a given URL by checking if a song already exists for it. If not, it downloads the video, converts supported video files to MP3, moves the MP3 to an output folder, and cleans up temporary files. It skips conversion if a song file exists, logs progress, and manages file operations ... | def handle_url(url):
print("\nAttempting process on url: " + url)
if (check_id_exists(get_video_id(url))):
print("\tSkipping mp3 conversion of " + url + " since a song file already exists for it in the output folder.")
skipped_conversions.append(url)
return
download_video(url)
fo... |
def load_data(queryset):
documents = load_data_from_queryset(queryset)
return documents
def data_split(data):
text_splitter = RecursiveCharacterTextSplitter(chunk_size = 500, chunk_overlap = 0)
all_splits = text_splitter.split_documents(data)
return all_splits
def store_splits(queryset):
data =... | The code defines a function `crate_llm` that processes a queryset by loading data, splitting it, storing the splits in a vector store, generating a RAG prompt, and creating an LLM model integrated with the vector store for retrieval-augmented generation. The main task is to build a language model enhanced with vector-b... | def crate_llm(queryset):
data = load_data(queryset)
split = data_split(data)
vectorstore = store_splits(split)
prompt = get_rag_promt()
model = get_llm(vectorstore, prompt)
return model |
def shapley_permsampling_from_data(X_feature, y_feature, n_data, v0=0.1):
n_sample = len(y_feature)
n_perm = int( n_sample // n_data )
if n_sample%n_data > 0:
print('WARNING: n_sample cannot be divided by n_data')
sv_vector = np.zeros(n_data)
for i in range(n_perm):
for j in range(0, n_data):
... | The function `compute_value` calculates a specific value (`sv`) based on the input `value_type` by selecting corresponding algorithms (e.g., Shapley, BetaShapley, Banzhaf, LOO, etc.) and passing parameters from `args`. It returns the computed value after applying the chosen method, which varies depending on the `value_... | def compute_value(value_type, args):
if value_type == 'Shapley_Perm':
sv = shapley_permsampling_from_data(args['X_feature'], args['y_feature'], args['n_data'], v0=args['sv_baseline'])
elif value_type == 'BetaShapley':
sv = betasv_permsampling_from_data(args['X_feature'], args['y_feature'], args['n_data'], a... |
def create_puzzle_range():
"""Helper to add a bunch of small puzzles to the database, some published and some not."""
for i in range(-2, 3):
puzzle = create_small_puzzle()
puzzle.pub_date = timezone.now() + timedelta(days=i)
puzzle.save()
def log_in_super_user(self):
"""Helper fu... | The main task of the code is to verify that a logged-in superuser can view a puzzle preview, specifically checking that the preview for puzzle #3 contains correct HTML elements (like grid, data-number, and title), excludes hidden elements (like "letter" class), and confirms access permissions for a superuser. | def test_preview_future_puzzle(self):
"""Check that previews are visible to a logged in superuser."""
create_puzzle_range()
self.log_in_super_user()
response = self.client.get(reverse('puzzle', args=['super', 3]))
self.assertContains(response, 'class="puzzle"')
self.asser... |
def create_puzzle_range():
"""Helper to add a bunch of small puzzles to the database, some published and some not."""
for i in range(-2, 3):
puzzle = create_small_puzzle()
puzzle.pub_date = timezone.now() + timedelta(days=i)
puzzle.save()
def log_in_super_user(self):
"""Helper fu... | This test verifies that the solution preview page for puzzle #3 renders correctly when accessed by a super user, checking for specific HTML elements, structure, and content such as the puzzle grid, letter elements, and page title. | def test_preview_solution_available(self):
"""Check that solutions are rendered into the preview solution page."""
create_puzzle_range()
self.log_in_super_user()
response = self.client.get(reverse('solution', args=['super', 3]))
self.assertContains(response, 'class="puzzle"')
... |
def create_puzzle_range():
"""Helper to add a bunch of small puzzles to the database, some published and some not."""
for i in range(-2, 3):
puzzle = create_small_puzzle()
puzzle.pub_date = timezone.now() + timedelta(days=i)
puzzle.save()
def get_superuser():
"""Helper to get the sup... | This test verifies that POST requests can successfully overwrite existing puzzle data. It creates a puzzle, sends updated JSON data via POST, and checks if the database reflects the new entries, including clues, answers, and solution grid, confirming the update functionality works correctly. | def test_update_existing_puzzle(self):
"""Check that POSTed data can overwrite existing puzzle data."""
ipuz = '{' \
'"version":"http://ipuz.org/v2","kind":["http://ipuz.org/crossword#1"],' \
'"dimensions":{"width":3,"height":3},"showenumerations":true,' \
'"... |
def execute(executable, args):
"""
Run container command with execve(2). Use manually execve
to run the process as same pid and avoid to fork a child.
"""
executable_path = shutil.which(executable)
if executable_path is None:
print(f"{sys.argv[0]}: {executable} not found.", file=sys.std... | The main task of the code is to handle command-line execution for a Dogecoin-related application. It determines the executable based on input arguments, checks if it's allowed, creates a data directory if needed, processes environment-specific parameters, and runs the specified command with arguments, prioritizing "dog... | def main():
"""
Main routine
"""
if sys.argv[1].startswith("-"):
executable = "dogecoind"
else:
executable = sys.argv.pop(1)
#Container running arbitrary commands unrelated to dogecoin
if executable not in CLI_EXECUTABLES:
return execute(executable, sys.argv[1:])
... |
def yes(prompt):
guess = input(prompt)
yes_options = ['yes', 'y', 'yup', 'sure', 'true']
if (guess.lower() in yes_options):
return True
return False
def loadTree(treeFile):
line = treeFile.readline()
if line == '':
return None
elif line == 'Leaf\n':
root = treeFile.re... | The main task of the code is to implement a 20 Questions game interface, allowing users to load/save game states, play multiple rounds by interacting with a decision tree, and manage game progression. It starts by welcoming players, checks for saved games, plays the game loop, and offers post-game saving. The code hand... | def main():
"""
Main funtion, Play 20 questions interface.
Parameters:
None
Returns:
None
"""
# Write the "main" function for 20 Questions here. Although
# main() is traditionally placed at the top of a file, it is the
# last function you will write.
... |
def get_stats_data_files(root=resources.STATS_ROOT):
files = get_all_stats_paths_relative()
for key in files:
files[key] = xr.open_dataset(root + files[key])
return files
def reformat(data_this):
# Get rid of the singleton
data_this = data_this.squeeze()
data_new = {}
for variable in... | The main task of the code is to process climate data files by reformatting them, calculating differences between RCP4.5 and RCP8.5 scenarios, and saving the results as NetCDF files. It reads input files, applies transformations, generates paired difference outputs for specific scenarios, and writes the final data to a ... | def main():
# """
# Read files
files = get_stats_data_files()
# Reformat
for key in files:
files[key] = reformat(files[key])
# Calculate differences
for key in files:
output = files[key]
if key[1] == "2080-2099":
other_key = (key[0], key[1], "RCP4.5" if ... |
def checkCellQuantity(self):
n = 0
for row in range(0, 4):
for column in range(0, 4):
if self.board[row][column] != None:
n += 1
return n
def resetLastMove(self):
self.lastMove = None
return True
def compressUp(self):
emptyB... | This method handles the "Up" movement in a grid-based game (like 2048). It checks if the move is valid by verifying the last move direction and cell quantity. If valid, it compresses the grid upward, merges adjacent equal cells (doubling their value and updating the score), recompresses, generates a new random piece, u... | def moveUp(self, move):
if self.lastMove == "Up" or self.lastMove == "W" or self.lastMove == "w":
quantity = self.checkCellQuantity()
if quantity == 1:
self.resetLastMove()
return False
self.compressUp()
#Merge cells:
f... |
def checkCellQuantity(self):
n = 0
for row in range(0, 4):
for column in range(0, 4):
if self.board[row][column] != None:
n += 1
return n
def resetLastMove(self):
self.lastMove = None
return True
def compressLeft(self):
empt... | This function handles a "Left" move in a tile-merging game. It checks if the move is valid by verifying if the last move was already "Left" or if only one cell exists (preventing redundant moves). If invalid, it resets the last move and returns False. Otherwise, it compresses tiles left, merges adjacent equal tiles (do... | def moveLeft(self, move):
if self.lastMove == "Left" or self.lastMove == "A" or self.lastMove == "a":
quantity = self.checkCellQuantity()
if quantity == 1:
self.resetLastMove()
return False
self.compressLeft()
#Merge cells:
... |
def checkCellQuantity(self):
n = 0
for row in range(0, 4):
for column in range(0, 4):
if self.board[row][column] != None:
n += 1
return n
def resetLastMove(self):
self.lastMove = None
return True
def compressDown(self):
empt... | The code handles a "Down" move in a grid-based game (like 2048). It checks if the move is valid by verifying if the last move was "Down" or "S" and if there's only one cell, then compresses the board downward. It merges adjacent cells in columns, doubling their values and updating the score. After compression and mergi... | def moveDown(self, move):
if self.lastMove == "Down" or self.lastMove == "S" or self.lastMove == "s":
quantity = self.checkCellQuantity()
if quantity == 1:
self.resetLastMove()
return False
self.compressDown()
#Merge cells:
for row... |
def checkCellQuantity(self):
n = 0
for row in range(0, 4):
for column in range(0, 4):
if self.board[row][column] != None:
n += 1
return n
def resetLastMove(self):
self.lastMove = None
return True
def compressRight(self):
em... | This code handles a "Right" move in a tile-merging game (like 2048). It checks if a move is valid, compresses tiles to the right, merges adjacent equal tiles (doubling their value and updating the score), recompresses, generates a new tile, updates the last move, and returns whether the move was successful. | def moveRight(self, move):
if self.lastMove == "Right" or self.lastMove == "D" or self.lastMove == "d":
quantity = self.checkCellQuantity()
if quantity == 1:
self.resetLastMove()
return False
self.compressRight()
#Merge cells:
... |
def read_log():
with open(log_file_name, 'r') as f:
infos = [line.strip() for line in f]
return infos[0], infos[1], infos[2]
def get_next_player(country_id, city_id, player_id):
with open(players_txt_path, 'r') as f:
players = [line.strip() for line in f]
index = players.index(player_id)
if index + 1 == len(pl... | The main task of the code is to generate a random number of player detections, collect their data into a list, append the data to a CSV file, and update the log with the next starting point for future sessions. It reads initial parameters, iterates through player data, writes detections to a CSV file, and saves the cur... | def routine():
detect_nb = random.randint(detect_nb_min, detect_nb_max)
# Create csv file with header
# csv_file = open('csv/player_detect_log.csv', 'w') DEBUG
csv_file = open(players_csv_path, 'a')
# csv_file.write('country_id,city_id,id,age,name,position,instruction,note\n')
# Create list to contain the playe... |
def waitWhileCastButtleBtnHidden():
start = time.time()
end = start
grabBox = (1100, 680, 1340, 760)
image = MakeScreenShot(grabBox = grabBox)
while not IsCastButtleBtnAppeared(image):
image = MakeScreenShot(grabBox = grabBox)
end = time.time()
print("detecting cast buttle takes time... | This code automates a fishing process in a game/app, handling two modes (Coast/Buttle). It initiates fishing, performs button clicks, waits for conditions, and loops until a fish is caught, then claims it. Key steps: mode-specific actions, timed waits, button interactions, and a loop checking for fish catch status. | def hunt_fish(mode):
start = time.time()
end = start
if(mode == Modes.Coast):
print("coast mode")
if(mode == Modes.Buttle):
print("buttle mode")
waitWhileCastButtleBtnHidden()
time.sleep(10)
start_fishing(mode)
print("start fishing: have been clicked bottom star... |
def raise_term(self, term: int, state_reset: State = None,
timeout_reset: bool = False, leaderId=None, set_event: bool = True):
# state control: case of FOLLOWER -> FOLLOWER
if state_reset is None:
prev_state = None
else:
prev_state = self.state
... | This function handles the candidate state in a distributed consensus algorithm. It requests votes from other nodes, updates the node's state if rejected, increments vote counts for successful responses, and checks if the candidate has won the election. | def candidate_state(self):
if self.state == State.CANDIDATE:
for key in self.list_of_stubs.keys():
if self.state == State.CANDIDATE:
try:
response = self.list_of_stubs[key][0].RequestVote(
pb2.VoteRequest(term=se... |
def _add_placeholders(self):
self.input_features = tf.placeholder(tf.float32, shape = [None, self.num_nodes,self.feat_dim], name = "input_features")
self.input_adj = tf.placeholder(tf.float32, shape = [None,self.num_nodes, self.num_nodes], name = "input_adj")
self.input_features1 = tf.placeholde... | This function implements a hierarchical graph neural network architecture for learning node embeddings. It applies GCN layers followed by multiple pooling steps to progressively reduce graph size, combining features across layers. The final bilinear layer generates output representations, with loss computed using poole... | def hierarchical_repr_arch(self):
##############COMPLETE ARCHITECHTURE OF THE PAPER################
self._add_placeholders()
with tf.variable_scope("node12_gnn",reuse=False):
A=self.input_adj
x=self.input_features
in_feat=x.get_shape().as... |
def check_if_exists(self):
"""Checks if file exists under given self.filepath variable"""
file_status = os.path.exists(self.filepath)
if file_status is False:
raise Exception(FileNotFoundError)
else:
return True
def recognize_extension(self):
"""Recognizes... | The main task of the code is to execute a sequence of operations in order: checking if an object exists, recognizing its file extension, inserting data into a database, and closing the database connection. This method ensures proper workflow execution and resource cleanup. | def run_all(self):
"""Runs all methods in correct order"""
self.check_if_exists()
self.recognize_extension()
self.insert_to_db()
self.cnx.close() |
def check_if_exists(self):
"""Checks if file exists under given self.filepath variable"""
file_status = os.path.exists(self.filepath)
if file_status is False:
raise Exception(FileNotFoundError)
else:
return True
def recognize_extension(self):
"""Recognizes... | The code's main task is to process and store quiz data by sequentially checking existence, recognizing file formats, validating data, generating a new quiz, inserting it into a database, and closing the database connection. It ensures proper data handling and storage in a structured workflow. | def run_all(self):
"""Runs all methods in correct order"""
self.check_if_exists()
self.recognize_extension()
self.check_data_for_tex()
self.create_new_quiz()
self.insert_to_db()
self.cnx.close() |
def update_dropdown_menu():
menu = file_type_menu["menu"]
menu.delete(0, "end")
for data_key in data_dict.keys():
menu.add_command(label=data_key, command=tk._setit(selected_data_var, data_key))
def display_selected_data(*args):
selected_data = selected_data_var.get()
if selected_data in da... | The code creates a GUI interface for Tab 4, enabling CSV uploads, data selection via dropdown, and visualization of results like "Top 25 Finishers" and "Team Scores" using buttons and a treeview display. It initializes UI components, links actions to functions, and prepares dynamic data handling through global variable... | def create_tab4_content(tab4):
# Create a frame for the content of Tab 4
tab4_frame = ttk.Frame(tab4)
tab4_frame.pack(expand=True, fill="both")
# Upload CSV Button
upload_button = tk.Button(tab4_frame, text="Upload CSV", command=upload_csv)
upload_button.pack(pady=10)
# Initialize selected... |
def calc_sub_total(self):
self.child_total = self.child_count * self.settings.child_price
self.adult_total = self.adult_count * self.settings.adult_price
return self.child_total + self.adult_total
def calc_tax(self):
return self.calc_sub_total() * self.settings.tax_rate
def get_gratuity(... | The code calculates the grand total by summing the subtotal, tax, and gratuity. It returns the combined value of `self.calc_sub_total()` (item costs), `self.calc_tax()` (applied taxes), and `self.get_gratuity()` (tips/service charges), representing the final total amount due. | def calc_grand_total(self):
return self.calc_sub_total() + self.calc_tax() + self.get_gratuity() |
def should_charge_auto_gratuity(self):
return (
self.adult_count + self.child_count
) >= self.settings.auto_gratuity_limit
def calc_sub_total(self):
self.child_total = self.child_count * self.settings.child_price
self.adult_total = self.adult_count * self.settings.adult_price... | The main task of the code is to generate and print a detailed ticket receipt, displaying payment status (paid/unpaid), transaction amounts, gratuity requirements, and a breakdown of subtotal, tax, gratuity, and total costs. It formats this information for display, including change due if paid, and uses specific print f... | def print_ticket(self):
if self.paid:
print_top(f"Ticket Detail: {self.id} :: Paid in Full :: Change Due: ${self.change_due:.2f} / Payment Amount: ${self.payment_amount:.2f}")
else:
print_top(f"Ticket Detail: {self.id} :: Unpaid")
print(f"Child Count: {self.child_count}"... |
def calc_grand_total(self):
return self.calc_sub_total() + self.calc_tax() + self.get_gratuity()
def calc_total_with_tax(self):
return self.calc_sub_total() + self.calc_tax()
def calc_sub_total(self):
self.child_total = self.child_count * self.settings.child_price
self.adult_total = self... | This function prompts the user to select a gratuity method (total ticket, percentage, or exact amount), calculates the corresponding gratuity value based on the input, and stores it in `self.gratuity_override`. It validates inputs, handles errors, and loops until a valid option is chosen. | def add_gratuity(self):
while True:
type_of_grat = input(
"Would you like to use Total Ticket (T), Percentage (P), or Exact Amount(E): "
)
if type_of_grat in {"t", "T"}:
amount = float(
input(
f"Enter... |
def calc_grand_total(self):
return self.calc_sub_total() + self.calc_tax() + self.get_gratuity()
def should_charge_auto_gratuity(self):
return (
self.adult_count + self.child_count
) >= self.settings.auto_gratuity_limit
def add_gratuity(self):
while True:
type_of_... | The main task of the code is to handle the payment process for a ticket, including displaying the total cost, checking if gratuity is required or added, collecting payment, and processing the transaction. It ensures the user pays the correct amount, records the payment, calculates change due, and marks the ticket as pa... | def pay_ticket(self):
print_top(f"Pay Ticket: {self.id}")
print()
print(f"Total: ${self.calc_grand_total():.2f}")
print()
# Ask to add gratuity
if self.should_charge_auto_gratuity():
print(f"Gratuity is required for this ticket.")
print()
... |
def to_str( head ):
"""
to_str: FrozenNode -> str
Convert a sequence of nodes to a string of the nodes' values
surrounded by brackets and the individual values separated by commas.
It is a recursive solution.
:param head: The first node in the list to be converted
:return: The entire sequenc... | The code demonstrates operations on a linked list using a FrozenNode structure. It creates a list [5,10,15], inserts 1's at specific indices, appends 70 and 90, removes specific values (1 and 15), and finally clears the list by repeatedly removing the first element. The process illustrates list manipulation tasks like ... | def test():
print( "Create list [5,10,15]." )
lst = FrozenNode( 5, FrozenNode( 10, FrozenNode( 15, None ) ) )
print( to_str( lst ) )
print( "Insert 1's everywhere in the list by index." )
lst = insert_before_index( lst, 1, 3 )
for i in range( 2, -1, -1 ):
lst = insert_before_index( lst,... |
def draw_bowtie0(size):
'''
Draws nothing
'''
pass
def draw_bowtie1(size):
'''
Draws one bowite
Preconditions: turtle facing East
Postconditions: turtle facing East in the starting location
'''
# Draws the bowtie
turtle.left(30)
turtle.forward(size)
turtle.right(120)
turtle.forward(size)
turtle.right(... | The main task of the code is to generate and display bowtie fractals of increasing depths (0–5) using Python's turtle module. It sets up the canvas, configures colors and speed, prompts user input to sequentially draw each fractal depth, and finally allows a custom depth input. The code clears the canvas between each f... | def main():
'''
Calls the bowtie functions in order
'''
# Sets the canvas size
turtle.setup(720,720)
# Sets the pen color and fill color
turtle.color("cyan", "pink")
# Makes the pen really fast
turtle.speed(0)
# Makes the 0th depth fractal
draw_bowtie0(turtle.window_width()/6)
# Makes the 1th depth fr... |
def overlap_matrix(self, L, eta):
AL = self.gaussian_integral(2 * L + 2, eta + eta.T)
BL = self.gaussian_integral(2 * L + 2, eta.conj() + eta.T)
return 2 * (AL + BL).real
def kinetic_potential(self, nuclear_system, eta):
AH0 = 2 * eta * eta.T * self.gaussian_integral(2 * nuclear_system.L + 4, eta + eta.... | This code constructs a Hamiltonian matrix for a nuclear system by combining kinetic, nuclear, and Coulomb potentials with a transformation matrix. It applies Cholesky decomposition to the overlap matrix, transforms the Hamiltonian components, and returns the transformed matrices along with potentials and inverse matric... | def hamiltonian(self, nuclear_system, N):
b = np.pi / 2 if nuclear_system.L == 0 else np.pi / nuclear_system.L / 3
eta = self.alpha * complex(1, b)
n = nuclear_system.L + 1.5
N_cos = np.sqrt(4 * (2 * self.alpha * np.sqrt(1 + b**2))**n / \
gamma(n) / ((1 + b**2)**(n / 2) + np.cos(n * np.arcta... |
def add_acc_message(s):
# This function create
acc_message = '\n' + '\n'.join(textwrap.wrap(s,120))
print('\n'.join(textwrap.wrap(s,120)))
with open('debug.txt', 'a') as file:
file.write(acc_message)
def bq_copy_table(source_dataset, source_table, dest_dataset, dest_table, client):
source_t... | The code assigns stable versions to BigQuery tables by copying data and labels from the latest version to a date-specific stable table, excluding two specified tables. It reads table names from 'query_order.csv', iterates through them, and uses BQ functions to perform the copy operations, ensuring metadata (labels) fro... | def assign_stable_version(date, dataset):
# read the order or running querries
add_acc_message(f"Start assigning stable version to {date}. Load query order from query_order.csv")
with open('query_order.csv', encoding='utf-8-sig') as f:
reader = csv.reader(f)
qlist = list(reader)
# loop t... |
def add_acc_message(s):
# This function create
acc_message = '\n' + '\n'.join(textwrap.wrap(s,120))
print('\n'.join(textwrap.wrap(s,120)))
with open('debug.txt', 'a') as file:
file.write(acc_message)
def bq_copy_table(source_dataset, source_table, dest_dataset, dest_table, client):
source_t... | The main task of the code is to assign stable versions to tables in a BigQuery dataset by copying tables from the query order list with a specified date suffix and transferring labels from their latest versions, excluding two specific tables. It reads a query order list from a CSV file, iterates through the tables, and... | def assign_stable_version(date, dataset):
# read the order or running querries
add_acc_message(f"Start assigning stable version to {date}. Load query order from query_order.csv")
with open('query_order.csv', encoding='utf-8-sig') as f:
reader = csv.reader(f)
qlist = list(reader)
# loop t... |
def error(msg):
print("*** ERROR ***");
print(msg)
print("\n\n")
input("Press Enter to continue...")
sys.exit(0)
def parseFaceTag(f, lena, linenb):
x = f.split("/")
if len(x) == 0 or len(x) > 3:
error(f"wrong face index: {f} at line {linenb+1}")
if len(x) == 1:
x += ['',... | The code reads and parses an .obj 3D model file, extracting vertices, texture coordinates, normals, and faces. It organizes faces into objects with tags, validates index ranges, checks for missing texture/normal data, and returns structured geometry data along with object tags. | def loadObjFile(filename):
"""
Load the .obj file
"""
vertice = []
texture = []
normal = []
obj = []
tag = []
currentobj = []
currentname = ""
currenttagline = 0
currentnb = 0
print(f"Reading file {filename}.\n")
try:
with open(filename, "r"... |
def load(image_file):
image = tf.io.read_file(image_file)
image = tf.io.decode_jpeg(image)
w = tf.shape(image)[1]
w = w // 2
input_image = image[:, w:, :]
real_image = image[:, :w, :]
input_image = tf.cast(input_image, tf.float32)
real_image = tf.cast(real_image, tf.float32)
return input_image, rea... | The main task of the code is to preprocess training images by loading an image pair, applying random jitter for data augmentation, normalizing pixel values, and returning the processed input and real images for model training. | def load_image_train(image_file):
input_image, real_image = load(image_file)
input_image, real_image = random_jitter(input_image, real_image)
input_image, real_image = normalize(input_image, real_image)
return input_image, real_image |
def is_key_pressed(key):
return ctypes.windll.user32.GetAsyncKeyState(key) & 0x8000 != 0
def solve_4_angle(x, y, v0, g, res_coef, a = 90):
# Lower and upper - borders
lower = 89
upper = 90
# A small optimization. We don't have to count an angle that close to 90,
# because it will play into th... | The main task of the code is to automate a basketball game by detecting the positions of the ball and hoop in real-time screenshots, calculating the optimal throwing angle using physics equations, and controlling the mouse cursor to simulate shooting. It adjusts for screen resolution, uses template matching for object ... | def main():
# Height of the screen
h_screen = win32api.GetSystemMetrics(1)
# A coefficient to equalize some data for the current environment
resolution_coefficient = h_screen / 1440
# Physical parameters of game world:
v0 = 2632.1094902 * resolution_coefficient # - initial velocity
g = 37... |
def is_key_pressed(key):
return ctypes.windll.user32.GetAsyncKeyState(key) & 0x8000 != 0
def add_to_excel(score):
wb = load_workbook("Results.xlsx")
ws = wb['Data']
ws.append(['Score:', score])
wb.save("Results.xlsx")
def replay():
move(977, 1267) # Possition of replay button
win32api.mouse_... | The code automates a game by detecting in-game elements (ball, ring, score) via computer vision, calculating optimal throwing angles using physics equations, and simulating mouse actions to score points. It adjusts for screen resolution, reads scores with OCR, logs results to Excel, and repeats until manually stopped. | def main():
# Height of the screen
h_screen = win32api.GetSystemMetrics(1)
# A coefficient to equalize some data for the current environment
resolution_coefficient = h_screen / 1440
# Physical parameters of game world:
v0 = 2632.1094902 * resolution_coefficient # - initial velocity
g = 37... |
def perform_move(x: int, y: int, ms_variation=None):
if ms_variation is None:
ms_variation = [10, 30]
current_x, current_y = get_position()
cp = random.randint(3, 5) # Number of control points. Must be at least 2.
# Distribute control points between start and destination evenly.
array_x =... | The code automates the detection and interaction with in-game elements (runes, nodes) to siphon resources. It continuously searches for rune essences and specific creature nodes, moves to confirmed nodes, checks for confirmation messages, and initiates siphoning threads when a higher-value node is found, optimizing res... | def garyspan_loop():
global FOUND_BETTER
while True:
print("searching")
rune_ess = pyautogui.locateOnScreen(RUNE_ESSENCE, confidence=0.8, region=ACTIVE_WINDOW_REGION)
if rune_ess is None:
print("todo fetch rune ess")
for rc in RunespanCreature:
node = pya... |
def perform_move(x: int, y: int, ms_variation=None):
if ms_variation is None:
ms_variation = [20, 40]
current_x, current_y = get_position()
cp = random.randint(3, 5) # Number of control points. Must be at least 2.
# Distribute control points between start and destination evenly.
array_x =... | This function locates a "banker" icon/image on-screen, either using the last known position or by searching the active window region. It attempts to find the icon with retries and a time limit, adjusting mouse position and region if unsuccessful. Upon detection, it moves to the banker's location, confirms the find, cli... | def find_banker(use_last_position: bool = False):
global BANKER_LAST_POSITION
global BANKER_LAST_REGION
global RESTART_MAIN_LOOP
if use_last_position:
perform_move(x=BANKER_LAST_POSITION[0],
y=BANKER_LAST_POSITION[1])
perform_click()
current_region = BANKER_LAS... |
def focus_minimap_north():
x_to_click = COMPASS_CENTER[0] + random.randint(-10, 10)
y_to_click = COMPASS_CENTER[1] + random.randint(-10, 10)
perform_move(x_to_click, y_to_click)
perform_click()
def perform_move(x: int, y: int, ms_variation=None):
if ms_variation is None:
ms_variation = [20, ... | The code automates locating and interacting with the "Edge Bank" on a game's minimap. It repeatedly presses a key to search for the bank's image, uses image recognition to detect it, calculates its position with random offsets, and performs a move/click action once detected. The process includes random intervals and va... | def teleport_to_edge():
focus_minimap_north()
edge_bank = None
while edge_bank is None:
pyautogui.press(KEYBIND_FOR_WILDERNESS_SWORD, presses=random.randint(1, 3), interval=(random.randint(15, 25) / 100))
time.sleep(random.randint(30, 50) / 10)
print("searching for bank")
e... |
def perform_move(x: int, y: int, ms_variation=None):
if ms_variation is None:
ms_variation = [20, 40]
current_x, current_y = get_position()
cp = random.randint(3, 5) # Number of control points. Must be at least 2.
# Distribute control points between start and destination evenly.
array_x =... | This function automates interacting with a game's action bar slots by clicking on a starting slot and subsequent slots with randomized offsets to avoid detection, then triggers a banker interaction and preset loading if not restarting. It adds randomness to mouse positions and includes delays between actions. | def fill_pouches(start_index: int, use_last_position: bool = False):
perform_move(x=ACTION_BAR_SLOT_REGION_CENTER[start_index][0] + random.randint(-10, 10),
y=ACTION_BAR_SLOT_REGION_CENTER[start_index][1] + random.randint(-10, 10))
pyautogui.click()
for i in range(start_index + 1, start_in... |
def find_and_click_from_image_list(image_list: list, region: list, x_variance: list, y_variance: list, confirmation_image=None,
confidence: float = 0.8) -> [int, int]:
for image in image_list:
found_image = pyautogui.locateOnScreen(image, confidence=confidence, region=regi... | The code automates crafting runes by managing cooldowns for potions (RC_POT_ACTIVE, POWERBURST_COOLDOWN) and searching for an altar image. It presses keybinds for potions, updates cooldowns, and uses image recognition to locate an altar. If the altar isn't found within 10 seconds, it moves to the last known position, c... | def craft_runes():
global POWERBURST_COOLDOWN
global RC_POT_ACTIVE
global ALTAR_LAST_POSITION
now = datetime.datetime.now()
if RC_POT_ACTIVE < now:
pyautogui.press(KEYBIND_FOR_EXTREME_RC_POTION, presses=random.randint(1, 3), interval=random.randint(10, 15) / 100)
RC_POT_ACTIVE = no... |
def perform_move(x: int, y: int, ms_variation=None):
if ms_variation is None:
ms_variation = [20, 40]
current_x, current_y = get_position()
cp = random.randint(3, 5) # Number of control points. Must be at least 2.
# Distribute control points between start and destination evenly.
array_x =... | The code's main task is to move a game character (Slayer Master) to a detected location, perform a click, wait, and then locate and interact with a wilderness wall. It uses image recognition to find targets, adds random offsets for movement variability, and executes timed actions like "surge" and waits for cooldowns, l... | def move_to_wall_and_hop():
global SLAYER_MASTER_LAST_POSITION
slayer_master = pyautogui.locateOnScreen(SLAYER_MASTER_IMAGE, confidence=0.8, region=MINIMAP_REGION)
if slayer_master is not None:
slayer_master_x, slayer_master_y = pyautogui.center(slayer_master)
perform_move(x=slayer_master_x... |
def find_and_click_from_image_list(image_list: list, region: list, x_variance: list, y_variance: list, confirmation_image=None,
confidence: float = 0.8) -> [int, int]:
for image in image_list:
found_image = pyautogui.locateOnScreen(image, confidence=confidence, region=regi... | The code navigates to a wizard by locating trees and rivers using image recognition, moving to their last known positions if detection fails. It initiates a thread for 'enter_the_abyss', triggers a surge, performs random movement, and waits for the thread to complete. | def navigate_to_wizard():
global TREE_LAST_POSITION
global RIVER_LAST_POSITION
tree_x, tree_y = find_and_click_from_image_list(TREE_IMAGES, ACTIVE_WINDOW_MIDDLE_REGION, [-20, 20], [-20, 20])
if None in [tree_x, tree_y]:
perform_move(TREE_LAST_POSITION[0], TREE_LAST_POSITION[1])
perform_... |
def refresh_familiar():
global FAMILIAR_REFRESH_TIME
icon_found = None
while icon_found is None:
icon_found = pyautogui.locateOnScreen(BANKING_ICON, confidence=0.8, region=BANKING_ICON_SCREEN_REGION)
if icon_found is not None:
pyautogui.press(KEYBIND_FOR_SECOND_PRESET, presses=... | The code's main task is to check if the current time exceeds a specified refresh time for a "familiar" and trigger a refresh if so. If the main loop isn't restarting, it loads a preset, fills the first four inventory slots, and continues filling pouches starting from position 5 using the last position's data. This auto... | def perform_banking():
if datetime.datetime.now() > FAMILIAR_REFRESH_TIME:
print("referesing familiar")
refresh_familiar()
if not RESTART_MAIN_LOOP:
load_preset()
# click first 4 slots on main bar
fill_pouches(1)
fill_pouches(5, use_last_position=True) |
def teleport_to_edge():
focus_minimap_north()
edge_bank = None
while edge_bank is None:
pyautogui.press(KEYBIND_FOR_WILDERNESS_SWORD, presses=random.randint(1, 3), interval=(random.randint(15, 25) / 100))
time.sleep(random.randint(30, 50) / 10)
print("searching for bank")
e... | The code automates a runecrafting process in a game by looping through tasks: teleporting to a location, banking resources, moving to a wizard, navigating to an altar, rotating the camera, entering the altar, and crafting runes. The loop checks a global flag (RESTART_MAIN_LOOP) to determine if tasks should restart or c... | def runecrafting_loop():
global RESTART_MAIN_LOOP
while True:
RESTART_MAIN_LOOP = False
teleport_to_edge()
find_banker()
if not RESTART_MAIN_LOOP:
perform_banking()
move_to_wall_and_hop()
navigate_to_wizard()
if not RESTART_MAIN_... |
def forward(self, input_sequence, debug=False, debug_state=None):
h_temp = []
a_temp = []
o_temp = []
p_temp = []
last_state = self.h[-1]
self.prev_state = last_state
if debug:
last_state = debug_state
for char in input_sequence:
evars = self.evaluate(char, last_state)
last_state = evars['h'... | The code trains a neural network model using RMSProp optimization on encoded text data. It processes sequences of length `seq_len`, performs forward and backward passes, updates weights with the RMSProp algorithm, and generates text samples during training. The loss is tracked and plotted, with periodic logging of trai... | def fit(self, n_epochs=100, seq_len=25, eta=0.01, gamma=0.9, sample_len=1000):
self.log_o = [0]
self.log_V = [0]
self.log_c = [0]
self.log_h = [0]
self.log_Vh = [0]
input_data = self.text_source.encoded_text
generated_sample = []
init_time = time.time()
time_prev = time.time()
for epoch in range(n_e... |
def train(n, m):
#read the train data
reviews = pd.read_csv("data/labeledBow.feat", sep = "\n", header = None, names=['Review'])
#make vectors out of the data
vectors = get_vectors(n, m, reviews, 'Review')
#remove a pair of commands (possitive/negative) and command before "getting the list..." comme... | The function trains an ID3 decision tree using parameters n and m, evaluates it on test data by classifying vectors, and calculates performance metrics (accuracy, precision, recall, F1 score) by comparing predicted vs actual classifications. It returns TP, TN, FP, FN counts and prints evaluation results. | def id3(n, m):
print("ID3 is running...")
#train our algorithm and get the decision tree
tree = train(n, m)
print("Tree made - algorithm trained...")
#read and create the test vectors
test_df = pd.read_csv("data/labeledBow.feat", sep = "\n", header = None, names=['TestReview'])
test_vectors ... |
def train(n, m):
#read the train data
#reviews = pd.read_csv("neg", sep = "\n", header = None, names=['Review'])
#make vectors out of the data
vectors = get_vectors(n, m, vocabulary, 'Review')
#remove a pair of commands (possitive/negative) and command before "getting the list..." comment
#from ... | The function `naiveBayes(n, m)` trains a Bernoulli Naive Bayes classifier using parameters `n` and `m`, computes probability distributions from training data, and evaluates the model on test data from "labeledBow.feat". It classifies each test sample, tracks true positives (TP), true negatives (TN), false positives (FP... | def naiveBayes(n, m):
print("Bernoulli Naive Bayes is running...")
#train our algorithm and get the tuple of probability related data
train_probs = train(n, m)
print("Probabilities calculated - algorithm trained...")
#read and create the test vectors
test_df = pd.read_csv("labeledBow.feat", sep ... |
def handle_custom_function(custom_function_str, num_variables, initial_point, edge_length, tol):
"""
Handles a custom function of any number of variables (1, 2, 3).
This function validates the input string, converts it into a sympy expression, and uses it
to create a lambda function. It also checks the... | The main task of the code is to validate user inputs for parameters like initial point, edge length, and tolerance, ensure only one custom function is selected, and trigger the appropriate algorithm and visualization (2D/3D/4D) based on user choices. It handles errors for invalid inputs and selects either a predefined ... | def submit():
"""
Data processing after pressing the "submit" button. If all the data is correct,
the algorithm is launched, the function and the extremum are drawn
:return: None
"""
try:
initial_point = [float(entry_init_point_x.get()), float(entry_init_point_y.get()),
... |
def find_command(command: str, msg: Optional[str] = None) -> str:
return run_pipe("which", command, msg=msg).read().strip()
def run_pipe(*args: str, msg: Optional[str] = None, verbose: bool = False, **kwargs: Any) -> TextIO:
p = run(*args, msg=msg, verbose=verbose, stdout=PIPE, universal_newlines=True, **kwargs... | This function configures and builds a software project using CMake, handling compiler selection, proxy settings, build type, and parallel jobs. It validates CMake version, sets build options, and executes the build process for targets like 'kvrocks' and 'unittest', with flexibility for custom configurations and skippin... | def build(dir: str, jobs: Optional[int], ghproxy: bool, ninja: bool, unittest: bool, compiler: str, cmake_path: str, D: List[str],
skip_build: bool) -> None:
basedir = Path(__file__).parent.absolute()
find_command("autoconf", msg="autoconf is required to build jemalloc")
cmake = find_command(cmak... |
def find_command(command: str, msg: Optional[str] = None) -> str:
return run_pipe("which", command, msg=msg).read().strip()
def run_pipe(*args: str, msg: Optional[str] = None, verbose: bool = False, **kwargs: Any) -> TextIO:
p = run(*args, msg=msg, verbose=verbose, stdout=PIPE, universal_newlines=True, **kwargs... | This function uses clang-format to either apply code fixes or check for style issues in source files. It verifies the required clang-format version, determines formatting options based on the 'fix' parameter, and executes the tool on detected source files within the project directory. | def clang_format(clang_format_path: str, fix: bool = False) -> None:
command = find_command(clang_format_path, msg="clang-format is required")
version_res = run_pipe(command, '--version').read().strip()
version_str = re.search(r'version\s+((?:\w|\.)+)', version_res).group(1)
check_version(version_str,... |
def find_command(command: str, msg: Optional[str] = None) -> str:
return run_pipe("which", command, msg=msg).read().strip()
def run_pipe(*args: str, msg: Optional[str] = None, verbose: bool = False, **kwargs: Any) -> TextIO:
p = run(*args, msg=msg, verbose=verbose, stdout=PIPE, universal_newlines=True, **kwargs... | This function runs clang-tidy on a project using LLVM's run-clang-tidy script. It verifies required tools exist, checks for compile_commands.json in the build directory, configures options like parallel jobs and fix mode, applies header filters via regex, then executes clang-tidy with specified parameters to analyze or... | def clang_tidy(dir: str, jobs: Optional[int], clang_tidy_path: str, run_clang_tidy_path: str, fix: bool) -> None:
# use the run-clang-tidy Python script provided by LLVM Clang
run_command = find_command(run_clang_tidy_path, msg="run-clang-tidy is required")
tidy_command = find_command(clang_tidy_path, msg="... |
def write_version(release_version: str) -> str:
version = release_version.strip()
if SEMVER_REGEX.match(version) is None:
raise RuntimeError(f"Kvrocks version should follow semver spec, got: {version}")
with open('src/VERSION.txt', 'w+') as f:
f.write(version)
return version
def find_c... | The main task of the code is to automate the preparation of a source package for release. It writes the version, commits changes, creates Git tags (or release candidate tags), generates a source tarball, signs it with GPG, and computes a SHA512 checksum for verification. This ensures standardized packaging and security... | def package_source(release_version: str, release_candidate_number: Optional[int]) -> None:
# 0. Write input version to VERSION file
version = write_version(release_version)
# 1. Git commit and tag
git = find_command('git', msg='git is required for source packaging')
run(git, 'commit', '-a', '-m', f... |
def validate_env_var():
verify_dotdoctor_dir_env()
validate_dotdoctor_dir()
def validate_directory_structure():
validate_root_directory()
validate_backup_directory()
def load_ignore_file():
global ignore, root_path
ignore_path = os.path.join(root_path, "ignore")
if os.path.exists(ignore_path... | The main task of the code is to initialize a project environment by validating environment variables, directory structure, and loading an ignore file, then generating a configuration list and updating data status. It ensures prerequisites are met for proper setup and operation. | def initialize():
validate_env_var()
validate_directory_structure()
load_ignore_file()
create_config_list()
update_dot_data_status() |
def init_color_pairs():
# GREEN on BLACK
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
# RED on BLACK
curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK)
# MAGENTA on BLACK
curses.init_pair(3, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
# GREEN on WHITE
curses.init_pair... | This function manages a curses-based interface loop for displaying and navigating a configuration list. It hides the cursor, initializes color schemes, and repeatedly clears/re-draws the screen with navigation help and configuration options. It processes user input and exits when an exit code is received, ensuring resp... | def config_list_loop(stdscr):
global current_index, got_exit_code
curses.curs_set(False)
init_color_pairs()
while True:
stdscr.clear()
draw_navigation_help(stdscr)
draw_list_of_configs(stdscr, current_index)
process_input(stdscr.getch())
if got_exit_code:
... |
def combine_tables(self):
"""Combine all tables together and add a preamble if required.
Unless -oo is specified, this is how input tables are arranged.
"""
all_tables = []
if self.label and len(self.files) > 1:
all_tables.append("% don't forget to manually re-label ... | The `run` method generates LaTeX code from tables, either combining all into a single file or saving each table separately. If `outfile` is specified, it uses `combine_tables` and saves the result; otherwise, it prints to the console. When `separate_outfiles` is set, it processes each table individually, adjusting outp... | def run(self):
"""The main method.
If all tables need to be put into a single file,
calls `combine_tables` method to generate LaTeX code
and then calls `save_content` function if `outfile` is provided;
otherwise, prints to the console.
If each table needs to be put into ... |
def print_menu():
print(" MENU ")
print("----------")
print("1: Play ")
print("2: Show score ")
print("3: Exit Program")
def play():
users_input = input("R for rock, P for paper, S for scissors: ")
computers_choice = random.choice(['r','p','s'])
printUsersInput(users_input, compu... | The main task of the code is to run a rock-paper-scissors game with a menu system. It displays rules, loops to let users choose actions (play, view score, or exit), and executes corresponding functions based on input. The loop continues until the user selects the exit option (3). | def main():
print("\nGame of rock paper scissors!! The rules are simple:\n")
print("Rock beats scissors\n")
print("Scissors beats paper\n")
print("Paper beats rock\n")
print("ok lets play!!\n")
option = 0
while option != 3:
print_menu()
option = int(input("Type number to c... |
def _print_back_page(self):
# Add Welcome! Section
self._print_welcome()
# Add the custom element to the Story
self._print_announcements()
self.hspace(0.25 * inch)
# Add the serving schedule section
self._print_serving_schedule()
def _print_front_page(self):
... | The main task of the code is to generate a multi-page PDF bulletin document using the provided service date. It assembles the content by printing the back page, front page, morning worship, and evening worship sections, with frame/page breaks to structure the layout, then compiles the final PDF using the collected stor... | def build(self, service_date):
self.data = BulletinData(service_date)
# Print the back of the bulletin
self._print_back_page()
# Add a FrameBreak to jump to the next frame
self.story.append(FrameBreak())
# Print the front of the bulletin
self._print_front_page()... |
def logger(qstate):
"""PFUI: Logs Response. Requires Unbound to run in daemon mode (-dv)"""
r = qstate.return_msg.rep
q = qstate.return_msg.qinfo
log_info("-" * 100)
log_info(
f"Query: {qstate.qinfo.qname_str}, "
f"type: {qstate.qinfo.qtype_str} ({qstate.qinfo.qtype}), "
f"c... | The function processes query events in a state machine, handling DNS resolution stages. It inspects resource records (RR) when queries complete (MODULE_EVENT_MODDONE), transmits results if valid, and updates module state (e.g., MODULE_FINISHED, MODULE_WAIT_MODULE). It logs events and errors, managing query state transi... | def operate(id, event, qstate, qdata):
"""
Unbound Pythonmod Required
pythonmod: Called when processing new (non-cached) queries. 'event' defines state-machine state.
PFUI is only invoked after a domain has been successfully resolved by the Iterator
and a valid RR exists (MODULE_EVENT_MODDONE).
... |
def create_physical_material():
mat = bpy.data.materials.new(name="Hair Physical Material")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
nodes.clear()
geo_input_node = nodes.new(type="ShaderNodeNewGeometry")
hair_node = nodes.new(type="ShaderNodeBsdfHairPrin... | The code processes hair strand data files, sets up rendering materials, reads head position data, and renders images for each batch of positions using different materials. It loads hair strands into Blender, positions them, applies materials, and generates renders for each head pose, then cleans up temporary objects an... | def main():
strand_names = [name[:-5] for name in os.listdir(STRANDS_DIR) if name.endswith('.data')]
strand_names.sort()
print(f"Found {len(strand_names)} strands files")
physical_mat = create_physical_material()
structure_mat = create_structure_material()
setup_render_engine()
setup_compo... |
def image_paths() -> tp.List[tp.Tuple[str, str]]:
paths = []
for dirname in os.listdir(SOURCE_DIR):
for filename in os.listdir(f"{SOURCE_DIR}/{dirname}"):
if not os.path.exists(f"{MASK_ROOT}/{dirname}/{filename[:-len('.jpg')]}.png"):
continue
if filename.endswith(... | The code processes images by iterating through specified paths, creating target directories if they don't exist, skipping existing output files, reading original images and masks, applying processing, overlaying results, and saving the final PNGs with progress tracking. | def main():
# img_dir, img_name = "01000", "01000"
for img_dir, img_name in tqdm.tqdm(image_paths()):
target_dir = f"{ORIENTATION_ROOT}/{img_dir}"
if not os.path.exists(target_dir):
os.mkdir(target_dir)
if os.path.exists(f"{target_dir}/{img_name}.png"):
continue
... |
def decode_operation(args):
if len(args) >=2 and args[1] == '-s' and args[2] == 'deploy':
return 'DEPLOY'
elif len(args) >=2 and args[1] == '-s' and args[2] == 'unittests':
return 'UNITTESTS'
elif len(args) >=2 and args[1] == '-s' and args[2] == 'teardown':
return 'TEARDOWN'
e... | The main task of the code is to control a CI/CD pipeline by determining the operation (UNITTESTS/DEPLOY) from command-line arguments, retrieving Git branch, S3 bucket, and cloud stack details, then executing testing or deployment workflows. For DEPLOY, it packages code, uploads artifacts to S3, and triggers deployment ... | def main():
""" Control function for the pipeline """
args = sys.argv
current_branch = pipeline_util.get_current_git_branch()
print(f'branch :: {current_branch}')
code_s3_bucket_name = pipeline_util.get_code_bucket(current_branch)
print(f's3 bucket name :: {code_s3_bucket_name}')
main_st... |
def print_line(n: int = 50, prefix="", c='-', eval_log=None):
print(f"{prefix}{c * n}", file=eval_log)
def _create_graph(gt_items, res_items, eval_log):
"""
Creates a bipartite graph from two sets of tables.
"""
# init a (bipartite) graph
G = nx.Graph()
gt_nodes, res_nodes, edges = set(), s... | The function evaluates ground-truth (GT) and recognized tables by creating a bipartite graph weighted by affinity scores, finding maximum weighted matches, and updating TP, FN, FP counts based on matched/unmatched nodes. It calculates precision, recall, and F1 scores for each page, logs results, and returns cumulative ... | def _eval_pairs_in_file(gt_label, res_label, gt_items, res_items, TP, FN, FP, ignore_fp, eval_log):
"""
Performs evaluation between the ground-truth and the recognized tables from a file.
Creates a bipartite graph from both sets of table nodes weighted by the affinity scores.
Finds the maximum weighted ... |
def print_line(n: int = 50, prefix="", c='-', eval_log=None):
print(f"{prefix}{c * n}", file=eval_log)
def _eval_pairs_in_file(gt_label, res_label, gt_items, res_items, TP, FN, FP, ignore_fp, eval_log):
"""
Performs evaluation between the ground-truth and the recognized tables from a file.
Creates a bip... | The function `eval_data` evaluates result files against ground-truth data, calculating true positives (TP), false positives (FP), and false negatives (FN). It compares candidates in result files with ground-truth items, selecting the best-performing variant (if enabled) using F1 score and secondary metrics. It logs eva... | def eval_data(gt_files, res_files, res_multivariant=True, ignore_fp=False, eval_log=None):
"""
Performs evaluation on a given set of ground-truth and result files.
"""
TP, FP, FN = 0, 0, 0
print_line(c='=', n=100, eval_log=eval_log)
for key, gt_items in gt_files.items():
if key in... |
def cards_to_dict(input_data):
card_dict = {}
for row in input_data:
lottery_nums = set(int(i) for i in row[1].split())
found_numbers = set(int(i) for i in row[2].split())
num_overlap = len(lottery_nums.intersection(found_numbers))
card_dict[row[0]] = [i for i in range(row[0]+1,... | The code processes a file containing card data by parsing it into a structured dictionary, then computes and prints two parts of a solution (Part 1 and Part 2) based on the parsed card information, likely for a problem-solving task like Advent of Code. | def main():
file_path = only_filepath_argparse()
input_data = read_from_regex(file_path, r'Card [ ]*(\d+): (.*)\|(.*)',[int,str,str])
card_dict = cards_to_dict(input_data)
print(f"Part 1 Ans: {part1(card_dict)}")
print(f"Part 2 Ans: {part2(card_dict)}") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.