dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _relation_hosts(self, relation) -> dict:
"""Fetch unit names and address of all profiling provider units for a single relation.
Args:
relation: An `ops.model.Relation` object for which the unit name to
address mapping is required.
Returns:
A dictiona... | The main task of the code is to generate static scrape configurations for a given relation by extracting `scrape_jobs` and `scrape_metadata` from the relation's data. It annotates each scrape job with Juju Topology labels derived from `scrape_metadata`, prefixes job names, and returns a list of labeled job configuratio... | def _static_scrape_config(self, relation) -> list:
"""Generate the static scrape configuration for a single relation.
If the relation data includes `scrape_metadata` then the value of this key is used to
annotate the scrape jobs with Juju Topology labels before returning them.
Args:
... |
def check_block_is_blank(block, block_type):
return (
block_type == "paragraph"
and not block["has_children"]
and not block[block_type]["rich_text"]
)
def blank() -> str:
return "<br/>"
def collect_info(self, payload: dict) -> dict:
info = dict()
if "rich_... | This function converts a block from a structured format into a string representation. It handles different block types, checks for blank blocks, processes child blocks recursively with indentation, and generates output for tables or unsupported types. Error handling is included for exceptions during conversion. | def convert_block(
self,
block: dict,
depth=0,
):
outcome_block: str = ""
block_type = block["type"]
# Special Case: Block is blank
if check_block_is_blank(block, block_type):
return blank() + "\n\n"
# Normal Case
try:
... |
def _reset(self):
# to avoid a call to the api server if we are sure we do not want to access properties
# of the object other than those inferred we can provide directly the minmal resource (es: {"kind": "Pod"})
if self._resource_body is not None and "uid" not in self._resource_body:
... | This function sets a property value for a resource, updating it in both insert and update scenarios. It retrieves the old value, computes the new value, updates the resource properties, generates a YAML-patched payload, and sends a PATCH request via an API client. Finally, it returns the new and old values of the prope... | def set(self, prop, old_value_default=None):
"""
Set value for property, works both in update and insert
This funtion requires updating the resource to prepare for the next patch
:return: value, old_value
"""
self._reset()
props = self._get_resource_properties()
... |
def _reset(self):
# to avoid a call to the api server if we are sure we do not want to access properties
# of the object other than those inferred we can provide directly the minmal resource (es: {"kind": "Pod"})
if self._resource_body is not None and "uid" not in self._resource_body:
... | The main task of the code is to delete a specified property from a resource, update the resource's annotations with the modified properties, and send a PATCH request to apply the changes. It retrieves the current properties, removes the target property, serializes the updated properties into YAML annotations, and patch... | def delete(self, prop):
"""
Delete a single property
This funtion requires updating the resource to prepare for the next patch
"""
self._reset()
props = self._get_resource_properties()
try:
del props[prop.type][prop.name]
except KeyError:
... |
def files_list(dir_name):
list_of_file = listdir(dir_name)
all_files = list()
for entry in list_of_file:
full_path = join(dir_name, entry)
if isdir(full_path):
all_files = all_files + files_list(full_path)
else:
all_files.append(full_path)
return all_fi... | The main task of the code is to process a large image dataset by filtering out non-image files, sorting remaining images by size in descending order, and selecting up to 4000 images that meet criteria: containing a detected face landmark, being a smiling portrait, and not rotated. Selected images are saved to a result ... | def main():
files = files_list('/Users/sonora/Desktop/large-dataset/imdb')
filtered = list(filter(lambda file: is_image(file), files)) # remove files which are not images
sorted_files = sorted(filtered, key=lambda file: image_size(file), reverse=True) # sort by image size
counter = 0
for index, f... |
def normalize(members):
if is_pow2(len(members)):
return members
input_len = len(members)
result_len = round_up_to_pow2(len(members))
ext_len = result_len - input_len
splitpoint = input_len - ext_len
result = []
for i in range(0, splitpoint):
result.append(members[i])
... | The code simulates a game where a list of elements (actuals) is iteratively processed in rounds until only one remains. It normalizes the input, ensures the length is a power of two, and tracks each state in 'results' during each round. The 'chooser' determines how rounds are conducted, and the loop continues until the... | def game(actuals, chooser):
assert(len(actuals) > 0)
actuals = normalize(actuals)
assert(is_pow2(len(actuals)))
results = []
while True:
results.append(actuals)
if len(actuals) == 1:
break
else:
actuals = perform_round(actuals, chooser)
return r... |
def game(actuals, chooser):
assert(len(actuals) > 0)
actuals = normalize(actuals)
assert(is_pow2(len(actuals)))
results = []
while True:
results.append(actuals)
if len(actuals) == 1:
break
else:
actuals = perform_round(actuals, chooser)
return r... | The main task of the code is to read a specified text file, process its lines through a game function (`game`) with a `choose` strategy, determine the winner using `game_winner`, and visualize the results with `draw_graph`. It ensures a filename is provided, reads the file, splits content into lines, and executes game ... | def main():
if len(sys.argv) < 2:
print("specify file")
quit()
fnam = sys.argv[1]
file = open(fnam, encoding="utf-8", errors="ignore")
members = file.read().splitlines()
file.close()
res = game(members, choose)
winner = game_winner(res)
print("Nyert:", winner)
... |
def pre_explore(self):
# To get initial Model
for s in range(self.mdp.nb_states):
if s not in self.mdp.terminal_states:
for a in range(self.mdp.action_space.size):
self.mdp.reset()
self.mdp.current_state = s # to force the execution of... | This code implements a Q-learning algorithm with eligibility traces and planning. It updates a transition matrix (T), handles exploration/exploitation, and performs Q-value backups. The agent learns by interacting with an MDP, modifying transitions from terminal states, and executing planning steps when reaching goals.... | def learn(self, params, seed):
self.mdp.timeout = params.max_episode_steps
self.saver.nb_exps = np.zeros(params.episodes)
if params.pre_explore:
self.pre_explore()
self.T = normalize_mat(self.T)
self.T = np.nan_to_num(self.T)
if params.transi_goal_to_... |
def new_render(self, title):
"""
initializes the plot by creating its basic components (figure, axis, agent patch and table)
a trace of these components is stored so that the old outputs will last on the notebook
when a new rendering is performed
"""
self.figure_history.a... | This function renders a maze environment's state values, policies, and agent position dynamically. It updates a table with value estimates (V/Q) and policies, adjusts the agent's visual position, and handles new plot creation. Optional parameters control visibility of elements. If in a notebook, it records the visualiz... | def render(
self,
agent_state=-1,
v=None,
policy=None,
stochastic=False,
title="No Title",
): # updates the values of the table
# and the agent position and current policy
# some of these components may not show depending on the parameters given when ... |
def get_args():
global base_url
global url
global csv_name
global num_requested_fic
global multichap_only
global tags
parser = argparse.ArgumentParser(description='Scrape AO3 work IDs given a search URL')
parser.add_argument(
'url', metavar='URL',
help='a single URL poin... | The main task of the code is to process data entries by either applying specified tags to URLs or processing them directly. It loads existing IDs, generates a README, and iterates through tags to reset, add tags, and process IDs with header information. If no tags are provided, it processes IDs directly. The script con... | def main():
header_info = get_args()
make_readme()
print ("loading existing file ...\n")
load_existing_ids()
print("processing...\n")
if (len(tags)):
for t in tags:
print ("Getting tag: ", t)
reset()
add_tag_to_url(t)
process_for_ids(he... |
def get_args():
parser = argparse.ArgumentParser(description='Scrape and save some fanfic, given their AO3 IDs.')
parser.add_argument(
'ids', metavar='IDS', nargs='+',
help='a single id, a space seperated list of ids, or a csv input filename')
parser.add_argument(
'--csv', default='fanfics.csv',
help='csv o... | The main task of the code is to process fanfiction metadata (IDs, titles, tags, etc.) from input files or lists, write structured data to a CSV file with error logging, create output directories, handle resuming from a specific entry, and apply delays between requests. It parses arguments, checks file existence, writes... | def main():
fic_ids, csv_out, headers, restart, is_csv, only_first_chap, lang, include_bookmarks, metadata_only = get_args()
os.chdir(os.getcwd())
# if the output pathname includes a folder, make sure it exists. if not, create it.
output_directory = os.path.dirname(csv_out)
print(output_directory)
if (output_dir... |
def get_args() -> argparse.Namespace:
"""Parses and processes user-given CLI arguments"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"PATH",
help="Can be file path or directory (all files in directory will be processed)",
)
parser.add_argument(
... | The main task of the code is to process files or directories based on user-provided arguments, categorize processed files by status, and optionally generate a JSON report. It validates the input path, handles file/directory processing, captures results in a dictionary, and writes a timestamped JSON report if requested,... | def main() -> None:
"""Main function"""
# Get arguments
args = get_args()
# Process file(s)
_path = Path(args.PATH).resolve()
processed_files_by_status: dict[Status, list[Path]] = defaultdict(list)
if not _path.exists():
raise FileNotFoundError(f"Couldn't find a file or directory at... |
def writeRsrcSig(f, sig, ver):
sig = "rsrc:" + sig
if len(sig) > 15: sig = sig[:15]
ver &= 0xFFFF
f.write(struct.pack("16s", sig))
f.write(struct.pack("4s", "{:02X}{:02X}".format(ver >> 8, ver & 0xFF)))
def getSkinNum(self):
if self.skinNodeNames: return len(self.skinNodeNames)
return 0
def getSkelNum(self):
... | This code writes a 3D model/mesh data structure to a binary file, serializing header metadata (offsets, counts) and geometry attributes (points, normals, UVs, etc.), while aligning data to 16-byte boundaries and updating header pointers post-writing. It handles multiple data sections like points, materials, indices, sk... | def write(self, f):
sig = "GWModel"
ver = 0x100
writeRsrcSig(f, sig, ver)
f.write(struct.pack("i", 0)) # +14: file size
f.write(struct.pack("I", 0)) # +18 -> strs
f.write(struct.pack("I", len(self.strs.data))) # +1C
npnt = len(self.pts)
ntri = len(self.tris)
nmtl = len(self.mtls)
nskn = self.getSkin... |
def init_vox_pane(window):
"""Creates an empty parent frame for the other content frames to occupy."""
content_frame = Frame(window, padding=20)
content_frame.grid(column=1, row=0, sticky="nsew")
content_frame.columnconfigure(0, weight=1)
content_frame.columnconfigure(1, weight=1)
content_frame... | This code initializes a GUI interface for a VOX model application, setting up frames, image displays, and variables to manage user inputs. It includes controls for generating images, tracking attributes, ranks, and signatures, while preventing excessive rendering through a lock mechanism. | def __init__(self):
self.lock_generator = False # Lock out for the image generator to prevent excess rendering
self.parent_frame = init_vox_pane(win.ROOT)
self.left_frame, self.portrait_image_label, self.portrait_image = init_file_select_pane(self.parent_frame)
self.vox_name_... |
def containing(t):
#get number of docs that contain term t
count = 0
corpus = csv.DictReader(open(file))
for doc in corpus:
if t in doc['description'].split():
count += 1
return count
def ave_length():
#get average document length
corpus = csv.DictReader(open(file))
t... | This code implements the BM25 algorithm to rank documents based on a query. It processes the query by removing punctuation, splits it into terms, calculates BM25 scores for each document in a CSV corpus, filters scores >0, sorts them descending, and returns the top-k results. | def bm25(query, k):
for c in string.punctuation:
query = query.replace(c,'')
terms = {}
for term in query.split():
terms[term] = containing(term)
aveLen = ave_length()
totalDocs = total_docs()
corpus = csv.DictReader(open(file))
results = []
for doc in corpus:
... |
def parse_input(input_: str) -> list[tuple[list, list]]:
values = list(
map(json.loads, filter(lambda s: s.strip() != "", input_.split("\n")))
)
return [(values[i], values[i + 1]) for i in range(0, len(values), 2)]
def part_1(values: list[tuple[list, list]]) -> int:
return sum(i + 1 for i, v in... | The main task of the code is to read input data from a file, parse it, execute two problem-solving functions (part_1 and part_2), output their results, and measure the total execution time in milliseconds. | def main():
with open("input/day13.txt") as f:
values = parse_input(f.read())
t = time.perf_counter()
print("Part 1:", part_1(values))
print("Part 2:", part_2(values))
t = time.perf_counter() - t
print(f"Processed in {t*1000:.3f}ms") |
def getTagInfo(self, serial_number):
serial = ' '.join(serial_number.upper().split(':'))
msg = self.sendCmd('sMN CSGtTAGInf %s' % (serial) )
msg = msg.replace('sAN CSGtTAGInf ', '').split(' ')
tag_info = {}
try :
tag_info.update({'error': msg[0]})
... | The function writes data to a tag's memory blocks by converting the payload to hexadecimal, sending write commands for each block, and verifying the operation. It checks for tag information errors, pads payload chunks, and ensures successful writes. If `check_write` is True, it reads the tag post-write to confirm data ... | def writeTag(self, serial_number, payload, check_write=False):
#payload_len = len(payload)
payload_hex = [hex(x)[2:].upper() for x in payload]
written_hex = []
serial = ' '.join(serial_number.upper().split(':'))
tag_infos = self.getTagInfo(serial_number)
if int(tag_infos... |
def angle(v1, v2):
inner = dotproduct(v1, v2) / (length(v1) * length(v2))
if(inner>.9999):
return 0.0
if(inner<-.9999):
return np.pi
return math.acos(inner)
def length(v):
return math.sqrt(dotproduct(v, v))
def crossproduct(v1,v2):
return (v1[0]*v2[1]) - (v1[1]*v2[0]) | The code constructs a 2D grid from a set of points by identifying a coordinate system based on spatial relationships between points. It finds a starting point with four valid neighbors, defines orthogonal axes (east/north vectors), and expands the grid by mapping points to integer grid positions. It fills gaps using pr... | def getGridFromPoints(pts, parr_tol = 20*np.pi/180.0, perp_tol = 20*np.pi/180.0, same_len_tol = .7,padding=0):
print("PTS:",pts)
#first build a table from point to 4 closest nieghbors
point_opoint_dist_map={}#{pt:[(opt,distSq),...]}
for pt in pts:
point_opoint_dist_map[pt]=[]
for pt in pts:
for opt in pts:
... |
def angle(v1, v2):
inner = dotproduct(v1, v2) / (length(v1) * length(v2))
if(inner>.9999):
return 0.0
if(inner<-.9999):
return np.pi
return math.acos(inner)
def length(v):
return math.sqrt(dotproduct(v, v))
def dotproduct(v1, v2):
##print ("v1:",v1," v2:",v2)
return v1[0]*v2[0]+v1[1]*v2[1] | The function `get_oriented` classifies vectors in a list based on their alignment with reference vectors `e_vec` and `n_vec` using angle thresholds and length ratios. It categorizes vectors into `n_vecs_tups` (parallel to `n_vec`) or `e_vecs_tups` (parallel to `e_vec`), adjusting their orientation via dot products to e... | def get_oriented(vec_pt_tup_list,e_vec,n_vec):
n_vecs_tups=[]
e_vecs_tups=[]
for vec,pt in vec_pt_tup_list:
if(angle(vec,n_vec)<parr_tol or angle(vec,n_vec)>np.pi-parr_tol):
lenRat = abs(length(vec)/length(n_vec))
if(lenRat<1.0/same_len_tol and lenRat>same_len_tol):
#print("IS N VEC:",vec)
n_... |
def jsonFile(relPath):
f = open(os.path.join(os.getcwd(),os.path.normpath(relPath)))
d = json.loads(f.read())
f.close()
return d
def saveJsonFile(relPath,contents):
f = open(os.path.join(os.getcwd(),os.path.normpath(relPath)),"w")
d = json.dumps(contents, indent=2)
f.write(d)
f.close()
def refresh():
global ga... | This function adds a new challenge type to a system by acquiring a lock, checking if the type exists in a JSON file, appending it if absent, creating a new JSON file for the type, updating the master JSON, releasing the lock, and triggering a refresh to reflect changes. | def enrollChallengeType(type):
lockDict["challengesMaster"].acquire()
c = jsonFile("Data/Current/Challenges/challengesMaster.json")
if type not in c["ExistingChallengeTypes"]:
c["ExistingChallengeTypes"].append(type)
d = {}
saveJsonFile("Data/Current/Challenges/"+type+".json",d)
saveJsonFile("Data/Current/Ch... |
def refresh():
global gameConstants
gameConstants = jsonFile("Data/Current/gameConstants.json")
updateLockDict()
def jsonFile(relPath):
f = open(os.path.join(os.getcwd(),os.path.normpath(relPath)))
d = json.loads(f.read())
f.close()
return d
def saveJsonFile(relPath,contents):
f = open(os.path.join(os.getcwd(),... | This function enrolls a new challenge by updating a JSON file with provided parameters (flag, hints, value, etc.), ensuring thread safety via a lock. It waits until the challenge type is available in a lock dictionary, modifies the challenge data, saves the updated JSON, and releases the lock. The function copies defau... | def enrollChallenge(type,challenge,flag,hints,value,otherData):
while type not in lockDict.keys():
time.sleep(1)
refresh()
lockDict[type].acquire()
c = jsonFile("Data/Current/gameConstants.json")
d = jsonFile("Data/Current/Challenges/"+type+".json")
d[challenge] = c["defaultChallenge"].copy()
d[challenge]["fl... |
def saveJsonFile(relPath,contents):
f = open(os.path.join(os.getcwd(),os.path.normpath(relPath)),"w")
d = json.dumps(contents, indent=2)
f.write(d)
f.close()
def jsonFile(relPath):
f = open(os.path.join(os.getcwd(),os.path.normpath(relPath)))
d = json.loads(f.read())
f.close()
return d
def refresh():
global ga... | This code creates a new team by initializing its data from a default template and updating a master list of existing teams. It ensures thread safety using a lock when modifying the master list, appends the new team name if not already present, and triggers a refresh to reflect changes. | def addTeam(teamName):
d = gameConstants["defaultTeamData"].copy()
saveJsonFile("Data/Current/Teams/"+teamName+".json",d)
del d
lockDict["teamsMaster"].acquire()
d = jsonFile("Data/Current/Teams/teamsMaster.json")
if teamName not in d["existingTeams"]:
d["existingTeams"].append(teamName)
saveJsonFile("Data/Cu... |
def trainTest(data):
"""Devide the data in train and test datasets"""
y = data.iloc[:, -1]
data_train, data_test, y_train, y_test = model_selection.train_test_split(
data, y, test_size=0.30, random_state=42)
return data_train, data_test, y_train, y_test
def build_tree(self, data, current_depth=0... | The main task of the code is to train a decision tree model using the provided data, selecting either Gini impurity or entropy as the splitting criterion. If pruning is enabled, it splits the data into training and pruning sets, builds the tree, evaluates its accuracy on the pruning set, and prunes the tree to prevent ... | def learn(self, data, impurity_measure='entropy', prune=False):
"""function to create the tree based on data"""
if impurity_measure == 'gini':
self.function = self.gini
if prune is True:
data_train, data_prune, y_train, y_prune = trainTest(data)
self.root = se... |
def adjustAllBuffers(type, device_count, minBuffer, defaultBuffer, maxBuffer):
sendCommandToMultiple(type, device_count, "sysctl -w net.ipv4.tcp_rmem=\'" + str(minBuffer) + " " + str(defaultBuffer) + " " + str(maxBuffer) + "\'", True)
sendCommandToMultiple(type, device_count, "sysctl -w net.ipv4.tcp_wmem=\'" + ... | The main task of the code is to configure network settings by adjusting buffer sizes for hosts, introducing a 20ms delay on a network interface, and implementing a token bucket filter (TBF) for traffic shaping. This involves setting parameters like buffer limits, delay durations, and bandwidth constraints to manage net... | def main():
adjustAllBuffers("h", hosts, 10240, 87380, 131072000)
addDelays("s1", "eth1", "root", "20ms")
addTBF("s2", "eth2", "root handle 1:", "1gbit", 500000, 26214400) |
def LSE_batch(x, d, p_in, x0 = None, affine = False):
if(len(x) != len(d)):
print("LSE_batch: Current version only allows len(x)=len(d)")
N = len(d)
lse = np.zeros((N,))
p = p_in
if(affine == True):
p += 1
x_arr = np.zeros((p,))
if(affine == True):
x_arr[-1] = 1
... | The code performs segmented least squares filtering by dynamically identifying segments in input-output data (x, d) using a Bellman equation approach. It then applies recursive least squares (RLS) on each segment to estimate filter coefficients (w), predicted outputs (dhat), and errors (e), while incorporating segment ... | def Segmented_LS(x, d, p, seg_penalty, x0 = None, affine = False, verbose = False):
if(len(x) != len(d)):
print("Segmented_LS: Current version only allows len(x)=len(d)")
N = len(x)
##PART1. Find segments
x_init = np.zeros((p,))
if(x0 is not None):
x_init[:] = x0[:]
... |
def LSE_batch(x, d, p_in, x0 = None, affine = False):
if(len(x) != len(d)):
print("LSE_batch: Current version only allows len(x)=len(d)")
N = len(d)
lse = np.zeros((N,))
p = p_in
if(affine == True):
p += 1
x_arr = np.zeros((p,))
if(affine == True):
x_arr[-1] = 1
... | The function `Segmented_RLS` performs segmented recursive least squares (RLS) estimation on input-output sequences `x` and `d`. It first identifies optimal segment boundaries using a penalty term (`seg_penalty`) and least squares (LSE) to minimize error. Then, it computes RLS filter coefficients (`w`), predicted output... | def Segmented_RLS(x, d, p, seg_penalty, alpha, x0 = None, affine = False, verbose = False):
if(len(x) != len(d)):
print("Segmented_RLS: Current version only allows len(x)=len(d)")
N = len(x)
##PART1. Find segments
x_init = np.zeros((p,))
if(x0 is not None):
x_init[:] = x0[:]... |
def getRpn(s):
mass = parse(s)[0]
opers = []
ans = []
for ch in mass:
if ch == '(':
opers.append(ch)
elif ch in delims:
if not opers:
opers.append(ch)
elif ch == ')':
while True:
curr = opers[len(o... | The code evaluates a Reverse Polish Notation (RPN) expression using values from a parsed table. It processes each token in the RPN string: digits fetch values from the table, '!' applies negation, and other tokens perform arithmetic operations on the last two values in a stack. The result is returned, or [0] if an erro... | def getResTable(s):
mass, table = getRpn(s), parse(s)[1]
a = []
for i in range(0, len(mass)):
if mass[i].isdigit():
a.append(table[int(mass[i])])
elif mass[i] == '!':
a1 = a.pop()
a.append(negative(a1))
else:
a2 = a.pop()
... |
def conv2d_fixed_padding(inputs, filters, kernel_size, data_format, strides=1):
"""Strided 2-D convolution with explicit padding."""
if strides > 1:
inputs = fixed_padding(inputs, kernel_size, data_format)
return tf.keras.layers.Conv2D(
filters=filters, kernel_size=kernel_size,
stri... | The code constructs the Darknet53 feature extractor, stacking convolutional layers with batch normalization and leaky ReLU, followed by residual blocks. It progressively increases filter sizes (32→64→128→256→512→1024) through downsampling convolutions and repeated residual blocks. The model outputs three feature maps a... | def darknet53(inputs, training, data_format):
"""Creates Darknet53 model for feature extraction."""
inputs = conv2d_fixed_padding(inputs, filters=32, kernel_size=3,
data_format=data_format)
inputs = batch_norm(inputs, training=training, data_format=data_format)
inputs =... |
def darknet53(inputs, training, data_format):
"""Creates Darknet53 model for feature extraction."""
inputs = conv2d_fixed_padding(inputs, filters=32, kernel_size=3,
data_format=data_format)
inputs = batch_norm(inputs, training=training, data_format=data_format)
inputs =... | This code processes input images through a YOLOv3 model to detect objects, returning bounding boxes for each image. It normalizes inputs, applies DarkNet-53, processes features through convolutional blocks, upsamples, generates detections via YOLO layers, concatenates results, builds boxes, and applies non-max suppress... | def __call__(self, inputs, training):
"""Add operations to detect boxes for a batch of input images.
Args:
inputs: A Tensor representing a batch of input images.
training: A boolean, whether to use in training or inference mode.
Returns:
A list containing cl... |
def parsed_dict(parser):
return parser.parse_args().__dict__
def clean_tmp(temp_path="./tmp"):
if os.path.exists(temp_path):
shutil.rmtree(temp_path)
print("[INFO] tmp files are cleaned up")
def frame_extraction(video_path="input.mp4",temp_path="./tmp/"):
if not os.path.exists(temp_path):
... | The code implements a command-line tool for video steganography, enabling users to encode a string into a video (encryption) or extract hidden data from a video (decryption). It uses argparse for argument parsing, validates required inputs, processes video frames, integrates audio, and handles temporary files. Encrypti... | def main():
parser = argparse.ArgumentParser(description="Command-line tool for video steganography")
parser.add_argument('-es','--encode-string',metavar='S',type=str,help='string for encryption')
parser.add_argument('-s','--source',metavar='U',type=str,help='source for video path')
parser.add_argument(... |
def open(self):
if not self._path: return None
if not self.is_jpeg(): return None
self._image = imagefile.open_image(self._path)
def width(self):
if not self._image: self.open()
if not self._image: return None
w, h = self._image.size
return w
def height(self):
... | The code resizes an image to a specified long side while maintaining aspect ratio, updates EXIF resolution data, and saves the resized image to a directory. If the original image is smaller than the long side, it copies the image instead. | def resize(self,save_dir, long_side=1000):
if not self._image: self.open()
if not self._image: return None
if not os.path.isdir(save_dir): return None
save_path = save_dir + '/' + self.name()
exif = piexif.load(self._image.info["exif"])
if self.width() < long_side and sel... |
def initialize_driver():
options = Options()
options.add_argument("--headless=new")
options.add_argument('--log-level=3')
driver = webdriver.Chrome(options=options)
# Selenium-stealth to bypass captcha
stealth(driver,
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537... | The main task of the code is to scrape hotel data for Bahrain on a specific date using a web driver, process the data into an Excel-compatible format, and terminate the driver session. It initializes a driver, retrieves hotel information, converts it into a structured dictionary for Excel output, and ensures proper res... | def main():
driver = initialize_driver()
hotel_data = scrape_hotel_data(initialize_driver(), destination="Bahrain", date="2024-03-02")
main_dic = {}
main_dic = excel(hotel_data)
driver.quit() |
def search_by_id(self, id):
obj_to_find = None
for obj in self.fetch_all():
if obj.id == id:
obj_to_find = obj
break
return obj_to_find
def get_object_variable_values_from_object(self, obj):
return [
(attr, getattr(obj, attr))
... | This code saves or updates an object in a database. If the object exists (checked via `search_by_id`), it updates the existing entry using prepared SQL with variable values. If not, it inserts a new record. The method retrieves relevant data from the object, prepares the appropriate query (`update` or `save`), and exec... | def save(self, obj):
if self.search_by_id(obj.id):
# Update
obj_variable_values = self.get_object_variable_values_from_object(obj)
return self.execute_query(
self.prepare_query(obj, obj_variable_values, query_for_model["update"])
)
else:
... |
def search_by_id(self, id):
obj_to_find = None
for obj in self.fetch_all():
if obj.id == id:
obj_to_find = obj
break
return obj_to_find
def execute_query(self, query):
# Idea: Make guestbook the app's name somehow so it can be accessed globall... | The main task of the code is to delete an object by its ID. It first checks if the object exists using `search_by_id`, returning False if not found. If found, it prepares and executes a deletion query using the model's `delete_by_id` logic, returning the result of the query execution. | def delete(self, id):
if not self.search_by_id(id):
return False
else:
return self.execute_query(
self.prepare_query(self._class(id), {}, query_for_model["delete_by_id"])
) |
def is_valid_move(self, row: int, col: int) -> bool:
if self.combined[row][col] == 0:
if not GomokuGame.rules.is_legal_move(row, col, self.player + 1, self.combined):
print("Illegal move")
return False
else:
print("Position taken")
retu... | The code's main task is to validate a move in a game, place a stone if valid, check for captured opponent stones, and return the count of captures. If the move is invalid, it returns -1. The function ensures proper game state updates by first verifying the move's legality, then executing it and counting captures, which... | def make_move(self, row: int, col: int):
if self.is_valid_move(row, col):
num_captures = self.check_for_captures(row, col)
self.place_stone(row, col)
return num_captures
else:
return -1 |
def block_possible(self, piece, x2, y2):
"""Verifies if it is possible to place a piece between the king and the attacking piece."""
king = None
for p in self.pieces_coords:
if p:
if p.color == self.opponent_color() and p.type == "king":
king = p
... | The function determines if the king can be protected from a check by verifying if the attack can be blocked, the king can evade, or the attacking piece can be captured. It returns True if any of these three conditions are met. | def protect_possible(self, piece, x2, y2):
"""Verifies if it is possible to protect the king against a check coming from piece at position x2, y2."""
return self.block_possible(piece, x2, y2) or \
self.evade_possible() or \
self.take_possible(x2, y2) |
def promotion(self, piece, x, y):
self.pawn_promotion(piece, x, y)
def get_piece(self, name):
"""retrieves piece object from the piece name."""
for p in self.pieces_coords:
if p.name == name:
return p
def king_checked(self, color):
"""verifies is the king of t... | This function validates a chess move for a given piece, updates the game state by placing the piece at the new position, handles captures, en passant, castling, pawn promotion, checks for check/checkmate, and updates the UI accordingly. It returns True if the move is valid, otherwise False. | def place_piece(self, piece, position):
"""If the move is valid the piece is placed at the given position and the game state updated. Otherwise 'False'
is returned and the game state stays unchanged."""
x1, y1 = piece.position
x2, y2 = position
valid = piece.valid_move(x2, y2, se... |
def med_weighted_dice_roll():
"""
Dice roll with a weighting of 1/24
"""
roll_24 = randint(1, 24)
# print(f"You scored a {roll_24 }")
return roll_24
def low_weighted_dice_roll():
"""
Dice roll with a weighting of 1/6
"""
roll_6 = randint(1, 6)
# print(f"You scored a {roll_6}"... | The function `player_attack` applies class-specific damage modifiers to a player's attack, reduces the monster's HP, and manages combat state. If the monster's HP reaches zero, it ends the encounter, resets movement, and triggers navigation. | def player_attack(dmg):
"""Attack Loop for Monster Encounters"""
global CURRENT_PLAYER_CLASS
global MONSTER_HP
global PLAYER_ENCOUNTER
# Checks the class of the player and adds a 'skill' randomised number to their base damage
if CURRENT_PLAYER_CLASS == 'Warrior':
dmg = dmg + med_weighte... |
def ping(self):
self.connect()
try:
with closing(self.db.cursor()) as cursor:
cursor.execute("SELECT 1")
except:
self.db = None
self.connect()
def migration_version(self):
self.ping()
version = 0
with closing(self.db.cu... | The code authenticates a user by verifying their password, checking database version, and assessing account status (active/retained/expired) based on retention deadlines and last activity. It updates the database with current time and status if needed, returning authentication success/failure along with a status messag... | def auth(self, validate: bool = False) -> Tuple[bool, str]:
"""Authenticate a username with given password."""
self.ping()
if self.migration_version() < AuthDb.MIN_VERSION:
return False, "Empty or not updated database."
auth_user = self.__find_user()
if not auth_use... |
def ping(self):
self.connect()
try:
with closing(self.db.cursor()) as cursor:
cursor.execute("SELECT 1")
except:
self.db = None
self.connect()
def migration_version(self):
self.ping()
version = 0
with closing(self.db.cu... | (The main task of the code is to register a new user by validating the username and password, checking database compatibility, ensuring the username is unique, generating a unique UID, hashing the password, and inserting the user into the database. It returns success or specific error messages based on validation steps... | def register(self) -> Tuple[bool, str]:
"""Register a new username with given password."""
self.ping()
if not self.user.name:
return False, "Bad username."
if not self.user.password:
return False, "Bad password."
if self.migration_version() < AuthDb.MIN... |
def ping(self):
self.connect()
try:
with closing(self.db.cursor()) as cursor:
cursor.execute("SELECT 1")
except:
self.db = None
self.connect()
def migration_version(self):
self.ping()
version = 0
with closing(self.db.cu... | This code changes a user's password in a database by validating the user, hashing the new password, and updating the database record. It checks the database version, confirms user existence, skips validation if specified, hashes the password with a default algorithm, and updates the 'auth' table. Errors include invalid... | def change_password(self, new_password: str, skip_validation: bool = False) -> Tuple[bool, str]:
"""Change a specified username's password."""
self.ping()
if self.migration_version() < AuthDb.MIN_VERSION:
return False, "Empty or not updated database."
auth_user = self.__fin... |
def ping(self):
self.connect()
try:
with closing(self.db.cursor()) as cursor:
cursor.execute("SELECT 1")
except:
self.db = None
self.connect()
def migration_version(self):
self.ping()
version = 0
with closing(self.db.cu... | The main task of the code is to unregister an existing username by marking the user's account as expired in the database. It performs checks for database version compatibility, verifies user existence, validates credentials (unless skipped), and updates the user's status. If any step fails, it returns appropriate error... | def unregister(self, skip_validation: bool = False) -> Tuple[bool, str]:
"""Unregister an existing username."""
self.ping()
if self.migration_version() < AuthDb.MIN_VERSION:
return False, "Empty or not updated database."
auth_user = self.__find_user()
if not auth_u... |
def _pretrain(self) -> None:
"""
Run the perceptual pre-training loop.
Run the perceptual-based pre-training loop for the given number of
epochs. The best recorded model from the pre-training phase will be
used to initialize the weights of the generator in the second phase of
... | The code's main task is to execute the pre-training phase of a neural network, clear the GPU cache to optimize memory usage during extended runtime, perform the main training phase using a GAN (Generative Adversarial Network), and finally execute cleanup operations to finalize the training process. | def train(self) -> None:
"""
Initiate the pre-training followed by the main training phases of the
network.
"""
self._pretrain()
# Clear the GPU cache between pre-training and main training phases to
# optimize memory usage during extended runtime.
torch.c... |
def selectqueue(update, context):
query = update.callback_query
data = query.data
data = data.replace('LOCATION=', '')
try:
params = {'location': data}
url = QUEUEURL + 'calculateWaitTime'
waitingtime = requests.get(url=url, params=params).text
except:
context.bot.ans... | This function handles callback queries by routing them to specific actions based on the data prefix: 'LOCATION=' triggers queue selection, 'JOINQUEUE=' adds the user to a queue, 'CANCELQUEUE' cancels the queue, and 'WASHTYPE=' initiates payment processing. It acts as a dispatcher for different user interactions in a qu... | def callbackquery(update, context):
query = update.callback_query
data = query.data
if data.startswith('LOCATION='):
selectqueue(update, context)
elif data.startswith('JOINQUEUE='):
joinqueue(update, context)
elif data == ('CANCELQUEUE'):
cancelqueue(update, context)
elif... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dataset", type=str, default='imdb', help="dataset name"
)
args = parser.parse_args()
return args
def load_embeddings(path):
idx_2_word = []
word_2_idx = {}
word_vectors = []
with open(path, encoding=... | The main task of the code is to load ConceptNet word embeddings and use them to expand label names for a specified dataset. It parses command-line arguments, loads embeddings into word-to-index and index-to-word mappings, then applies the `gen_label_names_conceptnet` function to enhance dataset labels with ConceptNet-b... | def main():
args = parse_args()
dataset = args.dataset
print("loading concetpnet embeddings....")
idx_2_word, word_2_idx, word_vectors = load_embeddings(embedding_path)
print(f"expanding {dataset} label names...")
print('with conceptnet')
gen_label_names_conceptnet(dataset, idx_2_word, word_... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dataset", type=str, default='imdb', help="dataset name"
)
args = parser.parse_args()
return args
def encode_and_save_5_benchmarks(dataset, suffix, model, tokenizer, model_name):
label_name_file = f"./datasets/Te... | The code's main task is to encode and save model outputs for benchmark datasets using a RoBERTa-large model. It loads the model and tokenizer, processes input datasets (agnews, yahoo, dbpedia, imdb, amazon), and applies different encoding functions based on the dataset type. The results are saved in specified formats (... | def main():
args = parse_args()
model_name = 'roberta_large'
dataset = args.dataset
suffix_dict = {
'agnews': "csv",
'yahoo': "csv",
'dbpedia': "txt",
'imdb': "txt",
'amazon': "txt"
}
tokenizer = AutoTokenizer.from_pretrained(configs.model_names[model_na... |
def port_write(port,script:str):
port.write(script.encode())
check_signal(port)
res = port.readlines()
return(res)
def sms_info(res:list):
for r in res:
r = r.decode("utf-8",errors="ignore")
if "+CMGR:" in r:
phone = re.findall("[0-9]+",r)[0]
date = re.findall... | The function retrieves an SMS message from a device using an AT command, processes the response to extract information, decodes the message content, checks for an OTP, and inserts the data into a database. It handles optional callback processing and port status checks. | def get_message(Device, index, cb =None):
script = "AT+CMGR={}\r".format(index)
res = port_write(Device.status["port"],script)
info = sms_info(res)
if cb != None:
res = cb(res)
raw_sms = ""
for r in res:
r = r.decode("utf-8",errors="ignore")
raw_sms = raw_sms + r
otp ... |
def board_is_clear(matrix): # Checks if the matrix is empty. Returns True if it is, and False if it isn't.
clear = True
for row in range(1, len(matrix)):
for cell in range(1, len(matrix[row])):
if matrix[row][cell] != ' ':
print("Problem with cell {} in row {}".format(cell, ... | The function automatically places AI ships on a clear matrix by randomly selecting positions and orientations, validating placements, and avoiding overlaps. It returns the updated matrix and a dictionary of ship locations, ensuring ships are placed without conflicts. Occasional suboptimal placements are allowed for var... | def ship_placement_ai(matrix): # This function runs through the ship-placement sequence for the ai. Call it
# when you want the AI to place their ships. It takes an empty matrix and automatically fills it with ships.
# Returns the matrix, and a dictionary of ship locations, in tuple form: (matrix, dict).
a... |
def board_is_clear(matrix): # Checks if the matrix is empty. Returns True if it is, and False if it isn't.
clear = True
for row in range(1, len(matrix)):
for cell in range(1, len(matrix[row])):
if matrix[row][cell] != ' ':
print("Problem with cell {} in row {}".format(cell, ... | The main task of the code is to randomly place a set of ships (Aircraft Carrier, Battleship, etc.) on a player's game board matrix, ensuring valid placements without overlaps. It uses a "lazy" approach by repeatedly attempting random orientations and positions, validating each placement, and avoiding previously failed ... | def ship_placement_lazy(matrix): # This is basically the AI Placement, but placing on the player's board.
player_ship_location_dict = {}
if board_is_clear(matrix):
ships_list = [('Aircraft Carrier', 5), ('Battleship', 4), ('Destroyer', 3), ('Submarine', 3),
('Patrol Boat', 2)]
... |
def ship_placement_lazy(matrix): # This is basically the AI Placement, but placing on the player's board.
player_ship_location_dict = {}
if board_is_clear(matrix):
ships_list = [('Aircraft Carrier', 5), ('Battleship', 4), ('Destroyer', 3), ('Submarine', 3),
('Patrol Boat', 2)]
... | The function allows a player to manually or automatically place ships on a matrix. It validates input for ship orientation, coordinates, and placement, updating the matrix and a ship-location dictionary. If manual, it iterates through predefined ships, prompting the user for each placement. Returns the updated matrix a... | def ship_placement_player(matrix): # This function runs through the ship-placement sequence for the player. Call it
# when you want the player to place their ships. It takes an empty matrix and lets the player fill it with ships.
# Returns the matrix, and a dictionary of ship locations, in tuple form: (matrix,... |
def read_battle_log(file_path):
with open(file_path, 'r',encoding='utf-8') as file:
lines = file.readlines()
battle_log = list(filter(None,[list(filter(None, [item.strip() for item in line.split('|')])) for line in lines]))
return battle_log
def split_battle_data(battle_log):
turn_log = []
... | This function processes battle logs by parsing player and Pokémon data, tracking game states through each turn, and returning structured battle situations with win status, total turns, ranks, and battle IDs. It initializes a battle, handles turn events, detects wins/ties, and logs situations until the battle ends. | def log_process(file_path):
file_name = file_path.split('/')[-1]
battle_log = read_battle_log(file_path)
turn_log = split_battle_data(battle_log)
#initialize battle
reg_num = file_name.split('.')[0].split('-')
battle = Battle(reg_num[0],reg_num[1])
for line in turn_log[0]:
if line[0... |
def _adjust_action(self, action: list):
assert np.array(action).shape == self.action_space.shape, "the action shape is wrong: {}".format(len(action))
if np.isnan(action[0]):
action[0] = 0
warnings.warn("linear action is NAN")
if np.isnan(action[1]):
action[1] ... | The main task of the code is to process a robot's action input, adjust it based on velocity thresholds, publish movement commands (linear/angular velocity), update the environment state (observations, step count, IMU data), and return the next observation and termination status for a reinforcement learning step. It als... | def step(self, action: Union[list, np.ndarray], vel_threshold=None):
if self.terminate_stop and self.robot_terminate:
action = np.zeros(len(action))
action = self._adjust_action(action=action)
if vel_threshold is None:
self.action_threshold = [self.action_space.high[0], ... |
def parse_command_line_args():
debug, verbose = False, False
if len(sys.argv) < 3:
sys.stderr.write("usage: same_sumission.py <subreddit1> <subreddit2>"+\
"[-d] -[v] [-l limit]\n")
sys.stderr.write("(enter -d for debug mode, -v for verbose mode)\n")
sys.stderr.wr... | This code scrapes Reddit data from two subreddits, constructs a network graph of user interactions (in-group and cross-subreddit), and saves it as a GEXF file. It parses command-line arguments, fetches submissions/comments, maps users/nodes, and annotates edges with submission context. Debug/verbose flags control outpu... | def main():
sub1, sub2, DEBUG, VERBOSE, LIMIT = parse_command_line_args()
if DEBUG:
sub1, sub2 = '100pushups', 'MakeupAddiction'
user_agent = ("reddit_sna scraper v0.1 by /u/sna_bot "
"https://github.com/brianreallymany/reddit_sna")
r = praw.Reddit(user_agent=user_agent)
... |
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def draw(p) -> bool:
return True if np.random.uniform() < p else False
def interact(self, ag_a: Agent, ag_b: Agent, is_nei: bool, iter_idx) -> None:
# if self.verbose:
# print("interact | ag {} and ag {}, is_nei = {}".forma... | The code simulates a multi-agent interaction process over a set number of iterations, tracking trust dynamics and fitness updates. Agents are paired either within their neighborhood (with probability `embeddedness`) or with strangers, facilitating interactions that update trust statistics and fitness. Periodic logging ... | def simulate(self, log_verbose_n=10, log_record_v=200):
eprint("params: n_player={}, n_neighbor={}, n_iteration={}, embeddedness={}, payoff_x={}, rnd_seed={}".format(self.n_player,
self.n_neighbor, self.n_iteration, self.embeddedness, self.PAYOFF_X, self.rnd_seed))
log_idx, log_t_list = 0, [... |
def read_input(input_file):
input_matrix = []
with open(f"../resources/{input_file}", 'r') as file:
for line in file:
input_matrix.append(list(map(int, line.split(' '))))
file.close()
return input_matrix
def the_shortest_safe_route(matrix):
shortest_route = float("inf")
for i... | The function determines the shortest safe route in a matrix by reading input data, processing the matrix to add zeros to neighbors, computing the route, handling TypeErrors by setting the result to -1, and writing the output to a specified file. | def find_the_shortest_safe_route(input_file, output_file):
try:
matrix = read_input(input_file)
shortest_route = the_shortest_safe_route(add_zeros_to_neighbours(matrix))
except TypeError:
shortest_route = -1
write_output(shortest_route, f"../resources/{output_file}") |
def __read_processes_state_dict2file(self):
dict2return = {}
if os.path.isfile(sc.PATH2SAVE_PROCESS_DICT):
file_to_read = open(sc.PATH2SAVE_PROCESS_DICT, "rb")
dict2return = pickle.load(file_to_read)
file_to_read.close()
logger.info(f'dict2return = {dict2retur... | This code initializes a process manager that monitors and updates process states using listeners and a scheduler. It sets up synchronization mechanisms, validates job prefix consistency across configurations, and schedules periodic checks to track process changes, appending processes, and verifying termination based on... | def __init__(self, max_number_of_process: int, upload_root_path: str, function2call_processes_changes_state: dict, function2append_process: dict, paths2verify_process_ends: dict):
self.__max_number_of_process = max_number_of_process
self.__upload_root_path = upload_root_path
self.__processes_sta... |
def print_ext(self, *args):
if self.silent == False:
print_ext(*args)
def check_model_iteration(self):
latest = tf.train.latest_checkpoint(self.snapshot_path)
if latest == None:
return 0
return int(latest[len(self.snapshot_path + 'model-'):])
def create_data(self)... | The code trains a machine learning model using TensorFlow, handling cross-validation via `fold_id`, setting up optimizers (Adam/Momentum), learning rate decay, and logging training/test metrics. It initializes networks, computes losses, runs training loops with periodic validation, saves model checkpoints, and manages ... | def run(self):
self.variable_initialization = {}
self.print_ext('Training model "%s"!' % self.model_name)
if hasattr(self, 'fold_id') and self.fold_id:
self.snapshot_path = './snapshots/%s/%s/' % (self.dataset_name, self.model_name + '_fold%d' % self.fold_id)
sel... |
def print_ext(self, *args):
if self.silent == False:
print_ext(*args)
def set_kfold(self, no_folds = 10, fold_id = 0):
inst = KFold(n_splits = no_folds, shuffle=True, random_state=125)
self.fold_id = fold_id
self.KFolds = list(inst.split(np.arange(self.no_samples)))
... | This function performs k-fold cross-validation (default 10 folds) on a neural network. It resets TensorFlow graphs for each fold, trains the model, records maximum accuracy per fold, calculates mean and standard deviation of accuracies, and logs results with timestamps to a file. The output includes mean accuracy (±std... | def run_kfold_experiments(self, no_folds=10):
acc = []
self.net_constructor.create_network(self.net_desc, [])
desc = self.net_desc.get_description()
self.print_ext('Running CV for:', desc)
start_time = time.time()
for i in range(no_folds):
tf.reset_de... |
def zip_target(self):
""" Zip the target directory. """
if Path(self.path_to_zip).exists():
raise LatcherError(
"Zip file at already exists at: "+
self.path_to_zip
)
if not Path(self.path_to_target).is_dir():
raise LatcherError(... | The code's main task is to perform three operations sequentially: zip the target data, encrypt it using the provided password, and then clean up any temporary files or resources. This method encapsulates data compression, encryption, and cleanup in a structured workflow. | def latch(self, password):
""" (1) Zip. (2) Encrypt. (3) Clean. """
self.zip_target()
self.encrypt(password)
self.clean() |
def get_args() -> Namespace:
"""
Parse command line arguments using argparse.
Returns the parsed argparse.Namespace object.
"""
parser = ArgumentParser()
parser.add_argument('--study_in', type=str, required=True,
help='Study subjects to use for PCA calculation')
parse... | The main task of the code is to process a genetic study dataset through multiple steps: ordering chromosomes, filtering variants (by MAF and missingness), removing ambiguous/multiallelic variants, performing LD pruning, and conducting PCA for population structure analysis. It uses PLINK2 tools to convert formats, subse... | def main() -> None:
args = get_args()
# Validate arguments.
# if not validate_args(args):
# die('Invalid arguments: one or more required files '
# 'do not exist.', 255)
#order chromosome
ordered_file = 'ordered_study'
order_chromosome_completed_process = order_chromosome(file_... |
def _get_task_template_and_graph_id(self, task_id: int) -> Tuple[int, int] | None:
""" Get the task template ID and the graph ID for a given task ID.
:param task_id: ID of task
:return: (task template ID, graph ID)
"""
cursor = self.conn.cursor()
cursor.execute("SELECT *... | This function retrieves evaluation data for a specified task ID by fetching associated graph and script components. It obtains the task template and graph ID, then derives the task solver ID and execution script. The graph is retrieved using the graph ID, and both are packaged into a BasicEvalRequestData object for eva... | def get_basic_eval_request_data(self, task_id: int) -> BasicEvalRequestData:
""" Get data for evaluation request for specified task ID.
:param task_id: ID of task
:return: BasicEvalRequestData
"""
task_template_id, graph_id = self._get_task_template_and_graph_id(task_id)
... |
def read_from_wls_se_files(datasetType, data_dir):
if datasetType == "test":
path = str(data_dir) + "/Test_Estimate.csv"
elif datasetType == "validation":
path = str(data_dir) + "/Validation_Estimate.csv"
else:
path = str(data_dir) + "/Training_Estimate.csv"
with open(path, 'r') ... | The main task of the code is to generate a dataset of factor graphs from WLS state estimation data. It reads input files, constructs directed graphs with variable and factor nodes, connects nodes via Jacobian edges, optionally links nodes to second neighbors, and serializes the resulting graphs into JSON files for trai... | def generate_dataset(datasetType, data_dir, should_connect_node_to_second_neighbours=True):
"""
:param datasetType: train, validation or test set
:param should_connect_node_to_second_neighbours: if true, adds direct variable-to-variable node connections, i.e.
creates the augmented factor graph f... |
def get_async_stack_root_addr() -> gdb.Value:
"""
Returns a pointer to the top-most async stack root, or a nullptr if none
exists.
"""
pthread_addr = get_current_pthread_addr()
if int(pthread_addr) == 0:
return nullptr()
# Check if the tls key is initialized
tls_key = gdb.parse_... | The function retrieves an async stack trace by combining normal and async stack frames. It starts from the top of the stack, walks through normal frames until reaching the async root, then alternates between normal and async frames to collect return addresses. The result is a list of GDB values representing the combine... | def get_async_stack_addrs() -> List[gdb.Value]:
"""
Gets the async stack trace, including normal stack frames with async
stack frames.
See C++ implementation in `getAsyncStackTraceSafe` in
folly/experimental/symbolizer/StackTrace.cpp
"""
async_stack_root_addr = get_async_stack_root_addr()
... |
def get_async_stack_addrs_from_initial_frame(
async_stack_frame_addr: gdb.Value,
) -> List[gdb.Value]:
"""
Gets the list of async stack frames rooted at the current frame
"""
addrs: List[gdb.Value] = []
while int(async_stack_frame_addr) != 0:
async_stack_frame = AsyncStackFrame.from_addr... | This code collects and prints async stack trace addresses using GDB's API. If an argument is provided, it parses it as a memory address, retrieves the async stack root, and extracts frame addresses. If no argument is given, it fetches all async stack addresses. Errors during execution are caught and displayed with trac... | def invoke(self, arg: str, from_tty: bool):
try:
addrs: List[gdb.Value] = []
if arg:
async_stack_root_addr = gdb.parse_and_eval(arg)
if int(async_stack_root_addr) != 0:
async_stack_root = AsyncStackRoot.from_addr(async_stack_root_addr)
... |
def is_valid_file(parser, arg):
"""Helper function for argparse to check if a file exists"""
if not os.path.isfile(arg):
parser.error('The file %s does not exist!' % arg)
else:
#return open(arg, 'r')
return arg
def list2str(lst):
"""Convert a list to a comma-separated string repr... | The main task of the code is to either reset or measure correction values for CBHV boxes. It processes command-line arguments to specify input/output files, host configurations, calibration parameters (voltage range, stepping), and execution mode (reset vs. calibration). The code prepares simulation settings, validates... | def main():
"""Main function: process all information, prepare simulation process, submit jobs"""
parser = argparse.ArgumentParser(description='CBHV boxes control: Set correction values '
'for boxes or measure them')
parser.add_argument('-i', '--input', nargs=1, metavar=... |
def get_apk_file_dict(csv_file):
apk_dict = dict()
with open(csv_file,'r') as file:
csv_reader = csv.reader(file)
# skiping the header
next(csv_reader, None)
for row in csv_reader:
apk_dict[row[0]] = row[1]
return apk_dict
def get_path(apk, home_dir):
sha1 = hashlib.sha1()
sha1.update(apk.encode('u... | The main task of the code is to detect Personally Identifiable Information (PII) in network traffic logs generated by Android apps. It processes APK files and traffic logs from a specified directory, extracts request flows, identifies PII using predefined patterns, and formats detected PII entries into CSV-compatible s... | def main():
ap = argparse.ArgumentParser(description='Detecting personal data in the network traffic by String-Matching Device-Bound Data')
ap.add_argument('-s', '--serial', dest='serial', type=str)
ap.add_argument('-f','--file', dest='file', type=str)
ap.add_argument('-d','--log_dir', dest='log_dir', type=str)
... |
def get_apk_file_dict(csv_file):
apk_dict = dict()
with open(csv_file,'r') as file:
csv_reader = csv.reader(file)
# skiping the header
# next(csv_reader, None)
for row in csv_reader:
apk_dict[row[0]] = row[1]
return apk_dict
def get_path(apk, home_dir):
sha1 = hashlib.sha1()
sha1.update(apk.encod... | The main task of the code is to perform dynamic analysis on Android APK files to capture network transmission data. It processes input APKs, checks for existing analysis results in specified output directories, and runs analysis only if no prior results are found. The code uses command-line arguments to specify input f... | def main():
ap = argparse.ArgumentParser(description='Dynamic analysis to capture network transmission data')
ap.add_argument('-s', '--serial', dest='serial', type=str)
ap.add_argument('-p', '--port', dest='port', type=int)
ap.add_argument('-f','--file', dest='file', type=str)
ap.add_argument('-o','--output', des... |
def feedforward(self, X):
'''
feedforward builds a 3-layer neural network and computes the two probabilities,
one for class 0 and one for class 1
:param X: input data
:param actFun: activation function
:return:
'''
for count in range(self.num_layers - 1):... | The main task of the code is to train a neural network using gradient descent with backpropagation. It performs forward propagation, computes gradients via backpropagation, applies L2 regularization to weights, updates parameters using a learning rate (epsilon), and optionally prints the loss every 1000 iterations. The... | def fit_model(self, X, y, epsilon=0.01, num_passes=20000, print_loss=True):
'''
fit_model uses backpropagation to train the network
:param X: input data
:param y: given labels
:param num_passes: the number of times that the algorithm runs through the whole dataset
:param ... |
def _generateMap(self, buildings):
"""Set the map of the experiment area
The simulated area is x_range by y_range. In order to denote the edge of the area,
we used [x_range+2, y_range+2] matrix to represent the map:
Example: x_range = 8, y_range = 6.
... | The function resets a reinforcement learning environment by generating a map with specified buildings, randomly or manually placing the agent and radiation source (avoiding buildings), initializing measurement and radiation matrices, computing shortest distances via BFS, and returning a normalized state array for the C... | def resetCNN(self, buildings, current_location, source_location, source_intensity='random'):
'''Reset the game for the reinforcement learning algorithm
Paremeters
----------
self: class object
buildings: list(set(2-tuple)). A list of the 'building' input for the... |
def _generateMap(self, buildings):
"""Set the map of the experiment area
The simulated area is x_range by y_range. In order to denote the edge of the area,
we used [x_range+2, y_range+2] matrix to represent the map:
Example: x_range = 8, y_range = 6.
... | The function `resetCNN_multiple_source` resets a reinforcement learning environment by initializing a map with buildings, positioning an agent (randomly or specified), placing radiation sources (randomly or specified with intensities), and generating a normalized state for a CNN. It validates positions to avoid buildin... | def resetCNN_multiple_source(self, buildings, current_location, source_location_list, source_intensity_list='random'):
'''Reset the game for the reinforcement learning algorithm
Paremeters
----------
self: class object
buildings: list(set(2-tuple)). A list of th... |
def get_backuppath(self):
'''get the file location where backups should be stored'''
backuppath = self.addon.getSetting("backup_path")
if not backuppath:
backuppath = xbmcgui.Dialog().browse(3, self.addon.getLocalizedString(32002),
'fi... | This code generates a dialog for managing skin backups, allowing users to create new backups, restore existing ones, or access settings. It lists sorted backup files, constructs UI elements, and triggers actions based on user selections, including recursive calls for continuous interaction. | def backuprestore(self):
'''show dialog with all options for skin backups'''
listitems = []
# create backup option
label = self.addon.getLocalizedString(32013)
listitem = xbmcgui.ListItem(label=label)
listitem.setArt({'icon': "defaultfolder.png"})
listitem.setPat... |
def get_backupfilename(self, promptfilename=False):
'''get the filename for the new backup'''
backupfile = "%s Skinbackup (%s)" % (
get_skin_name().capitalize(),
datetime.now().strftime('%Y-%m-%d %H.%M.%S'))
if promptfilename:
header = self.addon.getLo... | The main task of the code is to automatically back up skin settings if enabled, checking if a new day has passed since the last backup. If so, it generates a backup file, updates the last backup date, and cleans old backups, ensuring daily backups occur without user intervention. | def check_autobackup(self):
'''perform auto backup if enabled and needed'''
if self.addon.getSetting("auto_backups") == "true":
cur_date = datetime.now().strftime('%Y-%m-%d')
last_backup = self.addon.getSetting("last_backup")
if cur_date != last_backup and self.addon.... |
def get_all_possible_moves(self):
moves = []
for r in range(len(self.board)): #number of rows
for c in range(len(self.board[r])): #number of cols in a given row
turn = self.board[r][c][0]
if (turn == 'w' and self.whiteToMove) or (turn == 'b' and not self.white... | The code filters out invalid moves that leave the player's king in check by simulating each move, checking for check status, and removing invalid moves. It then determines if the game state is checkmate or stalemate based on the resulting move list, updating corresponding flags. The function returns the list of valid m... | def get_valid_moves(self):
moves = self.get_all_possible_moves()
for i in range(len(moves)- 1, -1, -1):
self.make_move(moves[i])
self.whiteToMove = not self.whiteToMove
if self.in_check():
moves.remove(moves[i])
self.whiteToMove = not self.... |
def train(corpus_path):
model = LogisticRegression()
corpus = [(tag_negation(snippet), label) for snippet, label in load_corpus(corpus_path)]
feat_dict = get_feature_dictionary(corpus)
X, Y = vectorize_corpus(corpus, feat_dict)
normalize(X)
model.fit(X, Y)
return model, feat_dict
def test(mo... | The code trains a model using 'train.txt', evaluates it on 'test.txt', and prints the test result. It then extracts and prints the top 5 most significant features from the model. | def main(args):
model, feature_dict = train('train.txt')
print(test(model, feature_dict, 'test.txt'))
weights = get_top_features(model, feature_dict, k=5)
for weight in weights:
print(weight) |
def load_training_corpus(proportion=1.0):
brown_sentences = brown.tagged_sents(tagset='universal')
num_used = int(proportion * len(brown_sentences))
corpus_sents, corpus_tags = [[]] * num_used, [[]] * num_used
for i in range(num_used):
corpus_sents[i], corpus_tags[i] = zip(*brown_sentences[i])
... | The code trains a logistic regression model for sequence tagging tasks (e.g., POS tagging) by extracting features from text corpora, removing rare features, converting data into numerical format, and fitting a classifier with balanced class weights. It returns the trained model and feature/tag mappings for prediction. | def train(proportion=1.0):
corpus_sents, corpus_tags = load_training_corpus(proportion)
# print(corpus_sents)
corpus_features = [[get_features(corpus_sents[i], j, corpus_tags[i][j-1] if j > 0 else '<S>')
for j in range(len(corpus_sents[i]))] for i in range(len(corpus_sents))]
cor... |
def load_test_corpus(corpus_path):
with open(corpus_path) as inf:
lines = [line.strip().split() for line in inf]
return [line for line in lines if len(line) > 0]
def get_predictions(test_sent, model, feature_dict, reverse_tag_dict):
n, T = len(test_sent[0]), len(reverse_tag_dict)
Y_pred = np.emp... | This function predicts sequence tags for a test corpus using a trained model. It loads test data, reverses the tag dictionary for decoding, applies the model to get predictions, uses the Viterbi algorithm to find optimal tag sequences, converts indices back to tags, and returns the predicted tag sequences for each sent... | def predict(corpus_path, model, feature_dict, tag_dict):
test_corpus = load_test_corpus(corpus_path)
reverse_tag_dict = {i: tag for tag, i in tag_dict.items()}
solution_tags = []
for sent in test_corpus:
sent = [sent]
Y_start, Y_pred = get_predictions(sent, model, feature_dict, reverse_t... |
def check_password():
"""Returns `True` if the user had a correct password."""
if "session_data" not in st.session_state:
st.session_state.session_data = {}
def login_form():
"""Form with widgets to collect user information"""
with st.form("Credentials"):
st.text_input(... | The main task of the code is to handle user authentication by checking the password, displaying a welcome message for authenticated users, providing a logout option, and redirecting users to either an admin page or an offense insertion process based on their role. It retrieves session data, verifies admin status, and e... | def main():
check_password()
username = st.session_state.session_data.get("username")
if username:
st.write(f"Welcome {username}")
if st.button("log_out", on_click=log_out):
log_out()
# Check if the username is an admin or a regular user
if is_admin(username):
... |
def _load_tokens(self, file: IOBase) -> None:
"""Normalizes all tokens and deletes empty strings
Args:
file (IOBase): opened source file
"""
for l in file:
tokens = [
t
for t in l.replace("\n", "").replace(",", "").lower().split(" "... | This code executes an assembler by reading a source file, parsing its tokens and resolving names, converting assembly code into binary data, and writing the resulting byte array to an output file. | def execute(self) -> None:
"""Executes the assembler"""
with open(self.source_file, "r") as fsrc:
self._load_tokens(fsrc)
self._find_names()
if self._lines_to_bin_step1():
self._resolve_names()
byte_arr = [0]
for line... |
def calculateSpeedPtr(row):
return math.sqrt(row.spd_x_bsm**2 + row.spd_y_bsm**2)
def calculateSpeedConf(row):
return math.sqrt(row.spd_x_noise_bsm**2 + row.spd_y_noise_bsm**2)
def calculateDistancePtr(row1,row2):
x_2 = (row1.pos_x_bsm-row2.pos_x_bsm)**2
y_2 =(row1.pos_y_bsm-row2.pos_y_bsm)**2
retu... | This code checks the consistency of position and speed data between two time points, ensuring they adhere to predefined constraints on time delta, acceleration, speed, and distance. It calculates trust factors using geometric and kinematic models, returning the minimum of computed factors to validate data plausibility. | def positionSpeedConsistancyCheck(row,oldRow):
MAX_TIME_DELTA = 3.1
MAX_MGT_RNG_DOWN = 6.2
MAX_MGT_RNG_UP = 2.1
MAX_PLAUSIBLE_ACCEL=2.6
MAX_PLAUSIBLE_DECEL = 4.5
MAX_PLAUSIBLE_SPEED=15
MAX_PLAUSIBLE_RANGE=420
speedDelta = calculateSpeedPtr(row) - calculateSpeedPtr(oldRow)
curSpe... |
def rangePlausibility(row1,row2):
MAX_PLAUSIBLE_RANGE=420
def helper(row1, row2):
x_2 = (row1.pos_x - row2.pos_x) ** 2
y_2 = (row1.pos_y - row2.pos_y) ** 2
return math.sqrt(x_2 + y_2)
distance = helper(row1,row2)
factor = CircleCircleFactor(distance,row1.pos_x_noise, row2.pos... | The function calculates plausibility metrics for vehicle data by merging GPS and BSM records, then computes range, position, speed, and heading consistency checks. It appends these as new features to the BSM DataFrame, returning a DataFrame with plausibility scores for each message. | def createPlausibilities(GPS_df,BSM_df):
"""
Extract the palusibilities and append to BSM_df for additional features
Args:
GPS_df:
BSM_df:
Returns:
"""
TOTAL_TIME=0
NUM_MESSAGES=0
MAX_PLAUSIBLE_RANGE = 420
# get all unique senders in session
all_senders = BSM... |
def parsePlausibilityRecords(plausibility_path):
vehicle_records= os.listdir(plausibility_path)
big_df = pd.DataFrame()
for vehicle_plausibility_record in vehicle_records:
vehicle_ID = vehicleIDfromPlausibility(vehicle_plausibility_record)
cur_file = os.path.join(plausibility_path,vehic... | The main task of the code is to parse simulation data from specified folders, merge plausibility records with vehicle trace data, clean the merged dataset by removing noise columns and resolving column conflicts, and export the final structured data as a CSV file to the designated output path. | def parseSim(data_folder,output_path):
folder_list = os.listdir(data_folder)
for folder in folder_list:
if "MDBsmsList" in folder:
plausibility_path = os.path.join(data_folder,folder)
if "VeReMi" in folder:
path_to_json = os.path.join(data_folder,folder)
plausibil... |
def extractFeaturesFromAllFiles(file_path):
"""
If needed, extract all the features and save to specific folders
"""
current_filenames = os.listdir(file_path)
for training_file in current_filenames: # create selected features
#if not 'veins' in training_file:
# continue
... | The code evaluates a pre-trained machine learning model on a test dataset by predicting labels, calculating accuracy, precision, and recall, and plotting a precision-recall curve. It loads features, aligns test data with the model's structure, and returns the model after evaluation. | def testModel(train_folder_path,test_folder_path,model=None):
if model == None:
model = pickle.load(open(train_folder_path + "trained_model.pkl", 'rb')) # if you have already trained model, use it
# extract features if not already extracted
if EXTRACT_FEATURES:
extractFeaturesFromAllFiles... |
def parsePlausibilityRecords(plausibility_path):
vehicle_records= os.listdir(plausibility_path)
big_df = pd.DataFrame()
for vehicle_plausibility_record in vehicle_records:
vehicle_ID = vehicleIDfromPlausibility(vehicle_plausibility_record)
cur_file = os.path.join(plausibility_path,vehic... | This function processes simulation data by parsing JSON files from specified folders, extracting plausibility records, merging them with BSM data, and exporting the cleaned results as a CSV file. | def parseSim(data_folder,output_path):
print("Current data folder: "+data_folder)
folder_list = os.listdir(data_folder)
plausibility_path = None
for folder in folder_list:
if "MDBsmsList" in folder:
plausibility_path = os.path.join(data_folder,folder)
if "VeReMi" in fo... |
def clear_data():
Match.objects.all().delete()
Competition.objects.all().delete()
Player.objects.all().delete()
Pass.objects.all().delete()
"""Deletes all the table data"""
print('Competition data cleared!')
def getSbCompetitionsDictionary():
sbCompetitions = sb.competitions()
sbCompeti... | The main task of the code is to parse command-line arguments, conditionally clear data if the --clearData flag is set, retrieve a sports competition dictionary, seed a competition model with it, and execute the main function of the seedLineups module to populate lineup data. | def main():
parser = argparse.ArgumentParser()
parser.add_argument("-clear", "--clearData", action='store_true', help="Delete all objects")
args = parser.parse_args()
if args.clearData:
clear_data()
sbCompetitionDict = getSbCompetitionsDictionary()
seedCompetitionModel(sbCompetition... |
def step(self, batch, batch_idx):
x,y = batch
z, x_hat, p, q = self._run_step(x)
recon_loss = F.mse_loss(x_hat, x, reduction='mean')
log_qz = q.log_prob(z)
log_pz = p.log_prob(z)
kl = log_qz - log_pz
kl = kl.mean()
kl *= self.kl_coeff
loss = kl... | The code performs a test step in a neural network model, calculating loss and logging metrics. It reconstructs input images, resizes original and reconstructed images for visualization, concatenates them, expands dimensions, and saves the combined image as 'img1.png' for comparison. | def test_step(self, batch, batch_idx):
loss, logs = self.step(batch, batch_idx)
self.log_dict({f"test_{k}": v for k, v in logs.items()}, on_step=True, on_epoch=False)
x, y = batch
z, x_hat, p, q = self._run_step(x)
orig = self.reduce_image(x,2)
recon = self.reduce_image(x... |
def get_screens(self, feature_screen, feature_minimap):
# shift dimensions => (channel, y, x)
feature_screen = torch.tensor(feature_screen).permute(2, 1, 0)
feature_minimap = torch.tensor(feature_minimap).permute(2, 1, 0)
# concat screens to one tensor
screens = torch.cat((feat... | The main task of the code is to implement a reinforcement learning agent's step function, which processes observations, manages reward accumulation, utilizes an experience replay buffer with a reward/non-reward gate mechanism, trains a neural network via optimization steps, updates target networks, adjusts exploration ... | def step(self, obs):
super(Agent, self).step(obs)
# combine features into one tensor
# screens = self.get_screens(obs.observation.feature_screen,
# obs.observation.feature_minimap)
screens = self.get_screens(obs.observation.rgb_screen,
... |
def connect(self):
# config file for queue db access
q_conf_file = os.path.join(os.path.abspath('.'), self.qdbfile)
# create handle to queue database (be sure it is running at the chosen address)
self.qdb = q_db.QueueDatabase(self.logger)
try:
self.qdb.read_config(q_... | This code initializes an object to manage astronomical observation scheduling. It sets parameters like observation grade, conditions, filters, and date ranges. It connects to a database, retrieves programs and observations, filters observable targets, builds dataframes, and prepares target objects with associated time ... | def __init__(self, grade, seeing, transp, filters, sdate, edate, maxOBquery, timewindow_obs,logger):
self.grade = grade
self.seeing = seeing
self.transp = transp
self.filters = filters
self.sdate = datetime(sdate.year, sdate.month,
sdate.day)+timede... |
def reset_the_game(self):
self.set_end_game(False)
self.reset_player_counter()
self.reset_question_number()
def check_end_game(self):
if self.end_game:
print(f"The Game is over. Player: '{self.cr_player.name}' "
f"your score is: '{self.cr_player.guess_counte... | The main task of the code is to initialize and run a game loop. It resets the game state, then repeatedly processes the next question until the game ends, determined by the `check_end_game()` method. The loop continues executing `next_question()` as long as the game is not over. | def start_the_game(self):
self.reset_the_game()
while not self.check_end_game():
self.next_question() |
def get_hitmask(image):
""" Returns a hitmask using an image's alpha. """
mask = []
for x in range(image.get_width()):
mask.append([])
for y in range(image.get_height()):
mask[x].append(bool(image.get_at((x, y))[3]))
return mask
def show_welcome_animation():
""" Shows wel... | The main task of the code is to initialize a Flappy Bird game by setting up the display, loading assets (images, sounds), and managing game states. It randomly selects visual elements, prepares collision detection masks, and orchestrates the welcome animation, main gameplay, and game-over screens through function calls... | def main():
global SCREEN, FPSCLOCK
pygame.init()
FPSCLOCK = pygame.time.Clock()
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Flappy Bird')
# numbers sprites for score display
IMAGES['numbers'] = (
pygame.image.load(ASSETS_DIR + '/sprit... |
def calculate_score(inputfile):
'''find the score after trying strategy'''
score = 0
with open(inputfile, encoding='utf-8') as fh:
for line in fh:
first, second = line.split()
score += wincheck(translate_hand(first), translate_hand(second)) + valcheck(translate_hand(second))... | The code's main task is to calculate and print game scores from input files, check win conditions, and validate moves. It processes './input/input1.txt', computes scores using calculate_score and calculate_score2, and evaluates outcomes with wincheck2 and valcheck2 functions, which likely assess game rules and move val... | def main():
'''do main()'''
examplefile = './input/example.txt'
inputfile = './input/input1.txt'
print(calculate_score(inputfile))
print(wincheck2('B', 'Z')+ valcheck2(translate_hand('B'),'Z'))
print(calculate_score2(inputfile)) |
def processorCheck():
import platform
if "amd" in (str(platform.processor())).lower():
print("Caution! Your processor may not work as intended.")
print("Refer to the README for info on how to fix this.")
else:
return()
def liveDeviceCheck(lType):
processorCheck()
import sound... | This function handles audio input routing based on parameters. It checks the current directory, validates input sources (device or file), and processes audio using either microphone input (dpMic) or file input (dpFile) functions, with error handling for invalid device/file combinations and directory adjustments. | def livebridge(filename, inputDevice, dtype, device1, device2):
processorCheck()
import os, threading, sys, sounddevice, pyaudio
if ("xavi" in os.getcwd()):
os.chdir('..')
if filename == 'livebridge' and inputDevice == 'blank':
print("When selecting a device, use the device number.")
... |
def is_open(x, y, seed):
number = x*x + 3*x + 2*x*y + y + y*y + seed
return bin(number).count('1') % 2 == 0
def render(x, y, previous, options, goal, seed):
w, h = 120, 30
sleep(0.3)
r = lambda x: round(x/30)*30
draw_room(r(x-w//2), r(y-h//2), r(x+w//2), r(y+h//2), seed, {
'▓': ((x, y),)... | This function recursively finds the shortest path from a start position to a goal in a grid, avoiding previously visited positions. It explores valid moves in four directions, prioritizes closer points via distance sorting, and returns the path length if a valid route exists, otherwise None. | def find_shortest_path(goal, seed, start=(1, 1), previous=tuple()):
sx, sy = start
options = [(sx+x, sy+y) \
for x, y in ((0, 1), (0, -1), (1, 0), (-1, 0)) \
if is_open(sx+x, sy+y, seed) and \
(sx+x, sy+y) not in previous]
render(*start, previous, options, go... |
def startScreen(self):
""" Start screen animation"""
pad = curses.newpad(1, 70)
self.stdscr.refresh()
pad.addstr("Welcome to the Nearly Impossible Chessboard Puzzle.")
for i in range(50):
try:
key = self.stdscr.getch()
if key != -1:
... | The code initializes a game by checking terminal size requirements, setting up color pairs for display, configuring the screen for non-blocking input, and sequentially launching game components like the start screen, player mode selection, context explanation, board display, and puzzle gameplay. | def start(self, stdscr):
""" Game starts here"""
if os.get_terminal_size().lines < TERMINAL_SIZE_REQUIREMENTS[0] or os.get_terminal_size().columns < TERMINAL_SIZE_REQUIREMENTS[1]:
print(os.get_terminal_size())
stdscr.addstr("Please resize your terminal window to a larger size and... |
def locate_square(self,pos):
for i in range(8):
for z in range(8):
if (self.squaregrid[i][z].rect.collidepoint(pos)):
return self.squaregrid[i][z]
def highlight_squares(self,highlight_list):
for x in highlight_list:
row = x[0]
c... | This code handles player clicks on a chessboard to select and move pieces, validate legal moves, manage en passant captures, check for checkmate, and update game state. It deselects pieces when clicking the same square, highlights legal moves, and reverts invalid moves while toggling turns. | def handle_click(self,pos):
clicked_square = self.locate_square(pos)
if (clicked_square.occupying_piece == '' and self.selected_piece is None):
print("Not a selectable square")
return
#Cancel move if the player selects the same square twice.
if self.selected_squ... |
def create_board(self):
# Create all the square objects first
blockSize = 90
color = WHITE
column = 0
for x in range(0, WIDTH, blockSize): # x coordinate
color = self.flip_color(color)
row = 0
column = column + 1
for y in range(... | This method initializes a new chess game by resetting game state variables, setting up the standard chessboard with piece positions, creating game elements, and preparing the game for play. It initializes the board, turns, sprites, and starts the game loop. | def new_game(self):
self.selected_piece = None
self.selected_square = None
self.white_king_square = None
self.black_king_square = None
self.game_over = False
self.all_sprites = pygame.sprite.LayeredUpdates()
self.turn = 'w'
#representation of the current b... |
def on_check(cmd):
global message
if on_off[command_names.index(cmd)] != "f" and not active[command_names.index("protect")]:
return True
elif DISABLED_MSG == "t":
sendMessage(irc, "/me @"+user+" Command '"+command_names[command_names.index(cmd)]+"' is disabled.")
message = ""
... | The `gamecontrol()` function processes user commands to modify game mechanics, applying effects like movement adjustments, visual changes, and ability activations. It checks command validity, cooldowns, and parameters, then executes corresponding actions via `sendForm`, `activate`, or `deactivate`. It manages durations... | def gamecontrol():
global message
while True:
#split a whole message into args so we can evaluate it one by one
args = message.split(" ")
if PREFIX + "protect" == str(args[0]).lower() and on_check("protect") and cd_check("protect"):
activate("protect")
... |
def try_kill_process(process_name):
if process_exists(process_name):
os.system("taskkill /f /im " + process_name)
def try_remove_dir(dir):
if exists(dir):
shutil.rmtree(dir)
def try_remove_file(file):
if exists(file):
os.remove(file)
def replaceText(path, search_text, replace_text):
... | The main task of the code is to check for updates of a mod from a GitHub repository, download and install the latest version if necessary, and launch the game with the updated mod. It compares the local installation's last modified date with the latest GitHub commit or release, handles ISO data extraction, migrates set... | def launch(URL, MOD_ID, MOD_NAME, LINK_TYPE):
if URL is None:
return
# start of update check method
# Github API Call
launchUrl = URL
if LINK_TYPE == githubUtils.LinkTypes.BRANCH:
launchUrl = githubUtils.branchToApiURL(URL)
print("\nlaunching from " + launchUrl)
PARAMS = {"... |
def maximizeUCB(node):
childrenStatesList = node.children
maxUCB = -inf
for state in childrenStatesList:
tmpChildNode = Utils.mcts[state]
tmpUCB = ucb(node, tmpChildNode)
if tmpUCB > maxUCB:
maxChildState = state
maxChildNode = tmpChildNode
ma... | This function performs a Monte Carlo Tree Search (MCTS) traversal. It selects child nodes using UCB scoring, expands unvisited nodes by generating child states, simulates outcomes through rollouts, and backpropagates results to update node statistics. The process explores the game tree to improve decision-making by pri... | def treeTraversal(state):
node = Utils.mcts[state]
# This state is a terminal state, so no need to traverse this state
if node.isTerminal:
return
Utils.currentNumericalAIPosition = node.numericalAIPosition
Utils.currentNumericalUserPosition = node.numericalUserPosition
# Chec... |
def set_unlimited_quotas(config):
client = _get_osclient(config)
client.set_project_quota(networks=-1, subnets=-1, ports=-1)
def create_resources(config):
hostname = get_node_name(config)
client = _get_osclient(config)
os_vif = os_vif_client.OSVifClient()
workers = get_number_of_workers(config)... | The main task of the code is to execute resource management actions based on command-line arguments. It reads configuration parameters, determines the specified action (CREATE, CLEAN, or DISCOVER_HOSTS), and performs corresponding operations: creating resources, cleaning them, or generating an inventory file. If the ac... | def main(argv=sys.argv[1:]):
config = conf.get_config(argv)
if config.action == constants.CREATE:
LOG.info("Starting resource creation")
set_unlimited_quotas(config)
create_resources(config)
LOG.info("Resources created")
elif config.action == constants.CLEAN:
LOG.info... |
def print_player_position(self):
print('Player at:', self.playerPosition)
def get_player_cell(self):
return self.get_cell_at(self.playerPosition[0], self.playerPosition[1])
def advance(self):
# print('--- MOVE START ---')
direction_for_next_step = self.calculate_direction_for_next_step()... | The main task of the code is to simulate a player moving in a specific direction until reaching an exit. It starts by printing initial status, checks if the current cell is an exit, and repeatedly advances the player in the current direction until the exit is reached, finally announcing success. | def run(self):
print('Let\'s start')
self.print_player_position()
print('Starts going to:', self.currentDirection)
result = self.get_player_cell().is_exit()
while not result:
self.advance()
result = self.get_player_cell().is_exit()
print('WE REACH ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.