dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def ProcessLibrary():
linked_list = LinkedList()
Lines = ReadInput(IndexFile)
Data = []
maps = dict()
for line in Lines:
#print("Input -> ",line)
docId, WordString = ExtractLine(line)
#print ("Doc id -> "+docId)
#print("Doc text -> "+WordString+"\n")
if docId ... | The main task of the code is to process search terms by converting them into indexes using a linked list data structure, then saving these indexed results as a JSON file. It initializes a linked list from a library, processes search queries, maps them to indexes via the linked list, and writes the output to a file for ... | def main():
linked_list = ProcessLibrary()
#print(linked_list.traverse_list())
#print(GetIndexesOfstemmedWord("etiopathogenesi", linked_list))
SearchWords = ProcessSearch()
Searches = ConvertSearchesIntoIndex(SearchWords, linked_list)
with open(outfile, 'w') as outfilePointer:
json.dump(... |
def End_of_game(tababla):
if sum(tababla[0:6])==0 or sum(tababla[7:13])==0:
return True
else:
return False
def Evaluation(tabbla,plTn,Iam): #ocenjujem moju trenutnu tablu utility fjas HEURISTIC
winner=CheckWinner(tabbla)
if Iam and winner==plTn:
return 100000
el... | The main task of the code is to implement the Minimax algorithm with alpha-beta pruning for a two-player game. It recursively evaluates all possible moves, alternating between maximizing (AI player) and minimizing (opponent) scores. The function returns the optimal evaluation value for the current board state, consider... | def MinMax(board, depth, alpha, beta, playerAI,playerTn):
print("MIN-MAX fja, board: ",board, "alpha,beta :",alpha,beta, )
if depth==0 or End_of_game(board):
res= Evaluation(board,playerTn,playerAI) # 1-(0,5 polja), 2-(7,12)
return res
if playerAI:
maxEval=float('-inf')
move... |
def get_local_data_dir(experiment, tactic, mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
return "data/experiment/{}/{}/{}/{}".format(experiment,
tactic.replace(" ", "_"),
get_mean_pooling_path_variabl... | The code uploads experiment results, including a confusion matrix image, results CSV, and compressed fold metrics, to a Google Cloud bucket. It generates local and remote directories based on input parameters, ensures the remote directory exists, and transfers files using a helper function. The fold metrics are zipped ... | def upload_results(tactic, experiment, mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
LOCAL_DATA_DIR = get_local_data_dir(experiment, tactic, mean_pooling_parameters, hidden_layer_used, num_of_hidden_units)
REMOTE_DATA_DIR = get_remote_data_dir(experiment, tactic, mean_pooling_parameters, hid... |
def get_local_data_dir(experiment, tactic, mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
return "data/experiment/{}/{}/{}/{}".format(experiment,
tactic.replace(" ", "_"),
get_mean_pooling_path_variabl... | The function saves hyperparameters, hidden layer settings, and mean pooling configurations into a JSON file locally and uploads it to a Google Cloud Storage bucket. It constructs local and remote directory paths, ensures the cloud directory exists, and transfers the parameters file for storage and retrieval in a machin... | def save_parameters(tactic, experiment, hyper_parameters, hidden_layer_parameters, mean_pooling_parameters):
hidden_layer_used = hidden_layer_parameters['use_hidden_layer']
num_of_hidden_units = hidden_layer_parameters['number_of_hidden_units']
LOCAL_DATA_DIR = get_local_data_dir(experiment, tactic, mean_p... |
def get_report_dir(experiment, mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
return '{}/reports/{}/{}'.format(get_experiment_dir(experiment),
get_mean_pooling_path_variable(mean_pooling_parameters),
get_hidden_layer_path_v... | The code generates a performance report for a machine learning experiment by aggregating precision, recall, and F-measure metrics across different tactic classifications. It processes JSON-defined categories, retrieves results from cloud storage, calculates sample sizes, compiles metrics into a DataFrame, sorts them by... | def create_report_experiment_1(mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
# Opening JSON file
file_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
f = open("drive/My Drive/pytorch_notebooks/tactic_classifier/tactic_categories.json".format(file_directory))
# returns JSON ... |
def get_report_dir(experiment, mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
return '{}/reports/{}/{}'.format(get_experiment_dir(experiment),
get_mean_pooling_path_variable(mean_pooling_parameters),
get_hidden_layer_path_v... | The function generates a performance report for experiment 2 by aggregating classification metrics (precision, recall, F-measure) and sample sizes across subcategories from a JSON-configured dataset. It downloads tactic data, retrieves results from cloud storage, compiles them into a sorted DataFrame, and saves/uploade... | def create_report_experiment_2(mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
# Opening JSON file
file_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
f = open(
"drive/My Drive/pytorch_notebooks/tactic_classifier/tactic_categories.json".format(
file_directory... |
def get_report_dir(experiment, mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
return '{}/reports/{}/{}'.format(get_experiment_dir(experiment),
get_mean_pooling_path_variable(mean_pooling_parameters),
get_hidden_layer_path_v... | The function generates evaluation reports for machine learning models by aggregating precision, recall, F-measure, and sample size metrics across sub-categories. It processes JSON-defined categories, downloads tactic data, reads model results, constructs sorted reports, saves them locally, and uploads to Google Cloud S... | def create_report_experiment_3(mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
# Opening JSON file
file_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
f = open(
"drive/My Drive/pytorch_notebooks/tactic_classifier/tactic_categories.json".format(
file_directory... |
def get_report_dir(experiment, mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
return '{}/reports/{}/{}'.format(get_experiment_dir(experiment),
get_mean_pooling_path_variable(mean_pooling_parameters),
get_hidden_layer_path_v... | The main task of the code is to generate and upload a performance evaluation report for Experiment 5. It loads classification categories, retrieves model results from a CSV file, calculates class distributions, appends sample sizes to metrics, sorts the data by F-Measure, saves the report locally as a CSV, and uploads ... | def create_report_experiment_5(mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
# Opening JSON file
file_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
f = open(
"drive/My Drive/pytorch_notebooks/tactic_classifier/tactic_categories.json".format(
file_directory... |
def get_report_dir(experiment, mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
return '{}/reports/{}/{}'.format(get_experiment_dir(experiment),
get_mean_pooling_path_variable(mean_pooling_parameters),
get_hidden_layer_path_v... | The function generates performance reports for subcategories in experiment 6 by aggregating precision, recall, F-measure, and sample size metrics from model results. It processes JSON-defined categories, downloads tactic data, retrieves evaluation results, sorts them by F-measure, and saves/uploaded CSV reports to Goog... | def create_report_experiment_6(mean_pooling_parameters, hidden_layer_used, num_of_hidden_units):
# Opening JSON file
file_directory = os.path.dirname(os.path.abspath(sys.argv[0]))
f = open(
"drive/My Drive/pytorch_notebooks/tactic_classifier/tactic_categories.json".format(
file_directory... |
def transition_notes(self):
"""
Play a few notes to indicate a transition
"""
print("Playing transition notes")
self.audio_sequence_ac.wait_for_server()
# half a second in nanoseconds
half_sec = Duration(sec=0, nanosec=500000000)
duration = Duration(sec=0,... | The main task of the code is to execute a patrol routine where the robot checks if it's busy, then performs actions like undocking, driving, completing a mission, returning to dock, and docking, while using a 'busy' flag to prevent overlapping operations. It logs status updates and transitions between states through pr... | def patrol(self):
"""
This function will run every time the timer is triggered
"""
if self.busy:
print("Busy, skipping patrol...")
return
self.busy = True
print("Patrolling...")
self.transition_notes()
print("Undock and Drive")
... |
def remove_users(tweet):
"""Takes a string and removes retweet and @user information"""
tweet = re.sub('(RT\s@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove re-tweet
tweet = re.sub('(@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove tweeted at
return tweet
def remove_links(tweet):
"""Takes a string ... | The function preprocesses tweets by removing users, links, hashtags, and av (possibly abbreviations), lowercasing text, stripping punctuation and numbers, normalizing spacing, tokenizing, and applying lemmatization to return a cleaned, normalized string for analysis. | def preprocess_tweet(tweet: str, topics: list) -> str:
"""Main master function to clean tweets, stripping noisy characters, and tokenizing use lemmatization"""
tweet = remove_users(tweet)
tweet = remove_links(tweet)
tweet = remove_hashtags(tweet)
tweet = remove_av(tweet)
tweet = tweet.lowe... |
def start_cmd(self):
""" @return Command line to start application. """
return self.conf['start_cmd']
def mkpath(self, relpath, pathtype='temp', unique=False):
""" pathtype := perm, temp, log """
path = os.path.join(self.root_path(), relpath)
if unique is True:
path +... | The main task of the code is to execute an application using a command retrieved from `start_cmd()`, redirect its standard output and error to log files (`stdout.log` and `stderr.log`), and return `True` if the application was successfully started (i.e., `start_cmd` is not `None`), otherwise return `False`.)> | def run(self):
""" Run application using conf @param start_cmd.
@returns true if app was started, or false if no start_cmd """
start_cmd = self.start_cmd()
if start_cmd is None:
return False
self.stdout_fd = open(self.mkpath('stdout.log', pathtype='log'), 'a')
... |
def dbg(self, msg):
if self.debug:
return self.log(msg)
def log(self, msg):
print('[%s] %s-%s: %s' %
(datetime.datetime.now(), self.name, self.appid, msg))
def wait_stopped(self, timeout=30, force=False):
"""
Wait for process to terminate.
Application .s... | The main task of the code is to stop a running process by sending a termination signal (SIGTERM) to its process group, optionally waiting for it to stop, updating the process state, and cleaning up resources like file descriptors and the process object. It handles cases where the process might already be dead, logs sta... | def stop(self, wait_term=True, force=False):
if self.state != 'started':
return
self.dbg('Stopping (pid {})'.format(self.proc.pid))
try:
os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
except OSError as e:
self.log('killpg() failed: already dead?... |
def status(self):
if self.state == 'started' and self.proc is not None and self.proc.poll() is not None: # noqa: E501
r = self.proc.wait()
if r != 0:
self.log('process terminated: returncode %s' % (str(r)))
else:
self.dbg('process terminated: ... | The function waits up to the specified timeout for an application to become operational. It repeatedly checks the application's status and operational state, returning True if operational (after executing post-commands) or False if the application stops or the timeout elapses. | def wait_operational(self, timeout=30):
""" Wait for application to go operational """
t_end = time.time() + timeout
while time.time() < t_end:
if self.status() == 'stopped':
return False
if self.operational():
self.run_post_cmds()
... |
def env_add(self, name, value, append=True):
""" Add (overwrite or append) environment variable """
if name in self.env and append:
self.env[name] += ' %s' % value
else:
self.env[name] = value
def create_dir(self, relpath, unique=False):
path = self.mkpath(relpath... | This code initializes an application instance within a cluster, setting up configurations, environment variables, node assignment, runtime directories, and state tracking. It allocates an app ID, processes input parameters, prepares cleanup paths, and configures runtime settings for execution within the cluster's node. | def __init__(self, cluster, conf=None, on=None):
self.appid = Allocator(cluster).next(self)
self.name = self.__class__.__name__
self.cluster = cluster
self.autostart = True # Starts with cluster.start()
self.do_cleanup = True
# Environment variables applied to execution
... |
def _setup_kerberos(self):
""" Set up Kerberos KDCs """
# Create KDCs for each realm.
# First realm will be the default / broker realm.
#
realm_cnt = int(self.conf.get('realm_cnt', 1))
# No point in having more than two realms
assert realm_cnt > 0 and realm_cnt <... | (The main task of the code is to initialize and start a Kafka cluster with configurable parameters, including setting up security protocols (SSL/SASL), brokers, Zookeeper/KRaft mode, SSL certificates, Schema Registry, and client configurations. It merges default and user-provided settings, creates broker instances, val... | def __init__(self, **kwargs):
""" Create and start a KafkaCluster.
See default_conf above for parameters. """
super(KafkaCluster, self).__init__()
conf = kwargs
self.conf = deepcopy(self.default_conf)
if conf is not None:
self.conf.update(conf)
s... |
def segment(self, img_stack, minsize, background_label):
'''
Predict the cell bodies using the trained NN model
and further segment after removing small holes and objects
Parameters:
-------------
img_stack: ndarray. shape=(# of frames, # of rows, # of colomns) array of ... | The main task of the code is to process image stacks by loading a pre-trained neural network model, segmenting regions, calculating ROI intensity and DFF values, detecting peaks, analyzing ROI data, extracting metadata, and plotting results when the "Analyze" button is clicked. It also computes connectivity metrics and... | def _on_click(self) -> None:
'''
once hit the "Analyze" botton, the program will load the trained
neural network model based on the image size and call the functions
-- segment, ROI intensity, DFF, find peaks, analyze ROI, connectivity--
to analyze the image stacks and plot the d... |
def _record_folders(self, folder: str):
"""Record folder location for compilation."""
if folder not in self.folder_list:
self.folder_list.append(folder)
def _on_click(self) -> None:
'''
once hit the "Analyze" botton, the program will load the trained
neural network mo... | This method enables batch processing of TIFF files by allowing users to select a folder, analyzing all .ome.tif files within it. It loads images, applies a pre-trained UNET model based on image size, processes data, saves results, and compiles summaries. The function handles model initialization, image analysis, and da... | def _select_folder(self) -> None:
'''
allow user to select a folder to analyze all the tif file in the folder
parameters:
------------------
None
'''
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.Directory)
if dlg.exec_():
folder_na... |
def cbl_get_ver_cmd(self):
print("Requesting the bootloader version...")
cbl_get_ver_cmd_len = 6
bl_host_buffer = [0] * 255
bl_host_buffer[0] = cbl_get_ver_cmd_len - 1
bl_host_buffer[1] = CBL_GET_VER_CMD
crc32_value = calculate_crc32(bl_host_buffer, cbl_get_ver_cmd_len - ... | The function `decode_command` maps an integer `command` to specific handler methods (e.g., `cbl_get_ver_cmd`, `cbl_mem_write_cmd`) based on its value. It acts as a dispatcher, executing the corresponding method for valid commands (1–7, 12) or printing an error for invalid codes. The primary task is to route incoming co... | def decode_command(self, command):
if command == 1:
self.cbl_get_ver_cmd()
elif command == 2:
self.cbl_get_help_cmd()
elif command == 3:
self.cbl_get_cid_cmd()
elif command == 4:
self.cbl_get_rdp_status_cmd()
elif command == 5:
... |
def bits(self, need):
"""
Returns the number of bits needed from input stream.
:param state: state of stream and buffer
:param need: number of bits needed
:return: needed bits
"""
val = self.s.bitbuf
while self.s.bitcnt < need:
next_byte = self... | This function decompresses DEFLATE-encoded data by iterating through blocks. It checks if a block is the last, reads the compression mode (stored/fixed/dynamic), and applies corresponding decompression logic. It logs progress and raises an error if dynamic mode is encountered, as it's unimplemented. The loop continues ... | def inflate(self):
last = 0
while not last:
# Verify block
last = self.bits(1)
self.infgen_log("!")
if last and self.s.stream_idx != len(self.s.stream):
self.infgen_log("last block")
# Verify mode
mode = self.bits(... |
def compute_w_from_V_and_e(A,D,c,x,n):
e = np.zeros((n,1), dtype = float)
e = e + 1.0
V = compute_V_from_x(A,D,c,x,n)
v = np.dot(V,e)
w = np.dot(V,v)
return w
def compute_v_from_V_and_e(A,D,c,x,n):
V = compute_V_from_x(A,D,c,x,n)
e = np.zeros((n,1), dtype = float)
e = e + 1.0
... | This function computes the curvature of a geometric object using vectors v and w derived from inputs A, D, c, x, n. It calculates the projection operator P_e, then uses triple products of v, w, and P_e to apply a curvature formula involving (vPv·wPw - (vPw)²)/(vPv³), returning the square root of this value. | def compute_curvature(A,D,c,x,n):
w = compute_w_from_V_and_e(A,D,c,x,n)
v = compute_v_from_V_and_e(A,D,c,x,n)
P_e = compute_projection_operator_P_e(n)
vPv = triple_product_vector_matrix_vector(v,P_e,v)
wPw = triple_product_vector_matrix_vector(w,P_e,w)
vPw = triple_product_vector_matrix_vector(... |
def scatterplot(self, x, y):
points = self.unpack(x, y)
ax.scatter(points[0], points[1])
def f(self, x):
return self.sigmoid(x * self.W + self.b)
def loss(self, x, y):
return -np.mean(np.multiply(y, np.log(self.f(x))) + np.multiply((1 - y), np.log(1 - self.f(x)))) | The main task of the code is to generate a plot visualizing the relationship between input data (x) and output data (y), alongside the model's predicted outputs (self.f(x)). It creates a scatter plot of the data points, overlays a line plot of the model's predictions, displays the loss value, and adds axis labels, a le... | def plot(self, x, y, xlab = 'Input', ylab = 'Output', title = 'Logical NOT Operator'):
self.scatterplot(x, y)
ax.plot(x, self.f(x))
print('loss: ', self.loss(x, y))
ax.legend()
ax.set_xlabel(xlab)
ax.set_ylabel(ylab)
plt.title(title)
plt.show() |
def scatterplot(self, x_train, y_train, xlab, ylab):
ax.plot(x_train, y_train, 'o', label = '$(\\hat x^{(i)},\\hat y^{(i)})$')
ax.set_xlabel(xlab)
ax.set_ylabel(ylab)
def f(self, x):
return 20 * self.sigma(x * self.W + self.b) + 31
def loss(self, x, y):
return np.mean(np.square(s... | The code generates a 2D nonlinear regression plot by visualizing training data as a scatter plot, overlaying the model's predicted curve using its function $f(x)$, displaying the loss value, and adding a legend/title. It sorts input data for smooth curve plotting and uses a sigmoid-based function $20\sigma(xW + b) + 31... | def plot(self, x_arr, x_train, y_train, xlab, ylab, title = 'non_linear_regression_2d'):
self.scatterplot(x_train, y_train, xlab, ylab)
x_plot = np.sort(x_arr, axis = 0)
ax.plot(x_plot, self.f(x_plot), label = '$y = f(x) = 20\u03C3(xW + b) + 31$')
print('loss: ', self.loss(x_arr... |
def read_file(filename):
terms = []
f = open(os.path.join(LOAD_PATH, filename), "r")
for line in f:
if line != " " and line != "\n":
terms.append(line.replace("\n", "").replace(" ", ""))
return terms
def get_indexes(filename):
print()
count = 1
f = open(os.path.join(LOAD... | The code implements a WIKI SEARCHER tool that allows users to load term files, write to new files, or exit. It reads terms from input files, processes definitions, saves them to output files with error handling, and trims the output. The program loops until the user quits, handling file operations and user inputs for l... | def main():
while(True):
while(True):
print("\n" * 50)
print("WIKI SEARCHER. Files with terms must be formatted with one term per line.")
print("load files by typing 'l'. Type 'w' to write to a new file.\n"
+ "Type 'x' to quit the program at any time.")
... |
def get_weight_scheme_LIST_OF_LISTs(filepath):
graph_info = open_and_read_file(filepath)
weight_scheme = list()
if len(graph_info) > 0:
for line in graph_info:
if len(line) > 0:
weights_line_info = line.replace('\n', '').split()
for i, weight in enumerate(... | The main task of the code is to process graph files (e.g., 'graph.txt') by analyzing and printing multiple graph representations: weight schemes, successor lists, edge-weight dictionaries, sorted steps sequences, edge counts, and total edge weights. It iterates through specified files, applying six distinct tasks to vi... | def task01():
graph_files = ['graph.txt', 'graph0.txt']
for filepath in graph_files:
# TASK a
print("\n" + CYELLOWBG + "\tWEIGHT SCHEME\t" + CEND)
print(get_weight_scheme_LIST_OF_LISTs(filepath))
# TASK b
print("\n" + CYELLOWBG + "\tSUCCESSORS SCHEME\t" + CEND)
p... |
def _configure_socket_for_listening(self, udp_socket):
# Below code allows us to write to the UDP port
udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# disable self messages looping back
# udp_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
udp... | The main task of the code is to establish a UDP socket, configure it for listening, send a HELLO message to a specified socket path, and manage connections with other types of endpoints. The method initializes a UDP socket, sets it up to receive data, transmits an initial message, and continuously handles incoming conn... | def _main(self):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp_socket:
self._configure_socket_for_listening(udp_socket)
self._create_and_send_msg(HELLO, self.socket_path, udp_socket)
self._spin_and_manage_connection_with_other_type(udp_socket) |
def make_query_message(self):
"""Construct DNS query message"""
msg = dns.message.make_query(self.qname, self.qtype)
msg.flags &= ~dns.flags.RD
if self.caller.config.bufsize != 0:
flags = dns.flags.DO if self.caller.config.dnssec else 0
options_list = []
... | This function sends a DNS query using UDP or TCP based on configuration. It creates a query message, sends it via UDP, checks for truncated responses, logs warnings if needed, switches to TCP fallback if configured, calculates RTT, and returns the result or None. | def send_query(self):
"""Send DNS query"""
msg = self.make_query_message()
wire_msg = msg.to_wire()
if self.caller.config.tcponly:
return self.send_query_tcp(wire_msg)
self.set_query_start_time()
res = self.send_query_udp(wire_msg)
if res and (res.fl... |
def MakeGitHubRequest(url):
log.info("Making GitHubRequest: {0}".format(url))
#look up our query to see if we can make a conditional request
try:
log.info("Checking cache")
myRequestCache = GitHubRequestCache.objects.get(query = url)
log.info("Using ETag: {0}".format(myRequestCache.E... | The main task of the code is to process a GitHub repository by fetching its details, updating or creating a local Repo object with attributes like full name, description, and URL, marking the request as processed, and retrieving closed pull requests for further processing. It handles exceptions by logging errors and de... | def ProcessRepo(name):
try:
log.info("Getting id: {0}".format(name))
remoteRepoURL = "repos/{0}".format(name)
remoteRepo = MakeGitHubRequest(remoteRepoURL)
if remoteRepo:
try:
myRepo = Repo.objects.get(pk = remoteRepo["id"])
except ObjectDoes... |
def RefreshRateLimitStats():
rateInfo = MakeGitHubRequest('rate_limit')
for resource in rateInfo['resources'].keys():
resource = str(resource)
UpdateRateLimit(resource, rateInfo['resources'][resource]['limit'], rateInfo['resources'][resource]['remaining'], rateInfo['resources'][resource]['reset... | The main task of the code is to perform a bulk import of GitHub repositories by fetching them in batches, processing each repository's data, tracking API rate limits, and marking requests as processed once completed, while logging progress and handling potential errors in repository data retrieval. | def BulkImport():
output = "Initializing Population\n"
RefreshRateLimitStats()
remaining = RateLimitRemaining('core')
since = 0
#while remaining > 4999:
output += "{0} API Calls Left\n".format(remaining)
#get open source repositories
repoURL = 'repositories?since=' + str(since)
r ... |
def ProcessRepo(name):
try:
log.info("Getting id: {0}".format(name))
remoteRepoURL = "repos/{0}".format(name)
remoteRepo = MakeGitHubRequest(remoteRepoURL)
if remoteRepo:
try:
myRepo = Repo.objects.get(pk = remoteRepo["id"])
except ObjectDoes... | The function processes queued GitHub requests by retrieving unstarted cache entries, determining their type (repos/repositories), and executing corresponding actions: processing repositories or pull requests based on query parameters, deleting outdated entries, or marking invalid requests. It handles up to a specified ... | def ProcessGitHubRequest(numberToProcess=10):
log.info("----------------------")
log.info("Processing Queue")
myRequestCaches = GitHubRequestCache.objects.filter(started_at__isnull = True).order_by('created_at')[:numberToProcess]
for myRequestCache in myRequestCaches:
queryParameters = myReques... |
def get_input():
data = []
with open("input.txt", "r") as file:
for line in file:
data.append(line.strip())
return data
def assemble_readings(data):
gamma = ""
epsilon = ""
for bit in range(len(data[0])):
if add_pos(data, bit) >= len(data)/2:
gamma = gamma... | The main task of the code is to process input data to calculate and display the Gamma and Epsilon rates, their product, and the Life Support Rating. It retrieves input, assembles binary readings, computes the product of Gamma and Epsilon values, and determines the Life Support Rating using a separate function. The outp... | def main():
data = get_input()
gam, ep = assemble_readings(data)
print(f"Gamma: {gam}\nEpsilon: {ep}\n\tTotal: {int(gam, 2) * int(ep, 2)}")
print(f"Life Support Rating: {life_support(data)}") |
def parse_args():
"""
Driver arguments. These are passed to the ReactionDiffusionSimulator class
"""
parser = argparse.ArgumentParser()
global param_names
for name in param_names:
parser.add_argument('-' + name, default=[0, 0, 1], type=float, nargs='+')
parser.add_argument('-num_it... | The code's main task is to execute different simulation modes based on command-line arguments. It parses inputs, displays system/cpu info, creates output directories, and conditionally runs functions like speed tests, resuming simulations, parameter searches, or genetic algorithms. If no specific mode is specified, it ... | def main():
args, _ = parse_args()
print(f'thread count per core: {psutil.cpu_count() // psutil.cpu_count(logical=False)}')
print(f"Num cores = {psutil.cpu_count(logical=False)}")
print(f'Num_processes = {args.num_processes}')
make_output_dirs(args)
if args.test_speed:
test_speed(args)... |
def importDiscover(self, element):
schemaLocation = element.get("schemaLocation")
if element.localName == "include":
importNamespace = self.targetNamespace
isIncluded = True
else:
importNamespace = element.get("namespace")
isIncluded = False
... | This method processes child elements of an XBRL model object, prioritizing imports/includes, then handling linkbase-related elements (roleType, arcroleType, linkbaseRef, linkbase) by categorizing them or triggering discovery processes. It recursively explores nested elements to build the XBRL structure, ensuring proper... | def schemaDiscoverChildElements(self, parentModelObject):
# find roleTypes, elements, and linkbases
# must find import/include before processing linkbases or elements
for modelObject in parentModelObject.iterchildren():
if isinstance(modelObject,ModelObject):
ln = mod... |
def schemaLinkbaseRefsDiscover(self, tree):
for refln in ("{http://www.xbrl.org/2003/linkbase}schemaRef", "{http://www.xbrl.org/2003/linkbase}linkbaseRef"):
for element in tree.iterdescendants(tag=refln):
if isinstance(element,ModelObject):
self.schemaLinkbaseRefD... | The code's main task is to process an XBRL instance element by discovering schema linkbase references, linkbases (including role/arcroleRefs and footnoteLinks), instance content, and validating the XML against the XBRL model. This ensures proper structure, references, and compliance with XBRL standards for financial re... | def instanceDiscover(self, xbrlElement):
self.schemaLinkbaseRefsDiscover(xbrlElement)
self.linkbaseDiscover(xbrlElement,inInstance=True) # for role/arcroleRefs and footnoteLinks
self.instanceContentsDiscover(xbrlElement)
XmlValidate.validate(self.modelXbrl, xbrlElement) |
def change_input_format_callback(self, sv):
ok_format = self.serial_object.setDataFormat(sv.get())
if not ok_format:
self.format_entry.delete(self.format_entry.index(INSERT)-1)
def cb_selection_changed(self,unused):
selection = self.combobox.current()
if selection is 0... | The main task of the code is to create a GUI-based serial monitor and plotter application. It initializes a Tkinter window with input fields for serial port configuration, data formatting options, and buttons to control serial communication, data recording, and plotting. The code sets up a serial connection, handles in... | def __init__(self):
self.gui = Tk()
self.gui.title("MEGN540 Serial Monitor & Plotter")
# Contact Info
self.contact = Label(text="iqybf@example.com").place(x=250, y=437)
self.ok = True # flag to indicate shutdown has initiated
self.gui.protocol("WM_DELETE... |
def select_supervised_samples(dataset, n_samples=len(xtr), n_classes=2):
X, y = dataset
X_list, y_list = list(), list()
n_per_class = int(n_samples / n_classes)
for i in range(n_classes):
# get all images for this class
X_with_class = X[y == i]
# choose random instances
i... | The main task of the code is to train a GAN (Generative Adversarial Network) with a supervised classifier. It alternates between training the classifier on labeled data, the discriminator on real/fake samples, and the generator to produce realistic data. The function updates models iteratively, tracks losses, and perio... | def train(g_model, d_model, c_model, gan_model, dataset, latent_dim, n_epochs=100, n_batch=4,l_d=list(),l_g=list(),l_c=list()):
# select supervised dataset
X_sup, y_sup = select_supervised_samples(dataset)
print(X_sup.shape, y_sup.shape)
# calculate the number of batches per training epoch
bat_per_e... |
def setPlayers(self, color):
if (color == BLACK):
self.player = Player.Player(BLACK)
self.cpu = Player.Player(WHITE)
elif (color == WHITE):
self.player = Player.Player(WHITE)
self.cpu = Player.Player(BLACK)
else:
print("You didn't ent... | This code implements a two-player board game where the user selects their color (black or white) and alternates turns with the CPU. The game continues until the board is full, at which point it displays the final score. The player's moves are handled by `player_hand()`, while the CPU's moves are managed by `cpu_hand()`... | def start(self):
# ignore for now
# self.gui.show_game()
# self.gui.update(self.board.board, 2, 2)
# get colors of players
keepPlaying = True
x = True
while(x):
try:
color = int(input("What color do you want to be? 1 = black, 0 = white... |
def getPointingTasks(state, mgoal):
"""
The method to get all the tasks that are related to pointing in the goal.
Args:
state: The state of the system.
mgoal: The goal state of the system.
Returns:
Returns the list of the pointing tasks that are not completed yet.
"""
t... | The function `m_achieveGoal` generates a plan to transition the system from its current `state` to the target `mgoal`. It processes tasks related to image acquisition and pointing adjustments. For image tasks, it checks prerequisites (e.g., calibration, power) and returns a sequence of actions like `calibrateInstrument... | def m_achieveGoal(state, mgoal):
"""
The main planner that creates the plan based on the task that needs to be performed.
Args:
state: The state of the system.
mgoal: The goal state the system has to reach.
Returns:
Returns the plan if possible.
"""
# Initializing attr... |
def _draw_cur_pytromino(self, color=None):
assert self._cur_pytromino.is_placed(), \
f'Current Pytromino not placed: {self._cur_pytromino}'
if not color:
color = self._cur_pytromino.get_color()
valid_blocks = self._cur_pytromino.filter_blocks_pos(
self._board... | This function handles holding a new pytronomino piece. It checks if the holder is open, then either stores the current piece and initializes a new one if the holder is empty, or validates and swaps the current piece with the stored one if possible. It updates the GUI display for the holder and ensures proper placement ... | def _hold_pytromino(self):
can_hold = self._holder.is_open()
if can_hold:
next_pytromino_t = self._holder.get_item()
if not next_pytromino_t: # holder is empty
# Reflect the change on holder display
self._gui.init_pytro_holder()
dis... |
def _init_new_pytromino(self):
if self._game_over: return
self._cur_pytromino = self._get_new_pytromino()
self._cur_pytromino.place_at(self._pytro_start_coord)
# Check if new piece can be placed, if not, game over
on_board_blocks = self._cur_pytromino.filter_blocks_pos(
... | The main task of the code is to manage a Tetris-like game loop, handling user input (movement, rotation, quitting), controlling falling piece speed, detecting collisions, freezing pieces when they can't descend further, checking for row clearances, updating score/level, and initializing new pieces. The loop runs until ... | def start_game(self):
cur_speed = self._start_speed
prev_time = self._pyg.time.get_ticks()
self._score = 0
self._game_over = False
self._level = 1
self._gui.init_window()
self._init_new_pytromino()
while not self._game_over:
for event in self.... |
def receive_message(self):
while True:
segment = self.receive()
if isinstance(segment, Message):
if segment.id != self.next_message_id:
print(f"[ORD] Received fragment out of order {segment.get_printable()}")
continue
... | This code processes incoming messages by handling text, file transfers, and control signals. For text, it accumulates content until confirmation. For files, it opens a file, receives fragments, and writes them. It sends appropriate responses (Ok, Accept) and closes connections on completion or errors. | def listen(self):
segment = self.receive_message()
if isinstance(segment, TextMessage):
text = ""
text += segment.text
while True:
response = self.send_message(NextMessage(self.id, self.next_message_id, []))
if isinstance(response, OkM... |
def paginate_by_year(self, **kwargs):
years = range(kwargs["start_year"], kwargs["end_year"], 1)
num_years = len(years)
year_pairs = [(years[i], years[i+1]) for i in range(0, num_years-1, 2)]
results_per_year = round(kwargs["sample_size"] / len(year_pairs))
for i, (start_year, en... | This function retrieves paper embeddings based on a query, using paginated or batched API requests depending on the sample size, and returns results filtered by specified years in a dictionary. | def paper_embeddings_search(self, query: str, sample_size: int,
start_year: int, end_year: int) -> dict:
results_dict = {}
if sample_size >= self.PAGINATED_LIMIT:
self.paginate_by_year(
endpoint=self.SEARCH_ENDPOINT,
query=quer... |
def create1PercentImage(self, inputRaster, value=1):
nominalSpatialRes = self.getNominalSpatialResolution()
onePerSpatRes = float(nominalSpatialRes) / 10
strOnePerSpatialRes = str(onePerSpatRes) + ' ' + str(onePerSpatRes)
temp1percentRasterPath = self.get1percentImagePath(value)
... | The main task of the code is to rasterize a given tile onto a downsampled (1%) reference image, sum the downsampled rasterized images across all classes, and combine the resulting rasterized data into a final output. The process involves creating a 1% version of the input image, applying rasterization to the tile on th... | def doRasterizeForTile(self, tile):
self.resultPath = self.workdir + '/trainingRaster_' + tile.name + '.tif'
self.currentReferenceTif = tile.exampleImage
print('create1PercentImage')
self.create1PercentImage(tile.exampleImage)
print('rasterizeTileOn1percentImage')
self.ra... |
def first_part():
a = []
b = []
c = []
try:
a = eval(input("Enter the numbers:"))
for x in a:
if x not in b:
b.append(x)
c = [x for x in b if x % 2 == 0]
print("List A equals ", a)
print("List B equals ", b)
print("List C equal... | The main task of the code is to execute three functions sequentially: first_part() initializes processing, second_part("temp.txt") counts words in the specified file, and third_part() handles post-processing. The script outputs the word count from the file, integrating file analysis with preprocessing and postprocessin... | def main():
first_part()
print("Number of words in the file :", second_part("temp.txt"))
third_part() |
def encode_by_index(self, entities: torch.LongTensor) -> torch.FloatTensor:
# take a node index and find its NodePiece hash
hashes, dists, ids = self.hashes[entities], self.distances[entities], self.total_paths[entities]
anc_embs = self.anchor_embeddings(hashes)
mask = None
i... | This function computes scores for triples (h, r, t) by calculating interactions between head (h), relation (r), and tail (t) embeddings. It retrieves embeddings for given h and r, ranks them against all possible tails (t), and computes scores using an interaction function. If subbatching is enabled, it processes in chu... | def score_t(self, hr_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102
# Get embeddings
h = self.encode_by_index(hr_batch[:, 0]).view(-1, 1, self.real_embedding_dim, 2)
r = self.relation_embeddings(hr_batch[:, 1]).view(-1, 1, self.real_embedding_dim, 2)
# Rank against all en... |
def encode_by_index(self, entities: torch.LongTensor) -> torch.FloatTensor:
# take a node index and find its NodePiece hash
hashes, dists, ids = self.hashes[entities], self.distances[entities], self.total_paths[entities]
anc_embs = self.anchor_embeddings(hashes)
mask = None
i... | This code computes scores for all entities in a batch by interacting relation and entity embeddings using an interaction function. It inverts relation embeddings, processes entities in subbatches for efficiency, and returns scores indicating compatibility between inverted relations and entities. | def score_h(self, rt_batch: torch.LongTensor) -> torch.FloatTensor: # noqa: D102
# Get embeddings
r = self.relation_embeddings(rt_batch[:, 0]).view(-1, 1, self.real_embedding_dim, 2)
t = self.encode_by_index(rt_batch[:, 1]).view(-1, 1, self.real_embedding_dim, 2)
r_inv = torch.stack([... |
def batch_and_slice(
self,
model: Model,
mapped_triples: MappedTriples,
additional_filter_triples: Union[None, MappedTriples, List[MappedTriples]] = None,
batch_size: Optional[int] = None,
device: Optional[torch.device] = None,
use_tqdm: bool = False,
rest... | The code evaluates a knowledge graph embedding model by computing metrics on given triples. It configures batch and slice sizes for memory optimization, uses provided or model-default triples, and executes the evaluation using `pykeen.evaluation.evaluate`. The function returns `MetricResults`, handling optional paramet... | def evaluate(
self,
model: Model,
mapped_triples: Optional[MappedTriples] = None,
additional_filter_triples: Union[None, MappedTriples, List[MappedTriples]] = None,
batch_size: Optional[int] = None,
slice_size: Optional[int] = None,
device: Optional[torch.device] ... |
def calculate_answer(result, prompt):
answers = []
equation_column = []
count = 0
if (prompt == 'arithcot'):
for i in range(len(result)):
response = result.response[i]
mapping = result.mapping[i]
equations = []
# Extract eqautions from respons... | The code evaluates the accuracy of model responses against ground-truth answers for different prompting strategies (e.g., arithcot, cot, varcot, pycot, sympy) on a dataset. It reads JSONL logs, processes responses using task-specific functions, computes accuracy by comparing predicted answers with actual answers, print... | def eval_result(filename, prompt, dataset_name):
result = pd.read_json("logs/" + filename + ".jsonl", lines=True)
if prompt == 'arithcot':
result['response_answer'], result['equations'] = calculate_answer(
result, "arithcot")
result['answer'] = [i[0] for i in result['answer']]
... |
def load_data():
"""
Load the datasets from specified paths.
:return DataFrames for activity, interaction, and health data.
"""
# Define data paths
DATA_ROOT = Path(__file__).parents[0] / "data"
PATH_TO_ACTIVITY_DATA = (DATA_ROOT / "activity_environment_data.csv").resolve()
PATH_TO_HEALT... | The main task of the code is to merge three datasets (activity, interaction, health) on user timestamps, generate mood descriptions in batches using a text generation model, and save the enriched data with descriptions to a CSV file. It processes data in 100-row batches, drops redundant columns, and applies the text ge... | def main():
"""
Main function to perform the data processing, text generation, and saving results.
"""
# Load data
activity, interaction, health = load_data()
# Merge datasets
combined_data = pd.merge(health, activity, on=['User_ID', 'Timestamp'], how='outer')
combined_data = pd.merge(c... |
def take_picture():
camera = PiCamera()
camera.resolution = (640, 360)
camera.rotation = 180
time.sleep(2)
camera.capture("/home/pi/cardstunt/test.jpg")
print("done.")
def resizeToWideScrn(img, col_ref, size, bdType, bgCol):
h, w = img.shape[:2]
th, tw = size
a = w / h
ta = tw / ... | The main task of the code is to capture a photo, adjust its color using a reference image, resize it to a specific dimension, save the processed image, and generate motor control data. The function performs image resizing, color correction, and outputs the result along with motor instructions in CSV format for further ... | def capture_photo():
# action
take_picture()
ref = cv.imread("/home/pi/cardstunt/color ref.png") # read color reference image
img = cv.imread("/home/pi/cardstunt/test.jpg") # read image / in case want to input file --> change filename here
result = resizeToWideScrn(img, ref, (105, 185), cv.BORDER_CO... |
def default_dir() -> str:
"""Get default data file directory"""
if sys.platform == "win32":
config_dir = os.path.join(os.environ["APPDATA"], "colinotes")
else:
config_dir = os.path.join(os.path.expanduser("~"), ".config", "colinotes")
return config_dir
def default_config() -> dict:
"... | The main task of the code is to read a configuration file (`config.json`) from a default directory, return its contents as a dictionary, and if the file is not found, generate a default configuration using `default_config()`, write it to the file, then return it. | def read_config() -> dict:
"""Get configuration from config file"""
config_file = os.path.join(default_dir(), "config.json")
try:
with open(config_file, "r") as f:
config = json.load(f)
except FileNotFoundError:
config = default_config()
write_config(config)
retu... |
def welcome():
"""
Prints a welcome message for the Hangman game along with the maximum number of tries allowed.
"""
print("Welcome to the game Hangman")
print(""" _ _
| | | |
| |__| | __ _ _ __ __ _ _ __ ___ ... | The main task of the code is to run a Hangman game. It starts by displaying a welcome message, prompts the user for a file path and index, retrieves a secret word from the specified file, and then initiates the Hangman game with that secret word. The code orchestrates the game flow by sequentially handling user input, ... | def main():
# Show open screen
welcome()
# Receive the file path and index, then and get the secret word
file_path, index = handle_initial_input()
secret_word = choose_word(file_path, index)
# Start the game
hangman(secret_word) |
def guess_letters(guess, wordle_word):
letter_list = []
for num in range(0, len(guess)):
if guess[num] in wordle_word:
if guess.count(guess[num]) <= wordle_word.count(guess[num]):
if guess[num] == wordle_word[num]:
letter_list.append("green")
... | The function `submit_guess` processes a user's word guess in a Wordle-like game. It validates the guess against a wordlist, updates the game state, and sends feedback ("win", "lose", or "not"). If valid, it increments attempts, triggers a timer, and ends the game upon winning or losing, updating UI elements like button... | def submit_guess(guess):
guess = ''.join(guess)
global game_over, tries, wordle, wordlist
if not game_over:
if guess in wordlist and tries < 7:
message_canvas.configure(width=200, height=10)
win = guess_letters(guess, wordle)
reset_timer()
if win:
... |
def generate_wordlist():
remove_list = ['slave', 'schwa', 'polio', 'didst', 'anode', 'lathe', 'dikes', 'bosom', 'imply', 'rotor', 'urine',
'nymph', 'asses', 'thine', 'sexes', 'daddy', 'emery', 'sunup', 'sloop', 'radii', 'booby', 'tepee',
'outdo', 'ketch', 'copra', 'tapir', 'flo... | The play() function initializes or restarts a Wordle game by generating a wordlist if empty, selecting a target word (wordle) if not already chosen, and starting a timer, all under the condition that the game is not yet over. It manages game state variables globally to prepare for player guesses. | def play():
global game_over, wordlist, wordle, letters_of_guess, tries
if not game_over:
if not wordlist:
wordlist = generate_wordlist()
if not wordle:
wordle = pick_word(wordlist)
start_timer() |
def xor(*args):
"""Return the xor of an arbitrary number of bitstrings of the same
length as another bitstring of the same length.
EXAMPLE: xor("01", "11", "10") -> "00"
"""
if args == []:
raise ValueError("at least one argument needed")
result = args[0]
for arg in args[1:]:
... | The function applies a cryptographic round transformation to a 128-bit bitstring 'BHati' using subkey KHat[i]. It XORs BHati with the subkey, applies the SHat function, then either transforms the result with LT (for rounds 0–Rounds-2) or XORs it with the final subkey (for the last round). The output is the transformed ... | def R(i, BHati, KHat):
"""Apply round 'i' to the 128-bit bitstring 'BHati', returning another
128-bit bitstring (conceptually BHatiPlus1). Do this using the
appropriately numbered subkey(s) from the 'KHat' list of 33 128-bit
bitstrings."""
# print("BHati", BHati, "(i=%2d) BHati" % i)
xored = x... |
def makeSubkeys(userKey):
"""Given the 256-bit bitstring 'userKey' (shown as K in the paper, but
we can't use that name because of a collision with K[i] used later for
something else), return two lists (conceptually K and KHat) of 33
128-bit bitstrings each."""
# Because in Python I can'... | The function `encrypt` encrypts a 128-bit plaintext using a 256-bit user key via a cryptographic algorithm. It generates subkeys from the user key, applies an initial permutation (IP) to the plaintext, iterates through multiple rounds of transformation using the subkeys, and finalizes with a permutation (FP) to produce... | def encrypt(plainText, userKey):
"""Encrypt the 128-bit bitstring 'plainText' with the 256-bit bitstring
'userKey', using the normal algorithm, and return a 128-bit ciphertext
bitstring."""
# print("fnTitle", "encrypt", None, "tu")
# print("plainText", plainText, "plainText")
# print("userKey",... |
def load_image_pixels(cv_image, shape):
# load the image to get its shape
#image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
#image = Image.fromarray(cv_image)
width, height, channel = cv_image.shape
# load the image with the required size
#image = image.resize(shape)
# convert to numpy array
#image = img_to_ar... | The code processes incoming image data using YOLOv3 for real-time object detection, identifying "Human" and "Vehicle" classes. It resizes images, runs predictions, decodes bounding boxes, applies NMS, and publishes detected object coordinates and labels. The task involves detecting and tracking objects in a video strea... | def callback(data):
global count
global model
global sess1
global graph1
if count%4==0:
bridge = CvBridge()
cv_image = bridge.imgmsg_to_cv2(data,desired_encoding='bgr8')
shape = cv_image.shape
cv_image = cv2.resize(cv_image,(416,416))
# load yolov3 model
# define the expected input shape for the mod... |
def _unpack_payload(payload: Union[bytes, bytearray],
fmt: str
) -> Iterable[Union[bytes, int, float]]:
"""
Unpack the payload, and validate the CRC32 checksum
"""
try:
unpacked = struct.unpack(fmt, payload)
except struct.error as e:
logging.er... | This function redirects an MQTT message to a Node-RED topic by processing its topic and payload according to configuration. It removes prefixes from the original topic, unpacks the payload using field definitions from the config, validates the data, and publishes the structured JSON payload to the corresponding Node-RE... | def _redirect_red(self, msg: mqtt.MQTTMessage) -> None:
"""
Redirect a message from a device to the appropriate Node-RED topic
"""
logging.info('Redirecting to red')
topic = msg.topic.removeprefix('/redmw').removeprefix('/')
fields = [_config_entry(x) for x in self.conf... |
def _build_pack_fmt(*entries: _config_entry) -> str:
return ''.join(_fmt(x['kind']) for x in entries)
def _build_topic(*parts: str) -> str:
"""
Build the topic that will be used as the Node-RED endpoint
"""
def _prepend_slash(x):
if not x.startswith('/'):
return '/' + x
... | This function redirects an MQTT message from Node-RED to a specific device topic by parsing the payload, extracting configured data fields, packing them into a binary format, optionally adding a CRC checksum, and publishing the result to the device's designated topic. | def _redirect_device(self, msg: mqtt.MQTTMessage) -> None:
"""
Redirect a message from the Node-RED instance to the appropriate device
topic
"""
logging.info('Redirecting to device')
data = json.loads(msg.payload)
topic = msg.topic.removeprefix('/devicemw').remov... |
def _redirect_device(self, msg: mqtt.MQTTMessage) -> None:
"""
Redirect a message from the Node-RED instance to the appropriate device
topic
"""
logging.info('Redirecting to device')
data = json.loads(msg.payload)
topic = msg.topic.removeprefix('/devicemw').remov... | The main task of the code is to handle incoming MQTT messages by logging them and routing them to specific processing functions based on their topic prefixes. It checks the message topic and directs it to methods like _redirect_device, _redirect_red, _remote_log, or logs formatted JSON for '/red' topics. Invalid topics... | def _on_message(self, client: mqtt.Client, usrdata: Any, msg: mqtt.MQTTMessage) -> None:
logging.info(f'Message recieved: {str(msg.payload)}')
if msg.topic.startswith('/devicemw'):
self._redirect_device(msg)
elif msg.topic.startswith('/redmw'):
self._redirect_red(msg)
... |
def initialize():
args = parse_args()
params = {}
# Set up training using either GPU or CPU
gpu_id = 0
device = torch.device('cuda:{0:d}'.format(gpu_id) if torch.cuda.is_available() else "cpu")
print('Using device:', device)
print()
if device.type == 'cuda' and args.verbose:
p... | The main task of the code is to train and evaluate a meta-learning model (PLATIPUS) on datasets like 'sine_line' or 'drp_chem', with options for cross-validation, custom loss weighting, and comparison to MAML. It initializes parameters, trains models per amine (for 'drp_chem'), adjusts loss functions based on class dis... | def main():
# Do the massive initialization and get back a dictionary instead of using
# global variables
params = initialize()
if params['train_flag']:
if params['datasource'] == 'sine_line':
meta_train(params)
elif params['datasource'] == 'drp_chem':
if param... |
def create_configmap():
i = random.randint(0, 99)
cm = client.V1ConfigMap(
metadata=client.V1ObjectMeta(
name=f"test-{i:02}"))
configmaps[i] = create_or_get_configmap(cm)
def update_configmap():
if not configmaps:
return
i = random.choice(list(configmaps.keys()))
... | The code interacts with a Kubernetes cluster to perform random operations (create, update, delete, list) on configmaps within a specified namespace over a defined number of rounds, handling namespace creation and API exceptions. | def main(rounds, *args, **kwargs):
global v1
try:
config.load_kube_config()
version = client.VersionApi().get_code()
logging.info(f"Connected to {Configuration._default.host} - {version.git_version}")
except Exception as e:
logging.error(f"Kubernetes version check failed: {e... |
def validate_keywords(self, document):
"""
Args: original text data, spaCy nlp, trained ner model
Returns: returns list of entities and ngram entities validated against skills list
"""
validated = []
validated.append(self.termValidator(document))
return [list(Orde... | The code's main task is to extract and validate keywords and phrases from a document, then filter out non-keyword elements to return a refined list of relevant terms. | def extractTerms(self, document):
keywords = self.validate_keywords(document)
phrases = self.validate_phrases(document)
return self.removeNonKeywords(keywords, phrases) |
def extractTerms(self, document):
keywords = self.validate_keywords(document)
phrases = self.validate_phrases(document)
return self.removeNonKeywords(keywords, phrases)
def termDictionary(self):
"""
For demo purposes only
"""
before = """\n<mark class="entity" sty... | The main task of the code is to process input text by extracting terms, generating a term dictionary, and replacing all instances of these terms in the lowercased text using the dictionary for substitution. | def displayTerms(self, text):
extracted_terms = self.extractTerms(text)
dictionary = self.termDictionary()
return self.replaceAll(text.lower(), dictionary) |
def opposite(direction):
switcher = {
RIGHT: LEFT,
LEFT: RIGHT,
UP: DOWN,
DOWN: UP
}
return switcher.get(direction,0)
def closeEdge(self,x,y,e):
if safeLen(e.squares) < 2:
return None
n = self.getNode(x, y)
e.end = n
e.start.edges[e... | This function processes a grid square to manage edge creation/closure. If the square is unoccupied (0) and an edge exists, it closes the edge by linking to the opposite direction's node. If occupied, it either opens a new edge or adds the square to an existing edge's list, ensuring connectivity in a grid-based structur... | def processSquare(self,x,y,d,e):
if self.squares[x][y] == 0:
if e is not None:
# create a node for the previous square and close the edge
ex,ey = Node(id,x,y).peek(opposite(d))
e = self.closeEdge(ex, ey, e)
else:
if e is None:
... |
def getRoot(graph):
if graph is None or len(graph.keys()) < 1:
return None
rootId = min(graph.keys())
root = graph.get(rootId, None)
return root
def isSolvable(root,squares,graph):
# If graph is empty, we are done
if safeLen(squares) == 0:
#log("Graph is empty")
#log("Sol... | The code solves a puzzle by checking if a path exists through a graph built from a level file. It initializes parameters, constructs the graph, verifies solvability, and traverses the graph up to 25 steps to find a solution path. The result includes the filename, processing time, and the path if solvable. | def start(filename):
MAX_STEPS = 25
started = time.process_time()
path = []
level = Level(filename)
graph = level.buildGraph()
squares = level.getSquares()
root = getRoot(graph)
if isSolvable(root,deepcopy(squares),deepcopy(graph)) is False:
path = None
else:
path = t... |
def swap(x,y,d):
if d == LEFT or d == RIGHT:
return x,y
else:
return y,x
def processSquare(self,x,y,d,e):
if self.squares[x][y] == 0:
if e is not None:
# create a node for the previous square and close the edge
ex,ey = Node(id,x,y).peek(opposit... | This code constructs a graph representation of a grid by iterating through predefined directional dimensions (RIGHT, LEFT, DOWN, UP). It processes each square in the grid, swaps coordinates based on direction, and connects nodes via edges. The graph is built by iterating over coordinate ranges for each direction, then ... | def buildGraph(self):
self.graph = dict()
#self.nodes = dict()
self.edges = dict()
# for i in range(10, -6, -2):
# for i in reversed(range(5)):
dimensions = {
RIGHT: [0,self.height,1,0,self.width,1],
LEFT: [0,self.height,1,self.width-1,-1,-1],
... |
def render_syslog_header(self):
# Workaround for mac systems (https://bugs.python.org/issue35164)
# To set hostname use: sudo scutil --set HostName `hostname`
try:
hostname = socket.getfqdn()
except socket.gaierror:
hostname = 'localhost'
header = ''
... | The code's main task is to concatenate three rendered components—syslog header, base header, and extensions—into a single output string. It calls three methods to generate these parts and combines them sequentially, likely to construct a structured log message or data format. | def render(self):
syslog_header = self.render_syslog_header()
base_header = self.render_base_header()
extensions = self.render_extensions()
return syslog_header + base_header + extensions |
def get_gh_repos_for_orgs(self):
for org in self.config['github_orgs']:
# See: https://pygithub.readthedocs.io/en/latest/github.html#github.MainClass.Github.search_repositories
for repo in self.gh.search_repositories(query=f'org:{org}'):
self.repo_ids_to_full_names[repo.i... | The code processes ZenHub release issues by fetching repository data, extracting issue details, and writing them to CSV files. It loads configurations, retrieves GitHub repos, identifies release IDs, maps labels to teams, and writes issue and relationship data. The script filters and outputs only epic sub-issues linked... | def run(self):
with open(sys.argv[1], 'r') as config_file, \
open(sys.argv[5], 'w', newline='') as issue_file, \
open(sys.argv[6], 'w', newline='') as rel_file:
self.config = yaml.load(config_file, Loader=yaml.FullLoader)
self.get_gh_repos_for_orgs()
... |
def create_dataframes_from_csv(csv_path: Union[Path, str], last_finished_season: str) \
-> Sequence[pandas.DataFrame]:
"""
:param csv_path:
:param last_finished_season:
:return:
"""
stats_per_year_ordered = sorted(Path(csv_path).glob('*.csv'),
key=la... | The main task of the code is to preprocess NHL player statistics to generate prediction features for a machine learning model. It loads historical season data, identifies comparable players across recent seasons, constructs feature datasets using aggregated statistics, and serializes the resulting prediction features i... | def main():
import pickle
stats_path = Path('D:/Repositories/nhl-statistics/statistics')
yearly_stats = create_dataframes_from_csv(stats_path, '2020-2021')
seasons_names_ordered = sorted([x["Season"][0] for x in yearly_stats],
key=lambda x: int(x.split('-')[0]))
... |
def generate_prior_and_conditional_countings(self):
print("\nGENERATING countings for prior/conditional distributions...")
print("-------------------------------------------------------------")
for pd in self.bn.bn["structure"]:
print(str(pd))
p = pd.replace('(', ' ')
... | The main task of the code is to initialize a Naive Bayes classifier by reading a Bayesian network configuration file, loading training data, computing prior and conditional probability counts, generating probability distributions, and writing the resulting conditional probability tables (CPTs) back to the configuration... | def __init__(self, configfile_name, datafile_name):
self.configfile_name = configfile_name
self.bn = BayesNetReader(configfile_name)
self.nbc = NB_Classifier(None)
self.nbc.read_data(datafile_name)
self.generate_prior_and_conditional_countings()
self.generate_probabilitie... |
def read_data(self, data_file):
print("\nREADING data file %s..." % (data_file))
print("---------------------------------------")
self.rand_vars = []
self.rv_key_values = {}
self.rv_all_values = []
with open(data_file) as csv_file:
for line in csv_file:
... | The code initializes an object by reading data from a file. If no pre-fitted model is provided, it estimates probabilities from the data. Otherwise, it adopts the model's parameters and validates the learned probabilities. The main tasks are data loading, probability estimation (or reuse), and validation of probabilist... | def __init__(self, file_name, fitted_model=None):
self.read_data(file_name)
if fitted_model is None:
self.estimate_probabilities()
else:
self.rv_key_values = fitted_model.rv_key_values
self.probabilities = fitted_model.probabilities
self.test_learn... |
def get_page(self, content, quiz_name):
code_runners = content.find_all("div", {"class": "coderunner"})
for div in code_runners:
content = div.find('div', {"class": "content"})
info = div.find('div', {"class": "info"})
question_number = info.find('h3').find('span').te... | The main task of the code is to recursively retrieve and process all pages of a quiz. It parses the current HTML page, extracts and processes quiz data, checks for subsequent pages, and navigates to them if available, repeating the process until all pages are handled. | def get_pages(self, quiz_name):
page = self.br.response().read()
soup = BeautifulSoup(page, features='html5lib')
self.get_page(soup, quiz_name)
next_page = self.has_next_page(soup)
if next_page != '-1':
self.go_to_page(next_page)
self.get_pages(quiz_name) |
def get_quiz_url(self, id):
return self.quiz_url.format(id)
def get_quiz_name(self):
page = self.br.response().read()
soup = BeautifulSoup(page, features='html5lib')
name = soup.find('div', {"role": "main"}).find('h2').text
if not os.path.exists(name):
os.mkdir(name)
... | The main task of the code is to retrieve a quiz from a Moodle platform by opening a quiz URL, handling potential HTTP errors, extracting the quiz name, submitting a form, navigating to the initial page if needed, and fetching the quiz's pages for further processing. | def get_quiz(self, id):
try:
self.br.open(self.get_quiz_url(id))
except mechanize.HTTPError as e:
raise MoodleScrapperQuizNotFoundException
quiz_name = self.get_quiz_name()
print('Getting Quiz {}'.format(quiz_name))
self.br.select_form(nr=0)
self.b... |
def read(file):
list_of_rows_from_file = []
if os.stat(file).st_size == 0:
# print("File Contents is empty")
exit("File Contents is empty")
with open(file, "r") as content:
for line in content:
rows = []
i = line.strip()
... | This method processes three input files by reading and formatting their data, sorting arrays, calculating credit points, GPA, and compulsion enrollment, then generating a final student report object containing these results. | def read_level_4_files(self, file1, file2, file3):
self.file1_data = self.read(file1)
self.file2_data = self.read(file2)
self.file3_data = self.read(file3)
a = self.format_array(self.file1_data)
self.b = self.format_array(self.file2_data)
c = self.format_array(self.file3... |
def reformat_data(self, score_data):
formatted_array = []
# print(score_data)
for i in score_data[1:]:
x = []
for j in i:
x.append(j.split()[0])
for k in j.split()[1:]:
if k.isnumeric() and (0 <= int(k) <= 100):
... | The main task of the code is to read and process data from three input files. It reads `file1`, reformats its data using `reformat_data`, reads `file2` and `file3` as-is, stores them in instance variables, and then creates a student object. This prepares structured data for further processing or analysis. | def read_level_3_files(self, file1, file2, file3):
self.file1_data = self.reformat_data(self.read(file1))
self.file2_data = (self.read(file2))
self.file3_data = (self.read(file3))
self.create_student_object() |
def get_pubkey(key):
ecdsa_digest = ecdsa_secp256k1(key.digest).to_string()
x_coord = ecdsa_digest[:int(len(ecdsa_digest) / 2)]
y_coord = ecdsa_digest[int(len(ecdsa_digest) / 2):]
if int(binascii.hexlify(y_coord), 16) % 2 == 0:
p = PREFIX_EVEN + x_coord
else:
p = PREFIX_ODD + x_coord... | The code generates a Bech32 address from a cryptographic key. It retrieves the public key, computes its hash160 digest (20 bytes), and encodes it using BECH32_PREFIX and WITNESS_VERSION. The function returns the encoded Bech32 string and the public key bytes. | def get_bech32(key):
p, pubkeyc = get_pubkey(key)
redeem_script_P2WPKH = hash160(p).digest() # 20 bytes
return str(encode(BECH32_PREFIX, WITNESS_VERSION, redeem_script_P2WPKH)), pubkeyc |
def header() -> None:
print(colored("Hello World ! Welcome to MRT Assitance !", attrs=["bold", "underline"]))
def get_user_command() -> str:
command_table()
print("Press", colored("'q'", "red", attrs=["bold", "blink"]) ,"for exit the program")
command_number = input("Enter the command number you want to... | The main task of the code is to execute a loop that repeatedly retrieves and processes user commands. It starts by displaying a header, obtains an initial command, and enters a loop where it maps the command number to a corresponding function, executes it, and fetches the next command. The loop continues until the user... | def main():
header()
command_number = get_user_command()
is_continue = True
while is_continue:
function_name = get_command_name(command_number)
function_name()
command_number = next_command() |
def command_mrt_station_and_number_table() -> None:
table = Table(title="Table of Avilable Commands")
columns = ["Station Number", "MRT Station Name"]
rows = []
for number, mrt_station_name in MRT_STATIONS.items():
rows.append([str(number), mrt_station_name])
for column in columns:
... | This function processes an MRT payment by retrieving user input for card details and stations, converting station names to numbers, calculating fare, applying age-based discounts, and updating the card balance. It handles errors like invalid cards or stations, displaying success messages or errors with colored text. | def process_payment_command() -> str | None:
command_mrt_station_and_number_table()
card_number = input("Card Number: ").strip()
start_station = input("Start Station Name/Number: ").strip()
destination_station = input("Destination Station Name/Number: ").strip()
try:
start_number = convert... |
def command_mrt_station_and_number_table() -> None:
table = Table(title="Table of Avilable Commands")
columns = ["Station Number", "MRT Station Name"]
rows = []
for number, mrt_station_name in MRT_STATIONS.items():
rows.append([str(number), mrt_station_name])
for column in columns:
... | This function calculates the fare between two MRT stations based on user input. It prompts for start and destination stations, converts names to station numbers, computes the fare using a predefined rate, and displays the result in green or errors in red. | def mrt_calculator_command() -> None:
print(colored("\nCheck Fare Rate", "blue", attrs=["bold"]))
command_mrt_station_and_number_table()
start_station = input("Start Station Name/Number: ").strip()
destination_station = input("Destination Station Name/Number: ").strip()
try:
start_number = ... |
def deleteLayout(self, layout):
if layout is not None:
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
else:
self.deleteLayout(item... | The code creates a UI overview tab with user profile data, activity metrics, sleep analysis, and body stats, using QWidgets. It sets up two tabs: "Daily Overview" (static user info) and "Timeline View" (interactive date picker with buttons). The dateedit triggers data updates via `method()`, and buttons control dynamic... | def overview(self,tables):
self.ui.label_11.setText("OVERVIEW")
self.deleteLayout(self.ui.frame_8.layout())
#set the tabs
self.tabWidget = QTabWidget(self.ui.frame_8)
self.tabWidget.setEnabled(True)
self.tabWidget.setStyleSheet(u"color: rgb(0, 0, 0);")
self.tab =... |
def activities(self,table_name):
self.ui.label_11.setText("ACTIVITIES")
self.deleteLayout(self.ui.frame_8.layout())
#set the tabs
self.tabWidget = QTabWidget(self.ui.frame_8)
self.tabWidget.setObjectName(u"tabWidget")
self.tabWidget.setEnabled(True)
self.tabWidge... | This code defines a method `assign_handle` that routes input data to specific processing functions based on the `text` parameter. It prints the input text, then calls corresponding methods like `activities`, `body`, `sleep`, etc., passing `table_name` as an argument. The `Overview` case uses `all_tables_case` instead. ... | def assign_handle(self, text,table_name,all_tables_case):
print(text)
if text == "activities":
self.activities(table_name)
if text == "body":
self.body(table_name)
if text == "sleep":
self.sleep(table_name)
if text == "foods":
self.... |
def _parse_subfigure(self):
"""Parse the code for specific commands"""
commands = "caption", "label", "includegraphics", "plotone", "\\fig"
info = {}
# careful with subfigure...
found = []
for match in re.compile(r"subfigure.*").finditer(self._code):
start, en... | This function parses LaTeX code to extract specific commands like 'caption', 'label', 'includegraphics', etc., handling multiple instances and special cases like 'subfigure'. It returns a dictionary with parsed information for each command, using different parsing methods based on occurrence counts and command types. | def _parse(self):
"""Parse the code for specific commands"""
commands = "caption", "label", "includegraphics", "plotone", "\\fig"
info = {}
# makes sure multiple includegraphics on the same line do work
try:
# careful with subfigure...
if "subfigure" in se... |
def getSplitData(self, matrices={'content':[1, []], 'stylistic':[3, []]}, testSize=0.3):
# Get split data from self.data with testSize
X_train, X_test, Y_train, Y_test = self.data.getRandomSplitData(testSize)
# Declare variable for content train and test matrices
cmTr, cmTe = None, None... | The code identifies the top k features using chi2 selection from content and stylistic matrices, maps them to original identifiers, trains an SVM with a linear kernel on transformed data, evaluates performance metrics, and returns the selected features along with results. It handles n-gram features, distinguishes betwe... | def runKBestFeatures(self, k, contentMatrix=True, contentMatrixFeatures=[], wordN=1,\
stylisticMatrix=True, stylisticMatrixFeatures=[],charN=3, testSize=.3):
m = {} # Dictionary to pass information to getSplitData
# If content matrix, build appropriate data
if contentMatrix:
... |
def c_vir(self):
# Concentration parameter for halo of a given virial mass
# taken from Klypin 2011 on Bolshoi simulations, equation 10
a = self.Mvir*self.h/ 1e12
return 9.60*(a)**(-0.075)
def r_s(self, c=False):
# Scale length for the NFW profile (in kpc)
if c:
... | The function calculates the mass enclosed within a given Galactocentric distance $ r $ using the Navarro-Frenk-White (NFW) dark matter halo profile. It uses either a provided concentration parameter $ c $ or computes it via $ self.c\_vir() $. The enclosed mass is derived by normalizing the cumulative mass function $ f(... | def mass(self, r, c=False):
"""NFW mass enclosed as a function of r
Input: r = Galactocentric distance (kpc)
c = concentration - Can take concentration as given (cvir) or give it a value
"""
if c:
cvir = c
else:
cvir = self.c_vir()
... |
def c_vir(self):
# Concentration parameter for halo of a given virial mass
# taken from Klypin 2011 on Bolshoi simulations, equation 10
a = self.Mvir*self.h/ 1e12
return 9.60*(a)**(-0.075)
def r_s(self, c=False):
# Scale length for the NFW profile (in kpc)
if c:
... | This function calculates the NFW (Navarro-Frenk-White) dark matter density profile at a given Galactocentric radius `r`. It uses either a provided concentration parameter `c` or computes it via `self.c_vir()`. The density `rho_N` is derived from the virial mass `Mvir`, scale radius `r_s`, and the concentration-dependen... | def rho(self,r, c=False):
"""NFW density profile as a function of r
Input: r = Galactocentric distance (kpc)
c = concentration - Can take concentration as given (cvir) or give it a value
"""
if c:
cvir = c
else:
cvir = self.c_vir()
x = r/se... |
def write_test(self):
book = load_workbook(self.file_path)
book.save(self.file_path)
def process_data(self):
date_string = f'{self.year_line_edit.text()}-{self.month_line_edit.text()}-{self.day_line_edit.text()}'
from_string = f'{self.year_range_end.text()}-{self.month_range_end.text()}-... | (The code retrieves a file path from a UI input, attempts to open/access the file, processes API data into a dictionary, writes the processed data to the file, and handles errors like file not found or permission issues. It logs errors, updates the UI, and resets the data dictionary for subsequent runs if the program r... | def run(self):
# get the file path
self.file_path = self.path_line_edit.text()
# test if file open or exists
try:
self.write_test()
# pull API data
try:
self.process_data()
self.write_data(self.dates_to_prices)
... |
def add(self, input):
my_dict = {46: None, 63: None}
ticker = input.translate(my_dict)
if ticker and not ticker.isspace():
url = f'https://api.marketdata.app/v1/stocks/quotes/{ticker}/?token={cfg.KEY}'
response = request("GET", url)
# check API for ticker data... | This code initializes a GUI application for tracking stock tickers, loading a UI layout, configuring active/inactive ticker lists, connecting buttons to functions for adding/deleting/toggling tickers, managing date ranges, file paths, and triggering actions like running processes or opening files. It sets up signal-slo... | def __init__(self):
super(MyGui, self).__init__()
uic.loadUi('tt.ui', self)
self.show()
self.setWindowTitle('Ticker Track')
self.active_list.addItems(cfg.ACTIVE_TICKERS[:])
self.inactive_list.addItems(cfg.INACTIVE_TICKERS[:])
self.path_line_edit.setText(cfg.BOOK_N... |
def player_hit(self, window, buttonNext, buttonHit, buttonStand, playerFrame):
# get the player from the game
player = self.game.get_player()
# player hits from the game deck
player.hit(self.game.get_deck())
# check if the player's total is greater than 21
if player.get... | This code creates a graphical user interface (GUI) for a Blackjack game using Tkinter. It sets up a window displaying the player's bank balance, their hand, the dealer's visible card, and action buttons (Hit/Stand). If the dealer's turn is active, a "Next" button is added to control game flow. The window includes prope... | def create_game_window(self, dealer=False):
gameWindow = tk.Tk()
gameWindow.title("Black Jack")
gameWindow.geometry("400x700+500+20")
gameWindow.configure(bg=BGCOLOR)
# label showing how much money you have in the bank
bankLabelText = f"You have ${self.game.get_player()... |
def get_prodid(pickle_file):
with open(pickle_file, 'rb') as f:
info = pickle.load(f)
proid = info['properties']['PRODUCT_ID']
## invalid
if proid.find('OPER') > -1:
return None
return proid
def get_obsgeo_from_MTD_TL(MTD_TL_XML):
'''
extract project and transform from MTD_T... | The main task of the code is to retrieve and process Sentinel-2 satellite data by querying BigQuery for product metadata, downloading the corresponding MTD_TL.xml file via gsutil, extracting geolocation and angular data from the XML, interpolating it to a 60m resolution, and returning solar and view zenith angles, rela... | def get_obsgeo(pickle_file):
try:
client = bigquery.Client()
except Exception as e:
from google.cloud import bigquery
client = bigquery.Client()
mtd_tl_xml_file = pickle_file.replace('_info.pickle', '_MTD_TL.xml')
if not os.path.exists(mtd_tl_xml_file):
proid = get_prodi... |
def formulate_query(qns):
qns_head = qns.split()[0]
ner_gpe = get_continuous_chunks(qns, "GPE")
ner_person = get_continuous_chunks(qns, "PERSON")
ner_org = get_continuous_chunks(qns, "ORGANIZATION")
ans_type = classify_qns(qns)
return [[qns_head], ner_gpe, ner_person, ner_org, ans_type]
def comp... | The code answers a question by analyzing the query to extract keywords, answer type, and structure. It splits the context into sentences, computes similarity between sentences and the query, retrieves top 3 relevant sentences, evaluates candidate answers using two methods, selects the best answer, and generates a struc... | def answer_question(context, qns):
# context = str(context.read())
sentences = context.split(".")
#qns analysis
query = formulate_query(qns)
qns_head = query[0]
query_keywords = query[1] + query[2] + query[3]
query_ans_type = query[4]
# print(query_ans_type)
# Remove trailing \... |
def max_size(list):
size=0
for i in list:
image = Image.open(i)
size+=image.size[0]*image.size[1]
image.close()
return size
def zip_to_bytestring(path):
tst=""
with open(path, "rb") as f:
bytes = f.read()
tst="".join(["{:08b}".format(x) for x in bytes])
return tst
def saf... | The code encrypts a message using ChaCha20 with a SHA-256 hashed key and a randomly generated nonce, splitting the message into parts embedded into PNG images from an input folder. Each modified image is saved to a destination folder with metadata containing the nonce and order index, enabling decryption by reconstruct... | def fog(key,message,image_bank,destination_folder):
print("Starting encryption...\n")
# Retrieve all images
img_list=glob.glob(image_bank+'/*.png')
print("Image list : ")
print(img_list)
print()
# Encode key with SHA-256
m = hashlib.sha256()
m.update(key.encode('utf-8'))
seed = m.digest(... |
def safe_randrange(nb,size,cipher):
zerobuf = bytes([0x00]) * 5
array = []
for i in range(size):
print("Number "+str(i)+"/"+str(size))
elem = sample(nb,cipher,zerobuf)
array.append(elem)
return array
def extract_message(image_file,size,cipher):
message = ""
image =Image.ope... | The code decrypts data from multiple fogged PNG images using ChaCha20 encryption. It hashes the input key with SHA-256, retrieves a nonce from image metadata, and decrypts message fragments stored across the images. The decrypted content is reassembled and output as a ZIP file. The process uses image order metadata and... | def wind(key,size,directory):
print("Starting decryption...")
# Retrieve all images
img_list=glob.glob(directory+'/*.png-fog')
print("Image list : ")
print(img_list)
print()
print(size)
# Encode key with SHA-256
m = hashlib.sha256()
m.update(key.encode('utf-8'))
seed = m.digest()
... |
def safe_randrange(nb,size,cipher):
zerobuf = bytes([0x00]) * 5
array = []
for i in range(size):
print("Number "+str(i)+"/"+str(size))
elem = sample(nb,cipher,zerobuf)
array.append(elem)
return array
def extract_message(image_file,size,cipher):
message = ""
image =Image.ope... | The code decrypts encrypted data stored across multiple PNG images using a ChaCha20 cipher. It hashes the key with SHA-256, retrieves a nonce from image metadata, decrypts message fragments from ordered images, and reassembles them into a byte stream. Finally, it converts the decrypted bytes into a ZIP file. The proces... | def wind(key,size,directory):
print("Starting decryption...")
# Retrieve all images
img_list=glob.glob(directory+'/*.png')
print("Image list : ")
print(img_list)
print()
print(size)
# Encode key with SHA-256
m = hashlib.sha256()
m.update(key.encode('utf-8'))
seed = m.digest()
pr... |
def the_shuffle(img,key):
dimX,dimY = img.size
length = dimX*dimY
array = []
for i in range(length):
array.append(i)
safe_shuffle(key,array)
print(array[0])
return array
def vers_8bit(c):
chaine_binaire = bin(ord(c))[2:]
return "0"*(8-len(chaine_binaire))+chaine_binaire
def modifier_pixel(... | The function 'hide' embeds a message into an image by converting it to binary, shuffling the image's pixels using a key, and placing each bit into the shuffled pixels in sequence. It adds metadata with the 'order' parameter and returns the modified image along with the metadata for later retrieval. | def hide(image_file,message,order,key):
image = Image.open(image_file)
dimX,dimY = image.size
array = the_shuffle(image,key)
im = image.load()
message_binaire = ''.join([vers_8bit(c) for c in message])
metadata = PngInfo()
metadata.add_text("Order", str(order))
i=0
for bit in message_binaire:... |
def split_msg(msg,key,nb):
image_nb = [random.randrange(0,nb) for i in range(len(msg))]
return image_nb
def smallf(x,arr,msg):
string =""
for i in range(len(arr)):
if arr[i] == x:
string+=msg[i]
return string
def hide(image_file,message,order,key):
image = Image.open(image_file)
dimX... | The main task of the code is to split a message using a key and embed each segment into corresponding images from an image bank. It uses randomness seeded by the key to process images, hiding non-empty message parts within them and saving modified images with updated paths. Empty segments result in original images bein... | def fog(key,message,image_bank):
random.seed(key)
img_list=glob.glob(image_bank+'/*.png')
image_nb = split_msg(message,key,len(img_list))
splitted_msg =[]
for i in range(len(img_list)):
splitted_msg.append(smallf(i,image_nb,message))
for idx,i in enumerate(img_list):
if splitted_msg[idx] !... |
def getElementByTagNameNR(elem, tagName):
children = elem.childNodes
for child in children:
if child.nodeType == child.ELEMENT_NODE and child.tagName == tagName:
return child
return None
def getElementsByTagNameNR(elem, tagName):
elements = []
children = elem.childNodes
for c... | The code parses an XML file to extract item, category, seller, and bid data. It writes item and category details, tracks unique sellers, and processes bids to record bidder information. Sellers and bidders are checked against lists/dictionaries to avoid duplicates, with new entries added and their data stored. The goal... | def parseXml(f):
dom = parse(f) # creates a dom object for the supplied xml file
document = getElementByTagNameNR(dom, 'Items')
item_list = getElementsByTagNameNR(document, 'Item')
for item in item_list:
writeItem(item)
writeCategories(item)
seller = item.getElementsByTagName(... |
def isXml(f):
return len(f) > 4 and f[-4:] == '.xml'
def parseXml(f):
dom = parse(f) # creates a dom object for the supplied xml file
document = getElementByTagNameNR(dom, 'Items')
item_list = getElementsByTagNameNR(document, 'Item')
for item in item_list:
writeItem(item)
writeCate... | The main task of the code is to parse XML files provided as command-line arguments, process each file to extract data, and write user tuples for bidder IDs that are not also seller IDs. It validates input, iterates through files, executes parsing, and ensures all output files are closed after processing. | def main(argv):
if len(argv) < 2:
print >> sys.stderr, 'Usage: python super_xml_parser.py <path to xml files>'
sys.exit(1)
# loops over all .xml files in the argument
for f in argv[1:]:
if isXml(f):
parseXml(f)
print ("Success parsing " + f)
# after all i... |
def bfs_search(initial_state):
"""BFS search"""
### STUDENT CODE GOES HERE ###
nodes_exp = set()
frontier = deque()
frontier.append(initial_state)
goal_state = None
in_que = set()
in_que.add(initial_state)
max_dep = 0
start_time = time.time()
while len(frontier) != 0:
... | The code's main task is to solve a puzzle (e.g., 8-puzzle) using a specified search algorithm (BFS, DFS, or A*). It reads input parameters: the search method and initial state. The initial state is parsed into a tuple, and the puzzle size is determined. Depending on the chosen method, it executes the corresponding sear... | def main():
sm = sys.argv[1].lower()
begin_state = sys.argv[2].split(",")
begin_state = tuple(map(int, begin_state))
size = int(math.sqrt(len(begin_state)))
hard_state = PuzzleState(begin_state, size)
res = None
if sm == "bfs":
res = bfs_search(hard_state)
elif sm == "dfs... |
def get_driver(self):
driver = getattr(self.threadLocal, 'driver', None)
if driver is None:
driver = self.configure_driver()
setattr(threadLocal, 'driver', driver)
return driver
def get_tag(self, selector, by=By.CSS_SELECTOR, all=False):
try: # This tells the dri... | This code scrapes product details from a category page by iterating through each product link. It uses Selenium to click on products, extract information with `get_product_info()`, save data to CSV via `write2csv()`, and navigate back to the category page. The loop continues until an exception occurs, signaling the end... | def get_products(self, url):
driver = self.get_driver()
driver.get(url) # Accessing the category link
try:
i = 1
while True: # We loop over all the products, accessing one by one
selector = f'{self.product_selector}[{i}]'
product = self.g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.