dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def CheckPlayerPoints(player:Player):
isEnoughPoint:bool = True
if player.points < Settings.POINTS_TO_START.value:
# Check enough points to start?
print("You need at least 30 point to start!")
print("Restarting the game to reset points!")
print("Game Closed! Goodbye!")
i... | The main task of the code is to manage a game loop where a player and house take turns receiving cards, determine round outcomes, and track points. It initializes game conditions, deducts starting costs, and iteratively processes rounds until the player chooses to stop, updating scores and handling game flow accordingl... | def StartNewGame(player:Player,house:House,desk:Desk):
# Start Game
isEnoughPointToStart:bool = CheckPlayerPoints(player)
if isEnoughPointToStart == False:
return Options.STOP.value
roundNum = 1
player.points -= Settings.POINTS_PAY_FOR_FIRST_ROUND.value
house.reward = Settings.REWARD_POI... |
def traverse(self, current_node: Node, expand_list: list) -> Node:
# children = self.get_children(current_node)
# unvisited_node = None
# best_uct_node = None
# for child in children:
# if current_node.parent is not None:
# if child == current_node.parent:
... | This function performs Monte Carlo Tree Search (MCTS) on a given root node, iteratively selecting, expanding, simulating, and backpropagating results within a 5-second timeout. It evaluates child nodes using UCT values to determine the optimal next move, returning the child with the highest UCT score. The process track... | def monte_carlo_tree_search(self, root: Node) -> Node:
# visited_list = []
# timeout = 5
# timeout_start = time.time()
# #for x in range(10):
# while time.time() < timeout_start + timeout:
# leaf = self.traverse(current_node, visited_list) # Selection
# i... |
def stft(y, win_length=640, hop_length=160):
fft_window = signal.windows.hann(win_length, False)
# Window the time series.
n_frames = 1 + (len(y) - win_length) // hop_length
frames = [y[s:s + win_length] for s in np.arange(n_frames) * hop_length]
stft_matrix = np.fft.fft(fft_window * frames, axis=... | The main task of the code is to change the playback rate of an audio signal by modifying its spectrogram. It resizes each frequency bin's time-domain representation using a given ratio, then reconstructs the altered audio via inverse STFT. This adjusts the temporal resolution of the spectrogram, effectively stretching ... | def resize_spectrogram(data, ratio):
'''
change the rate by changing the spectogram
:param data: 1D ndarray of dtype float64 representing the original sample points
:param ratio: positive float64 representing the rate change of the WAV file
:return:
'''
spec = stft(data)
new_spec = np.z... |
def build_laplacian_pyramid(im, max_levels, filter_size):
"""
construct a laplacian pyramid
:param im: a grayscale image
:param max_levels: the maximal number of levels in the resulting pyramid.
:param filter_size: the size of the Gaussian filter
:return: laplacian pyr... | The code performs pyramid blending of two images using a mask. It constructs Laplacian pyramids for both input images and a Gaussian pyramid for the mask. The mask determines the contribution of each image at each pyramid level, with the final blended image reconstructed by combining the weighted Laplacian layers. | def pyramid_blending(im1, im2, mask, max_levels, filter_size_im, filter_size_mask):
"""
blend 2 picture together with the provide mask
:param max_levels: number of levels in the pyrmaid we will create
:param filter_size_im: size of the filter
:param filter_size_mask: size of the filter
:return: ... |
def build_laplacian_pyramid(im, max_levels, filter_size):
"""
construct a laplacian pyramid
:param im: a grayscale image
:param max_levels: the maximal number of levels in the resulting pyramid.
:param filter_size: the size of the Gaussian filter
:return: laplacian pyr... | The function performs pyramid blending of two images using a mask. It constructs Laplacian pyramids for both images and a Gaussian pyramid for the mask, then combines the pyramids by weighting each level with the mask. The final blended image is reconstructed from the combined Laplacian pyramid, allowing seamless integ... | def pyramid_blending(im1, im2, mask, max_levels, filter_size_im, filter_size_mask):
"""
blend 2 picture together with the provide mask
:param max_levels: number of levels in the pyrmaid we will create
:param filter_size_im: size of the filter
:param filter_size_mask: size of the filter
:return: ... |
def read_image(filename, representation):
"""
Reads an image file in a given representation and returns it.
"""
im = imageio.imread(filename)
if representation == 2:
return im/255
else:
im = rgb2gray(im)
return im/255
def relpath(filename):
return os.path.join(os.pat... | The code demonstrates image blending by combining two images using a mask. It loads 'barbie.jpg' and 'terminator.jpg', applies a mask from 'termask2.jpg', and blends them with specified parameters. The result is visualized alongside the original images and mask, showcasing the blending technique's effect. | def blending_example1():
"first blend example"
im1 = read_image(relpath("externals/barbie.jpg"), 2)
im2 = read_image(relpath("externals/terminator.jpg"), 2)
mask = read_image(relpath("externals/termask2.jpg"), 1).astype(np.bool)
im_blend= blend(im2,im1,mask.astype(np.float64),9, 9, 5)
plt.figu... |
def read_image(filename, representation):
"""
Reads an image file in a given representation and returns it.
"""
im = imageio.imread(filename)
if representation == 2:
return im/255
else:
im = rgb2gray(im)
return im/255
def relpath(filename):
return os.path.join(os.pat... | The code demonstrates image blending by combining two input images (im1 and im2) using a binary mask. It visualizes the original images, the mask, and the blended result in a 2x2 subplot layout. The blend function applies a weighted combination of the images based on the mask, with parameters 9,9,5 likely controlling b... | def blending_example2():
"second blend example"
im1 = read_image(relpath("externals/simba.jpg"), 2)
im2 = read_image(relpath("externals/sefertora.jpg"), 2)
mask = read_image(relpath("externals/mask_sefertora.jpg"), 1).astype(np.bool)
im_blend= blend(im2,im1,mask.astype(np.float64),9,9,5)
plt.fi... |
def multicast(msg):
global node_socket_dict
global num_connected_nodes
global sleep_time
global local_name
global num_bytes_send
# print(local_name ," start multicast :",msg.getID(),msg.getPriority(),msg.getSender())
json_msg = msg.get_message_string()
num_connected_nodes_lock.acquire()
... | The code handles incoming messages by receiving data from a socket, parsing JSON-formatted messages, checking for duplicates using a global repository, updating message priority based on local name and timestamp, and multicasting valid messages. It ensures reliable message delivery, tracks message IDs and senders, and ... | def handle_receive(new_socket):
global received_repo
global msgID_repo
global timeStamp
global msgSender_dict
global local_name
global sleep_time
global num_bytes_recv
global msg_tracker
# print("handle_receive enter")
while True:
# receive message
raw_data = new_... |
def beginExportSection(self, file, section):
self.writeUnsignedInt(file,section)
size_location = file.tell()
self.writeUnsignedInt(file,0)
return size_location
def writeUnsignedInt(self, file, value):
b = struct.pack("!I",value)
file.write(b)
def writeMeshUVs(self, file, uvs, vertices, uv_set):
size_l... | This function writes UV set data for a mesh to a file, handling up to two UV sets. It writes the count of UV sets, then iterates through each set (capped at 2) to export UV coordinates using writeMeshUVs, while managing file section boundaries with beginExportSection and endExportSection. | def writeMeshUVSets(self, file, uv_sets, vertices):
num_uv_sets = len(uv_sets)
if num_uv_sets == 0:
return
size_location = self.beginExportSection(file, MESHES_MESH_UV_SETS)
# write uvs
self.writeUnsignedInt(file, num_uv_sets)
print("Writing uv set: %i" % num_uv_sets)
if num_uv_sets > 2:
... |
def beginExportSection(self, file, section):
self.writeUnsignedInt(file,section)
size_location = file.tell()
self.writeUnsignedInt(file,0)
return size_location
def writeMeshJoints(self, file, jointNames):
size_location = self.beginExportSection(file, MESHES_MESH_SKINNING_JOINTS)
# write normals
sel... | The code writes mesh skinning data to a file, including joints and their influence weights, if provided. It checks for empty joint names, initializes an export section, writes joint names and weights via helper methods, then finalizes the section. | def writeMeshSkinning(self, file, jointNames, weights):
if (len(jointNames) <= 0):
return
size_location = self.beginExportSection(file, MESHES_MESH_SKINNING)
self.writeMeshJoints(file, jointNames)
self.writeMeshInfluences(file, weights)
self.endExportSection(file, size_location) |
def beginExportSection(self, file, section):
self.writeUnsignedInt(file,section)
size_location = file.tell()
self.writeUnsignedInt(file,0)
return size_location
def writeSkeletonJoints(self, file, bones, parent, indent):
#print("Writing %i bones" % len(bones) )
self.writeUnsignedInt(file, len(bones) )
... | This code exports a 3D skeleton structure from a list of objects to a file. It first verifies there's only one armature in the selection, then writes the skeleton's bone hierarchy starting from root bones, ensuring proper exporting of the skeletal data structure. | def writeSkeleton(self, file, objects_list, options):
# count the armatures in our selection
skeletonCount = 0
for obj in objects_list:
if obj.type == 'ARMATURE':
skeletonCount = skeletonCount + 1
if (skeletonCount > 1):
print("Error: Cannot export more than one skeleton")
return
#
... |
def beginExportSection(self, file, section):
self.writeUnsignedInt(file,section)
size_location = file.tell()
self.writeUnsignedInt(file,0)
return size_location
def writeUnsignedInt(self, file, value):
b = struct.pack("!I",value)
file.write(b)
def writeString(self, file, value):
for c in value:
self.... | This function exports animation tracks for each bone in a 3D object. It writes the number of pose bones, their names, and individual animation data to a file. The process begins by marking the animation tracks section, iterates through each bone to write its name and corresponding keyframe data, then finalizes the sect... | def writeTracks(self, scene, file, obj, keyframes):
size_location = self.beginExportSection(file, ANIMATION_TRACKS)
posebones = obj.pose.bones
self.writeUnsignedInt(file, len(posebones))
for posebone in posebones:
print("Bone: %s" % posebone.name)
self.writeString(file, posebone.name)
self.writeTr... |
def beginExportSection(self, file, section):
self.writeUnsignedInt(file,section)
size_location = file.tell()
self.writeUnsignedInt(file,0)
return size_location
def writeMeshName(self, file, name):
size_location = self.beginExportSection(file, MESHES_MESH_NAME)
# write string
print("Writing name: %s... | This code writes a triangular mesh's data to a file, including its name, vertices, normals, UV coordinates, skinning information, and face indices. It structures the mesh data within a defined section using helper methods for each component, ensuring proper formatting during export. | def writeMesh(self, file,tri_mesh):
size_location = self.beginExportSection(file, MESHES_MESH)
#
# write out mesh parts
#
self.writeMeshName(file, tri_mesh.name)
self.writeMeshPositions(file,tri_mesh.vertices)
self.writeMeshNormals(file, tri_mesh.normals, tri_mesh.vertices)
self.writeMeshUVSets(file... |
def beginExportSection(self, file, section):
self.writeUnsignedInt(file,section)
size_location = file.tell()
self.writeUnsignedInt(file,0)
return size_location
def writeUnsignedInt(self, file, value):
b = struct.pack("!I",value)
file.write(b)
def writeFloat(self, file, value):
b = struct.pack("!f",va... | This function exports animation data from a Blender object to a file. It checks for animation/action data, collects keyframes based on frame range and options, writes FPS and normalized time values, and exports animation tracks. It resets the scene frame after processing. | def writeAnimation(self, scene, file, obj, options):
cur_frame = scene.frame_current # Remember current frame
print ('Start Frame: %i, End Frame: %i' % (scene.frame_start, scene.frame_end))
print ('Frames Per Sec: %i' % scene.render.fps)
if obj.animation_data == None:
print("No animation data")
ret... |
def beginExportSection(self, file, section):
self.writeUnsignedInt(file,section)
size_location = file.tell()
self.writeUnsignedInt(file,0)
return size_location
def writeUnsignedInt(self, file, value):
b = struct.pack("!I",value)
file.write(b)
def writeMesh(self, file,tri_mesh):
size_location = self.be... | This function exports mesh data from selected objects into a file. It counts meshes, writes their count, handles armature bind poses if enabled, processes each mesh (applying modifiers if specified), triangulates, optimizes if needed, then writes each mesh to the file using helper methods for section management. | def writeMeshes(self, scene, file, objects_list, options):
size_location = self.beginExportSection(file, MESHES)
# count the meshes in our selection
meshCount = 0
for obj in objects_list:
if obj.type == 'MESH':
meshCount = meshCount + 1
#
# Meshes header
#
self.writeUnsignedInt(file... |
def writeUnsignedInt(self, file, value):
b = struct.pack("!I",value)
file.write(b)
def beginExportSection(self, file, section):
self.writeUnsignedInt(file,section)
size_location = file.tell()
self.writeUnsignedInt(file,0)
return size_location
def writeAnimation(self, scene, file, obj, options):
cur_f... | The main task of this code is to export animation data from armature objects in a 3D scene to a binary file. It writes a header with magic number and version, then processes each armature in the objects list to export its animation data using `writeAnimation`, organizing the file structure with section markers for size... | def writeScene(self, scene, filepath, objects_list, options):
print("running writeScene to : %s " % filepath)
file = open(filepath, 'wb')
self.writeUnsignedInt(file,MAGIC)
self.writeUnsignedInt(file,VERSION)
size_location = self.beginExportSection(file, FILE)
#
# Animations header
#
f... |
def writeUnsignedInt(self, file, value):
b = struct.pack("!I",value)
file.write(b)
def beginExportSection(self, file, section):
self.writeUnsignedInt(file,section)
size_location = file.tell()
self.writeUnsignedInt(file,0)
return size_location
def writeMeshes(self, scene, file, objects_list, options):
s... | The main task of the code is to export a 3D scene to a binary file by writing mesh and skeleton data along with metadata (magic number and version). It opens a file, writes headers, exports mesh and skeleton information via helper methods, and closes the file, returning a completion status. | def writeScene(self, scene, filepath, objects_list, options):
print("running writeScene to : %s " % filepath)
file = open(filepath, 'wb')
self.writeUnsignedInt(file,MAGIC)
self.writeUnsignedInt(file,VERSION)
size_location = self.beginExportSection(file, FILE)
print("********************")
print... |
def clear_table_data(table: str):
"""
function clears all table data
assumption: table exists
"""
sql = (
f'TRUNCATE TABLE {table}'
)
mycursor.execute(sql)
mydb.commit()
def get_active_machines() -> list:
"""
function returns the active machines that having records in [te... | The function updates the [operation], [quantity], and [utilization] tables with laser activity data from the last specified hours. It processes activity logs to identify active periods, using a 10-second inactivity threshold to determine idle time. Temporary tables are cleared first, and metadata is aggregated to track... | def update_operation_of_last_hours(hours: int):
"""
function updates the [operation] table with [activity] from the last hours
this is a helper function to ease on queries later that scan the [activity] table
and extracts the time where laser was active based on assumption that if a laser
is idle fo... |
def generate_points(
loc_1: tuple[float,float] = (0,0),
loc_2: tuple[float,float] = (6,6),
prop_of_labels: float = 0.01,
n: int = 1000):
# generate two clusters of points
n_labeled = int(n*prop_of_labels)
cluster_1 = np.array(
[np.random.normal(loc=loc_1[0], size=n//2),
np.ra... | The code performs gradient descent on labeled and unlabeled data using a specified method ('bcgdr'), either loading pre-saved data or generating new data (random or real, like Iris). It initializes unknown labels, runs optimization, tracks accuracy over iterations, and saves results (histories, plots) for analysis. | def main():
# 'new_rand', 'new_real', 'load'
data = 'load'
save = True
# Choose method
m = 'bcgdr'
# initialize points
if data == 'load':
x_l = np.loadtxt('x_l.txt')
x_u = np.loadtxt('x_u.txt')
sim_l = np.loadtxt('sim_l.txt')
sim_u = np.loadtxt('sim_u.txt')
... |
def _setup_parser():
"""Set up Python's ArgumentParser with data, model, trainer, and other arguments."""
parser = argparse.ArgumentParser(add_help=False)
# Add Trainer specific arguments, such as --max_epochs, --gpus, --precision
trainer_parser = pl.Trainer.add_argparse_args(parser)
trainer_parser... | The code runs an active learning experiment using different sampling techniques (ratio, margin, least, entropy, random) on datasets like MNIST or EMNIST. It loads a pre-trained model checkpoint, configures data and model classes based on command-line arguments, and executes the experiment with specified parameters (e.g... | def main():
"""
Run an experiment.
Sample command:
```
python training/run_experiment.py --max_epochs=3 --gpus='0,' --num_workers=20 --model_class=MLP --data_class=MNIST
```
"""
n_samples = 5000
add_random = int(1*n_samples)
sampling_technique_list = ['ratio', 'margin', 'least',... |
def _connect_to_db(db_name):
connect = mysql.connector.connect(
host=HOST,
user=USER,
password=PASSWORD,
database=db_name,
port=PORT,
auth_plugin="mysql_native_password",
)
return connect
def distinguish_direction(direction):
if str(direction).lower() == "... | This function handles the insertion or updating of truck weigh-in/weigh-out records in a database. It determines the appropriate database operation (insert/update) based on the truck's direction (in/out), checks for existing entries to avoid duplicates, manages session IDs for tracking, and enforces rules like requirin... | def post_weight(direction, truck, containers_id, truck_weight, unit, force, produce):
db = _connect_to_db(DATABASE)
cur = db.cursor()
now = datetime.now()
timestamp = now.strftime("%Y-%m-%d %H-%M-%S")
column = distinguish_direction(direction)
insert_transactions = ""
last_direction, last_... |
def sanitize_tags(tags):
tags = tags.lower()
tags = tags.rstrip()
tags = tags.replace(" ", "_")
return urllib.parse.quote(tags)
def generate_link(tags):
global danbooru
global nsfw_filter
link = danbooru + "/posts?tags=" + tags
if nsfw_filter == "nsfw":
rating = " rating:explicit... | The code scrapes images from Danbooru/Safebooru based on user-provided tags, applies an NSFW filter, collects image links from multiple pages, and downloads them using multiprocessing. It handles input validation, pagination, URL generation, and parallel image downloading with generated filenames and a dedicated direct... | def main():
global image_list
global danbooru
global nsfw_filter
print("Input tags: ", end="")
tags = input()
print("Input page: ", end="")
pages = int(input())
while True:
print("NSFW Filter[sfw|normal|nsfw]: ", end="")
nsfw_filter = input()
if nsfw_filter in ['... |
def gohan_ids_only_query(gohan_args, granularity):
config = current_app.config
query_url = config["GOHAN_BASE_URL"] + config["GOHAN_SEARCH_ENDPOINT"]
current_app.logger.debug(f"launching gohan query: {gohan_args}")
results = gohan_results(query_url, gohan_args)
return unpackage_sample_ids(results)
d... | This function handles Gohan API queries by routing requests based on parameters: returns IDs-only results if specified, full records for "record" granularity, or a count from a configured endpoint. It constructs URLs, logs queries, and processes results to return a count when neither IDs nor records are requested. | def generic_gohan_query(gohan_args, granularity, ids_only):
if (ids_only):
return gohan_ids_only_query(gohan_args, granularity)
if granularity == "record":
return gohan_full_record_query(gohan_args)
# count or boolean query follows
config = current_app.config
query_url = config["GO... |
def filenames_by_results_set(ids):
if not ids:
return {}
# payload for bento search that returns all experiment filenames in results
payload = {
"data_type": "phenopacket",
"query": ["#in", ["#resolve", "subject", "id"], ["#list", *ids]],
"output": "values_list",
"fi... | The function generates handover entries for given IDs by mapping each results set to a list of DRS-linked VCF files. It processes filenames, extracts links using `drs_link_from_vcf_filename`, filters valid links, and constructs handover entries. The output is a dictionary grouping these entries by results sets, enablin... | def handover_for_ids(ids):
# ideally we would preserve the mapping between ids and links,
# but this requires changes in katsu to do well
handovers = {}
files_for_results = filenames_by_results_set(ids)
for results_set, files in files_for_results.items():
handovers_this_set = []
f... |
def beacon_to_gohan_generic_mapping(obj):
gohan_query = {}
for beacon_key, beacon_value in obj.items():
if beacon_key in gohan_beacon_variant_query_mapped_fields.keys():
gohan_query[gohan_beacon_variant_query_mapped_fields[beacon_key]] = beacon_value
elif beacon_key in beacon_varian... | The function converts a sequence query from Beacon format to Gohan format by mapping parameters, validating required fields (alternateBases, referenceBases), setting bounds, and executing a generic Gohan query with specified granularity and sample ID options. | def sequence_query_to_gohan(beacon_args, granularity, ids_only):
print("SEQUENCE QUERY")
gohan_args = beacon_to_gohan_generic_mapping(beacon_args)
alternateBases = beacon_args.get("alternateBases")
if alternateBases is None:
raise InvalidQuery(
message="variant query requires either... |
def beacon_to_gohan_generic_mapping(obj):
gohan_query = {}
for beacon_key, beacon_value in obj.items():
if beacon_key in gohan_beacon_variant_query_mapped_fields.keys():
gohan_query[gohan_beacon_variant_query_mapped_fields[beacon_key]] = beacon_value
elif beacon_key in beacon_varian... | This function converts a range query from beacon format to gohan format by mapping parameters, adjusting bounds using zero_to_one normalization, and executing a generic gohan query with specified granularity and sample ID retrieval. | def range_query_to_gohan(beacon_args, granularity, ids_only):
print("RANGE QUERY")
gohan_args = beacon_to_gohan_generic_mapping(beacon_args)
gohan_args["lowerBound"] = zero_to_one(beacon_args["start"][0])
gohan_args["upperBound"] = zero_to_one(beacon_args["end"][0])
gohan_args["getSampleIdsOnly"] = ... |
def bracket_query_to_gohan(beacon_args, granularity, ids_only):
print("BRACKET QUERY")
# TODO
# either implement here by filtering full results, or implement directly in gohan
raise NotImplemented(message="variant bracket query not implemented")
def sequence_query_to_gohan(beacon_args, granularity, ids_... | The function `query_gohan` processes variant queries for a genome beacon, determining the query type (sequence, range, bracket, or gene ID) based on input parameters. It validates required fields like `referenceName` and routes the query to specialized helper functions (`bracket_query_to_gohan`, etc.) to convert and re... | def query_gohan(beacon_args, granularity, ids_only=False):
if beacon_args.get("referenceName") is None:
raise InvalidQuery(message="referenceName parameter required")
# control flow for beacon variant query types
# http://docs.genomebeacons.org/variant-queries/
start = beacon_args.get("start")... |
def _get_intermediate_node(self) -> Generator[Tuple[bytes, CID], None, None]:
"""
Generate intermediate file node blocks from raw node blocks.
Yields:
Generator[Tuple[bytes, CID], None, None]: Generator of block data and CIDs.
"""
pbnode, unixfs = self._get_pbnode(d... | The function constructs a Directed Acyclic Graph (DAG) by recursively aggregating file nodes into parent nodes, limited by `max_children` per layer. It calculates the required number of layers, iteratively combines node blocks, and returns the root CID along with the total layers, enabling hierarchical data structure c... | def _build_dag(self) -> Tuple[CID, int]:
"""
Generate the root node by building layers of file nodes.
Returns:
Tuple[CID, int]: The CID of the root node and the number of layers.
"""
parents = [(len(block), cid) for block, cid in self._get_intermediate_node()]
... |
def _build_dag(self) -> Tuple[CID, int]:
"""
Generate the root node by building layers of file nodes.
Returns:
Tuple[CID, int]: The CID of the root node and the number of layers.
"""
parents = [(len(block), cid) for block, cid in self._get_intermediate_node()]
... | The main task of the code is to generate the root node's CID for a CARv1 file, optionally including a name node with metadata. It builds a DAG, constructs a Protobuf node with file links, serializes it, and returns the file size and CID. If `with_name_node` is True, it creates a named node linking to the file's CID, in... | def _get_file_node(self, with_name_node=False) -> Optional[Tuple[int, CID]]:
"""
Get the root node for the CARv1 file.
Returns:
CID: The CID of the root node.
"""
if not self.file:
return None
file_cid = self._build_dag()
size = self.file.... |
def convert_prob(m):
for r in range(len(m)):
total = 0
for c in range(len(m[r])):
total += m[r][c]
if total != 0:
for c1 in range(len(m[r])):
m[r][c1] /= float(total)
return m
def RQ(m, term_state, non_term_state):
R = []
Q = []
... | The code calculates the absorption probabilities in an absorbing Markov chain by identifying terminal and non-terminal states, constructing transition matrices, solving for the fundamental matrix, and computing the probabilities of reaching terminal states from non-terminal states. | def solution(m):
# Use linear algebra formulation of absorbing Markov Chains
n = len(m)
if n==1:
if len(m[0]) == 1 and m[0][0] == 0:
return [1, 1]
term_state = []
non_term_state = []
for r in range(len(m)):
temp = 0
for c in range(len(m[r])):
if m[... |
def _make_mol_block_rational(mol_block):
""" Make molecule blocks passed parse successfully.
Note that although some missing lines and a molecule reading flag (M END) has been filled up,
for some unknown reasons, considerable molecule blocks can not be successfully recognized as expected.
I found that ... | The function converts an SDF-like file into a proper SDF format by repairing missing header lines, adding InChI/InChIKey properties, and separating valid/failed molecule blocks. It returns valid blocks, failed blocks, counts, and the maximum atom count in valid molecules, saving outputs to specified directories. | def convert_to_sdf(path_to_bad_sdf, failed_block_file_name=None, output_dir=None):
""" Make a sdf-like data file converted to sdf.
Note that to form a proper molecule block, some missing lines in header of original molecule string read from
sdf-like data files are filled up. Moreover, InChI will be taken t... |
def get_dataset_from_record(fnames,
hparams,
mode,
features_to_load=None,
all_data_in_one_batch=False):
"""Parse inputs from a tf.Record file containing molecular mass spec data.
Args:
fnames :... | This function validates that a NumPy array of spectra matches the corresponding data in a TFRecord file. It loads the TFRecord dataset, extracts features/labels, and compares each spectrum in the array with the dataset's values. If mismatches are found, it raises a ValueError, ensuring consistency between the stored Nu... | def validate_spectra_array_contents(record_path_name, hparams,
spectra_array_path_name):
"""Checks that np.array containing spectra matches contents of record.
Args:
record_path_name: pathname to tf.Record file matching np.array
hparams: See get_dataset_from_reco... |
def naive_bayes(training_file, development_file, counts):
"""Train a Naive Bayes classifier using length and frequency
features. Print out evaluation results on the training and
development data.
"""
clf = GaussianNB()
__my_classifier(training_file, development_file, counts,clf,True, True)
p... | The main task of the code is to execute and compare multiple text classifiers (Naive Bayes, Logistic Regression) on given training and development datasets, analyze their performance, and run a custom classifier implementation with analysis of mismatches. It orchestrates model training, evaluation, and result compariso... | def classifiers(training_file, development_file, counts):
print("\n========== Classifiers ===========\n")
print("Naive Bayes")
print("-----------")
naive_bayes(training_file, development_file, counts)
print("\nLogistic Regression")
print("-----------")
logistic_regression(training_file, de... |
def gen_dts(self, dts_path, test_args, initrd_start, initrd_end):
"""Create a DeviceTree source which will be compiled into a DTB and
passed to FVP for a test run."""
vm_args = join_if_not_None(self.args.vm_args, test_args)
write_file(dts_path, read_file(FVP_PREBUILT_DTS))
append... | The code's main task is to execute a test run by generating and compiling a device tree (DTS/DTB), configuring FVP execution with specified arguments, managing artifact files, logging UART outputs, and handling exceptions. It initializes run state, creates necessary files, computes memory addresses for initrd, compiles... | def run(self, run_name, test_args, is_long_running):
run_state = self.start_run(run_name)
dts_path = self.args.artifacts.create_file(run_name, ".dts")
dtb_path = self.args.artifacts.create_file(run_name, ".dtb")
uart0_log_path = self.args.artifacts.create_file(run_name, ".uart0.log")
... |
def get_test_json(self):
"""Invoke the test platform and request a JSON of available test and
test suites."""
out = self.driver.run("json", "json", self.force_long_running)
hf_out = "\n".join(self.extract_hftest_lines(out))
try:
return json.loads(hf_out)
excep... | The main task of the code is to run test suites matching specified regex patterns, collect test results, generate an XML log with timestamps, and return the count of run/failed tests. It writes results to a sponge log file, prints pass/fail status, and cleans up the driver. | def run_tests(self):
"""Run all suites and tests matching regexes given to constructor.
Write results to sponge log XML. Return the number of run and failed
tests."""
test_spec = self.get_test_json()
timestamp = datetime.datetime.now().replace(microsecond=0).isoformat()
... |
def checkReachPos(comp, boundary_inf, boundary_sup, jnt): # Check if the pos of a joint has reached a particular value
if comp == 'inf':
if getPos(jnt) <= boundary_inf:
return True
elif comp == 'sup':
if getPos(jnt) >= boundary_sup:
return True
elif comp == 'between':... | The code simulates robotic arm movements between pronation and supination positions, collects joint angle data, and generates tremors based on a Parkinson's disease coefficient. It sets motor parameters, moves to target positions, samples joint data, applies tremors when PD_state > 1, and analyzes the motion with time-... | def generateMovement():
global last_samp_t
global start_t
# Set ref speeds and accelerations
iPos.setRefSpeed(1, 10)
iPos.setRefAcceleration(1, 50)
iPos.setRefSpeed(4, 180)
iPos.setRefAcceleration(4,60)
iPos.setRefSpeed(5, 50)
iPos.setRefAcceleration(5,20)
# Set joints target... |
def tic_view():
tic_layout = [[sg.Text('Ur in trouble now, mister!')], [sg.Frame(
'Tic tac toe or die!', checkbox(9), font='Helvetica', title_color='Black')]]
tic_window = sg.Window('Tic tac toe bitch!', tic_layout)
return tic_window
def enter(arr, x, y, value):
if arr[x, y] != 'X' and arr[x, y]... | This code implements a Tic-Tac-Toe game where a player and AI alternate turns. It updates a 3x3 grid GUI, handles player moves (X), AI moves (O), checks win conditions, and closes the window when the game concludes with a win or draw. | def tic_selection():
tic_window = tic_view()
arr = np.zeros((3, 3), dtype=str)
while True:
event, values = tic_window.read()
if event == sg.WIN_CLOSED:
break
for k in range(1, 10):
if event == f"-BOX{k}-":
entry = enter(arr, (k-1) // 3, (k+2) %... |
def _check_exists(self):
return (os.path.exists(os.path.join(self.processed_folder,
self.training_file)) and
os.path.exists(os.path.join(self.processed_folder,
self.test_file)))
def read_image_file(path):
... | The main task of the code is to download the MNIST dataset if it doesn't already exist in the processed folder. It creates necessary directories, downloads raw data files from specified URLs, processes the image and label files, and saves them as PyTorch-compatible .pt files in the processed directory. The function ens... | def download(self):
"""Download the MNIST data if it doesn't exist in processed_folder already."""
if self._check_exists():
return
os.makedirs(self.raw_folder, exist_ok=True)
os.makedirs(self.processed_folder, exist_ok=True)
# download files
for url, md5 in... |
def _check_exists(self):
return (os.path.exists(os.path.join(self.processed_folder,
self.training_file)) and
os.path.exists(os.path.join(self.processed_folder,
self.test_file)))
def read_image_file(path):
... | The code downloads the MNIST dataset if not already present, creates necessary directories, extracts files, processes raw image/label data into PyTorch tensors, and saves them as processed `.pt` files for efficient loading. It checks for existing data, avoids redundant downloads, and ensures structured storage in speci... | def download(self):
"""Download the MNIST data if it doesn't exist in processed_folder already."""
if self._check_exists():
return
os.makedirs(self.raw_folder, exist_ok=True)
os.makedirs(self.processed_folder, exist_ok=True)
# download files
for url, md5 in... |
def get_article_date():
return datetime.strptime(get_metadata()['date'][0], app.config['DATE_FORMAT_EXTRACT'])
def get_article_title():
return get_metadata()['title'][0]
def get_article_summary():
return get_metadata()['summary'][0]
def get_article_tags():
return get_metadata()['tags']
def get_article_p... | The function retrieves a sorted list of recent articles, each containing metadata like date, title, summary, tags, and path. It sorts articles by date in descending order and returns either all articles (if quantity is -1) or the top 'quantity' number of articles. | def get_recent_articles(quantity=-1):
qto = slice(None) if quantity == -1 else slice(quantity)
return sorted(
({'date': get_article_date(),
'title': get_article_title(),
'summary': get_article_summary(),
'tags': get_article_tags(),
'path': get_... |
def __getActiveDrivePath(self):
command = 'net use'
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
drivePathText = ''
drivePathList = []
while True:
line = proc.stdout.readline()
drivePathText += str(line)
... | The main task of the code is to update the assignment table widget by retrieving active and custom drive paths, printing them for debugging, and passing these paths to a method that configures the table widget with the relevant data. | def __updateAssignment(self):
activeDrivePath = self.__getActiveDrivePath()
customDrivePath = self.__getCustomDrivePath()
print(activeDrivePath)
print(customDrivePath)
self.__setTableWidget(self.actionUi.assignmentTW, activeDrivePath, customDrivePath) |
def DEBUG(message=""):
if DEBUG_MODE:
print(message)
raw_input("Press Enter to continue...")
def move_to_table_point(self, table_point, end_effector_offset=EndEffectorOffset.CARD_GRIP,
direction='left', angle_deg=15, linear=True):
pose = geometry_msgs.msg.Pose()
... | The main task of the code is to execute a robotic card-dealing motion sequence by moving to specified target points, extracting cards from a shoe, sliding them to runways, and placing them accurately. It handles flipping cards if required, adjusting positions for proper alignment, and ensuring precise placement at desi... | def deal_cards(self, points, use_runway_list, flip_card_list):
"""Executes a card dealing motion sequence, dealing cards to the list of points specified. """
DEBUG()
pose_waypoints = []
for point, use_runway, flip in zip(points, use_runway_list, flip_card_list):
# Move to... |
def get_player_count(self):
count = 0
for player in self.player_list:
if player is not None:
count += 1
return count
def wait_for_bets(self):
self.game_status = GameStatus.WAITING_FOR_BETS
print("Waiting for bets.")
# self.bet_timer.start()
... | The main task of the code is to manage a Blackjack game loop, handling player interactions, card dealing, game state updates, and robotic actions for game mechanics. It waits for bets, deals cards, checks hand values, processes player inputs, determines winners, and resets game elements. Robotic actions include clearin... | def play_game(self):
while True:
if self.get_player_count() == 0:
rospy.sleep(0.5)
continue
self.wait_for_bets()
self.deal_initial_cards()
print("initial cards dealt")
while self.play_flag:
self.print... |
def deal_cards(self, points, use_runway_list, flip_card_list):
"""Executes a card dealing motion sequence, dealing cards to the list of points specified. """
DEBUG()
pose_waypoints = []
for point, use_runway, flip in zip(points, use_runway_list, flip_card_list):
# Move to... | This method executes action server callbacks by handling different task types. It processes DEAL, CLEAR, MOVE, and FLIP operations based on the goal's type, delegating to corresponding methods like deal_cards() or flip_card(). If the action type is unrecognized, it prints "NO ACTION". Finally, it marks the action as su... | def execute_callback(self, goal):
"""Execution callback for the action server."""
print("EXECUTE CALLBACK", goal.type)
if goal.type == ActionType.DEAL:
self.deal_cards(goal.card_points, goal.use_runway_list, goal.flip_card_list)
elif goal.type == ActionType.CLE... |
def testCellConv(self, num_cells=20):
assert(num_cells < (GRID_H - 1) * (GRID_W - 1))
color = [256, 0, 0]
x_locations = np.arange(1, GRID_W - 1) # Can't spawn on the borders
y_locations = np.arange(1, GRID_H - 1) # Can't spawn on the borders
# Generate random xy spawn coordinat... | The code simulates a game with neural network-based cells, running 100 iterations. It updates cell states, performs backpropagation to calculate losses, tracks training progress, and visualizes loss trends for active cells. The loop handles rendering, event processing, and periodic loss plotting to monitor neural netwo... | def startGame(self):
iterations = 100
pbar = tqdm(total=iterations)
itr = 0
self.testCellConv(num_cells=50)
running = True
while running:
print("iteration", itr)
CLOCK.tick(70) # Makes game run at 70 fps or slower
self.checkRep()
... |
def load_tsv(ticker_list):
df = pd.read_csv(ticker_list, sep='\t')
return df
def find_tickers(df):
patterns = [{"label": "BUY", "pattern": '(?i)buy'}, {"label": "SELL", "pattern": '(?i)sell'}, {"label": "STOCK", "pattern": '(?i)wish'}]
letters = '[A-Z]'
symbols = df.Symbol.tolist()
companies = d... | The main task of the code is to process financial data by loading ticker lists, analyzing text with spaCy for named entities, visualizing results with DisplaCy, counting entities, and saving outputs to a CSV file. The function orchestrates data loading, NLP processing, visualization, and storage, concluding with a comp... | def main(ticker_list, file, path):
# load index list
df = load_tsv(ticker_list)
# create trainer
find_tickers(df)
# load text
data = load_text(file, path)
# process with spacy
doc = load_doc(data)
# data visualization with DisplaCy
visual_doc(doc)
# save data to csv
ent_c... |
def web_driver(ticker):
global driver
driver_path = Service('C:/Users/suen6/.wdm/drivers/chromedriver/win32/98.0.4758.80/chromedriver.exe')
driver = webdriver.Chrome(service=driver_path, options=build_chrome_options())
driver.header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit... | The main task of the code is to scrape data from a web page using a specified filter option, organize it into a structured DataFrame, and save it as an Excel file with a timestamped filename. The function initializes a web driver, applies the filter, scrapes data across multiple pages, and exports the results to a spec... | def main(ticker, path, pages, filter_opt):
# create instance of web driver
web_driver(ticker)
# choose filter method in drop down list
select_reaction(filter_opt)
data = scrape_loop(pages)
driver.close()
headers = ['Index', 'Poster', 'Upvote', 'Downvote', 'Sentiment', 'Message']
date = d... |
def generate_path(numElements=12, gridSize=(16,16), imSize=(512,512),
D=32.0, jitterD=.25, B=32, jitterB=10,
startRadius=64, max_attempts=6):
'''just a wrapper around `_generate_path` to handle retries'''
found=False
for attempt in range(max_attempts):
try:
... | The code generates an image by placing Gabor-filtered textures along a computed path, with optional background elements. It creates a grid of positions, embeds Gabor patterns at path points, and randomly places background textures if enabled. Parameters control path geometry, texture orientation, and image properties, ... | def generate_path_image(imWidth=512,imHeight=512,numElements=12, D=32.0,
jitterD=.25,B=30, jitterB=10, startRadius=64,
randomize=False,background_present=True,alpha_offset=90,gridSize=(16,16),max_attempts=100,
gabor_lambda=8,gabor_phase=-90,gabor_st... |
def generate_path(numElements=12, gridSize=(16,16), imSize=(512,512),
D=32.0, jitterD=.25, B=32, jitterB=10,
startRadius=64, max_attempts=6):
'''just a wrapper around `_generate_path` to handle retries'''
found=False
for attempt in range(max_attempts):
try:
... | The code generates two images using Gabor filters: one with structured contour paths (aligned orientations) and a control image with randomized orientations. It creates a coherent contour pattern in `img_contour` and a scrambled version in `img_control`, both for texture discrimination tasks. | def generate_contour_control_pair_image(imWidth=512,imHeight=512,numElements=12, D=32.0,
jitterD=.25,B=30, jitterB=10, startRadius=64,
background_present=True,alpha_offset=90,gridSize=(16,16),max_attempts=100,
... |
def generate_path(numElements=12, gridSize=(16,16), imSize=(512,512),
D=32.0, jitterD=.25, B=32, jitterB=10,
startRadius=64, max_attempts=6):
'''just a wrapper around `_generate_path` to handle retries'''
found=False
for attempt in range(max_attempts):
try:
... | The code generates images using Gabor filters by placing oriented elements on a grid. It creates contour and control images with specific orientations, combining path-following elements and random background elements. The function returns generated images, element positions, angles, and a structured dictionary recordin... | def generate_everything(imWidth=512,imHeight=512,numElements=12, D=32.0,
jitterD=.25,B=30, jitterB=10, startRadius=64,
alpha_offset=90,gridSize=(16,16),max_attempts=100,
gabor_lambda=8,gabor_phase=-90,gabor_stddev=4.0,gabor_imSize=28,gabor_elCentre... |
def generate_period_boundaries(start_year, start_month, period_type, periods):
for i in range(periods):
yield( date(start_year, start_month, 1), period_end(start_year, start_month, period_type) )
start_year, start_month = next_period_start(start_year, start_month, period_type)
def account_from_path(... | This function extracts and summarizes expenses from a GNU Cash file for a specified year and quarter. It processes command-line arguments, initializes accounting periods, retrieves expense account data, calculates debit/credit totals, and outputs results in CSV format, including per-period and overall totals for each a... | def get_exps_qtr_main():
global gnucash_session
exe = argv[0].split('/')[-1]
if len(argv) < 4:
print("NOT ENOUGH parameters!")
print("usage: {} <book url> <year> <quarter>".format(exe))
print("PROGRAM EXIT!")
return
print("\nrunning {} at run-time: {}\n".format(exe, str(... |
def account_from_path(top_account, account_path, original_path=None):
# mhs | debug
# print("top_account = %s, account_path = %s, original_path = %s" % (top_account, account_path, original_path))
if original_path is None:
original_path = account_path
account, account_path = account_path[0], acco... | The main task of the code is to analyze Gnucash financial data by processing command-line parameters to extract account balances, debits, and credits over specified periods. It reads a Gnucash file, identifies target accounts, calculates transaction sums for each period, and outputs results in CSV format with period de... | def aa_sum_main():
global gnucash_session
exe = argv[0].split('/')[-1]
if len(argv) < 9:
print("NOT ENOUGH parameters!")
print("usage: {} <book url> <start year> <start month, numeric> <period type: 'monthly', 'quarterly', etc>".format(exe))
print("\t\t\t <number of periods to show, ... |
def list_maker(array):
"""
this function recursivly plays the prime game
"""
i = 0
while i < len(array):
value = array[i]
find_multiples(array, value)
i += 1
return array
def game(array, winner):
"""
this function recursivly plays the prime game
"""
f... | The function `isWinner` determines the winner of a prime-based game between two players, Ben and Maria. It processes a list of numbers, using primes up to the maximum value in the list. For each number, it evaluates game outcomes (using helper functions) and tallies wins. The winner is decided by comparing the counts o... | def isWinner(x, nums):
"""
This function is the main function of the prime game,
it returns who one.
"""
winner = []
if x < 1:
return None
primes = list_maker(list(range(2, max(nums) + 1)))
for i in nums:
winner.append(game(get_relevant_primes(primes, i), 'Ben'))
... |
def lamgrid(self,oversamp=1,lam1=0.8e-6,lam2=3.5e-6):
""" define a wavelength grid oversampled with respect to diffraction resolution
return the grid and associated detector position (wavelength solution)
"""
start_lam = self.lam
lam0=lam1
lam_grid=[lam0]
whi... | The function generates a spectral image by calculating the source spectrum, background, and optical losses (slitloss, allloss, strehl) across a wavelength range. It uses oversampling parameters, contamination thresholds, and channel selection to create a 2D image of light distribution, returning wavelength grids, spect... | def draw_spectrum(self,channel=1,oversamp=4,oversamp1=2,dzfac=0.,contamination=0.01):
"""
create an image of the spectrum between lam1 and lam2
oversamp is oversampling of PSF in units of lambda*F#
oversamp1 is oversampling of lambda grid relative to spectral FWHM
returns... |
def encrypt_password(self, login, passwd):
"""Encrypt the password using the google publickey, using
the RSA encryption algorithm"""
binaryKey = b64decode(config.GOOGLE_PUBKEY)
i = utils.readInt(binaryKey, 0)
modulus = utils.toBigInt(binaryKey[4:][0:i])
j = utils.readInt... | The code authenticates a Google account by either initializing a first-time login with email/password to obtain tokens or reusing existing gsfId/authSubToken for subsequent sessions. It encrypts passwords, sends POST requests to acquire AC2DM tokens, validates tokens via search, and handles errors like security checks ... | def login(self, email=None, password=None, gsfId=None, authSubToken=None):
"""Login to your Google Account.
For first time login you should provide:
* email
* password
For the following logins you need to provide:
* gsfId
* authSubToken"""
... |
def details(self, packageName):
"""Get app details from a package name.
packageName is the app unique ID (usually starting with 'com.')."""
path = "details?doc=%s" % requests.utils.quote(packageName)
data = self.executeRequestApi2(path)
return utils.fromDocToDictionary(data.payl... | The main task of the code is to download an already purchased Android app (APK) and its optional expansion files (main/patch) from Google Play using the delivery API. It constructs a request with parameters like package name, version code, and download token, handles authentication, and returns a dictionary with downlo... | def delivery(self, packageName, versionCode=None, offerType=1,
downloadToken=None, expansion_files=False):
"""Download an already purchased app.
Args:
packageName (str): app unique ID (usually starting with 'com.')
versionCode (int): version to download
... |
def details(self, packageName):
"""Get app details from a package name.
packageName is the app unique ID (usually starting with 'com.')."""
path = "details?doc=%s" % requests.utils.quote(packageName)
data = self.executeRequestApi2(path)
return utils.fromDocToDictionary(data.payl... | The main task of the code is to download an Android app (APK) from Google Play, requiring user authentication and a purchase for free apps. It retrieves the latest version if unspecified, obtains a download token via a purchase request, and then uses the `delivery` method to fetch the APK data, optionally including exp... | def download(self, packageName, versionCode=None, offerType=1, expansion_files=False):
"""Download an app and return its raw data (APK file). Free apps need
to be "purchased" first, in order to retrieve the download cookie.
If you want to download an already purchased app, use *delivery* method.... |
def Authentication_Attack_State2():
global Final_Statement
response1 = input("Is the attacker able to compromise the home network after compromising the home network? " + Yes_or_No + " ")
if (response1 == "yes" or response1 == "y" or response1 == "Yes" or response1 == "YES" or response1 == "Y"):
... | This function simulates an authentication attack simulation where the user selects between two attack paths (Home Wi-Fi or IoT App). It tracks attempted options, checks success/failure responses, updates a global status log, and transitions to subsequent states (State2/State3) or re-runs if options remain. If all optio... | def Authentication_Attack_State1():
global Final_Statement
if(Dict_of_State_1_options_exhausted == Dict_of_State_1_options): #if all options have been attempted, give failure message
print("\n"+Final_Statement + Failure)
else: #if options to proceed are still possible
print("... |
def Confidentiality_Attack_State3():
global Final_Statement
response1 = input("Did the attacker succeed in connecting directly to the IoT application (via mobile data)? " + Yes_or_No + " ")
if (response1 == "yes" or response1 == "y" or response1 == "Yes" or response1 == "YES" or response1 == "Y"):
... | The function simulates an attacker's attempt to bypass confidentiality measures by offering three options (Public Wi-Fi, Dongle/router, IoT App). It tracks attempted options, validates user input, and branches to subsequent states (State 3/4/5) or failure based on success/failure responses. If all options fail, it outp... | def Confidentiality_Attack_State2():
global Final_Statement
if(Dict_of_State_2_options_exhausted == Dict_of_State_2_options): #if all options have failed, give failure message
print("\n"+Final_Statement+Failure)
else:
response1 = input("Would you like to attempt a request to the Pub... |
def Confidentiality_Attack_State3():
global Final_Statement
response1 = input("Did the attacker succeed in connecting directly to the IoT application (via mobile data)? " + Yes_or_No + " ")
if (response1 == "yes" or response1 == "y" or response1 == "Yes" or response1 == "YES" or response1 == "Y"):
... | The code simulates a decision-making process in a confidentiality attack scenario, allowing the user to choose between attacking a public Wi-Fi or a user's phone. It tracks attempted options, validates user input, and transitions between states (State 2 or 3) based on success/failure. If all options fail, it logs the a... | def Confidentiality_Attack_State1():
global Final_Statement
if(Dict_of_State_1_options_exhausted == Dict_of_State_1_options): #if all options have failed, give failure message
print("\n"+Final_Statement + Failure)
else: #if options to proceed are still possible
print(... |
def analysis():
cumulative_list=[]
table=[]
header=["Semester","Avg.\nBefore","Semester\nAvg.","Avg.\nAfter","Delta","Hours","no.\ncourses"]
for y in range(1,5):
for s in range(1,4):
courses_list=get_semester(y,s)
row=[]
if len(courses_list)!=0:
... | The main task of the code is to generate HTML accordion components from a table dataset. It iterates through each row, creating collapsible sections with a summary table in the header and detailed semester information in the body. The function returns a concatenated HTML string of these accordions, using Bootstrap clas... | def build_accordions():
table,header = analysis()
accordions=""
for row in table:
accordions+='''
<div class="accordion-item">
<div class="accordion-header" id="'''+str(row[0])+'''1">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
... |
def closestIntervalIndex(x, grid):
for i in range(len(grid) - 1):
if grid[i] <= x and x <= grid[i + 1]:
return i
if x < grid[0]:
return 0
return len(grid)-2
def Derivatives(grid, functionValues):
deltas = deltaGrid(grid)
y = firstVector(functionValues, deltas)
matriz ... | This function computes a clamped cubic spline interpolation. It identifies the interval containing input x, retrieves sample points and their function values, calculates second derivatives, determines cubic polynomial coefficients for the interval, and evaluates the resulting polynomial at x. The clamped condition ensu... | def clampedCubicSpline(x, sample, functionValues):
closest = closestIntervalIndex(x, sample)
derivatives = Derivatives(sample, functionValues)
x_j = sample[closest]
x_j_1 = sample[closest + 1]
f_x_j = functionValues[closest]
f_x_j_1 = functionValues[closest + 1]
f_2_x_j = derivatives[closest... |
def proxyURL(url: str):
"""Redirects an AIO media link to an https, proxied link to the same file."""
# Proxying is no longer needed as media.focusonthefamily.com supports HTTPS
return url.replace('http://', 'https://')
def getRadioEpisodes() -> list:
"""Returns radio episodes as a list of dicts, each w... | The function retrieves episode information by URL, first checking radio episodes and then free episodes if no match is found, returning the first matching episode or None. | def getEpisodeByUrl(url: str):
"""Gets a dict of info about the episode linked to by the url."""
url = proxyURL(url)
candidates = list(filter(lambda x: x['url'] == url, getRadioEpisodes()))
if len(candidates) < 1:
candidates = list(filter(lambda x: x['url'] == url, getFreeEpisodes()))
return... |
def eps_to_pickle(infile, run_name):
data = HDFBrowser(infile)
df = data.to_df()
df = df[df["run_name"] == run_name]
epsilon = {}
for idx, run in df.iterrows():
eps = get_epsilon(run, "force_symmetry_axis")
epsilon.update({np.around(run["compliance_factor"], 2): eps})
with open(f... | The code processes input data to generate and save mode coefficients. It checks if epsilon data exists, creates it if not, then computes mode coefficients for each epsilon entry using `get_mode_coeffs` with a simulation resolution of 30. Results are stored in a dictionary and saved as a JSON file for the specified run ... | def write_mode_coeffs(infile, run_name):
if not os.path.isfile(f"./data/{run_name}_epsilon.pkl"):
eps_to_pickle(infile, run_name)
eps = eps_from_pickle(run_name)
res_table = {}
for key, val in sorted(eps.items()):
res_table.update({key: get_mode_coeffs(eps[key], sim_res=30)})
with ... |
def create_fk_model(self,input_dim = 3, output_dim = 3):
model = Sequential()
model.add(Dense(256, input_dim=input_dim, activation='relu')) # input layer (relu makes any negative numbers 0)
model.add(Dense(256, activation='relu')) # two hidden layers
model.add(Dense(256, activation='relu')) # layer size? / outp... | This code initializes a model with forward (FK) and inverse kinematics (IK) components, setting save/load file paths, configuring an Adam optimizer for IK training, and preparing a memory buffer for training. It loads pre-trained models if specified, using parameters from a config module to define memory size, batch si... | def __init__(self,ik_save_file="./models/rigid_ik_model",fk_save_file="./models/rigid_fk_model",
ik_load_file="./models/rigid_ik_model",fk_load_file="./models/rigid_fk_model",load=True):
self.fk = self.create_fk_model()
self.ik = self.create_ik_model()
self.fk_save_file = fk_save_file
self.ik_save_file = i... |
def clearBig():
global big,cflow,target,targetinv,jjj,pc,NonFor,forw, mll
big = []
ppview = []
cflow = dict()
target = dict()
targetinv = dict()
myList.delete(0,END)
jjj = 0
pc = 0
NonFor = list()
forw = list()
mll = set()
def setpc0():
global pc
pc = 0
pc_... | The main task of the code is to simulate a simple processor's execution of assembly-like instructions, track register/memory states, handle labels and jumps, and analyze pipeline stalls with/without forwarding. It processes input instructions, executes arithmetic/memory operations, records execution flow, and calculate... | def print_area(listt):
# pc = 0
clearBig()
global pc
setpc0()
print("pc=",pc)
for z in range(len(listt)):
ooo = listt[z]
if ooo == '' or (ooo.split())[0][0] == '#':
continue
big.append(ooo)
if isLabel(ooo):
ooo = list(ooo.split(':')... |
def stop_balls():
"""
Stop the balls movement, by bringing horiz. steppers out the uo to stop all balls
:return: None
"""
# move vertical steppers up
set_vertical_pos(LIFT_DISTANCE)
# slowly move the horizontal steppers into the middle/stopping positions
set_horizontal_speed(STOPPING_SP... | The function `new_scoop` manages a scooping process by retrieving the number of balls on both sides, stopping them, adjusting vertical speed, and initiating scooping actions. If there are 5 balls, it separately scoops left and right, waiting for horizontal movements to complete. Otherwise, it scoops both sides simultan... | def new_scoop():
"""
New scooped initiated, gets the number of balls on each side and calls the perspective function to control pickups
:return: None
"""
num_left = sm.get_screen('main').cradle.num_left()
num_right = sm.get_screen('main').cradle.num_right()
if num_left + num_right == 0:
... |
def ball_left(self, ball_string):
if ball_string.r == BallString.ROT_RIGHT:
self.ball_down(ball_string)
return
balls = self.get_balls()
i = balls.index(ball_string)
for ball in balls[i:]:
if ball.name == "right":
ball.down()
... | This function determines the action to take when a ball is touched based on its rotation and name. If the ball's rotation is ROT_DOWN, it triggers left or right actions depending on the ball's position (left, middle-left, middle, middle-right, right). Otherwise, it triggers a down action. Finally, it updates the main s... | def ball_touched(self, ball_string):
if ball_string.r == BallString.ROT_DOWN:
if ball_string.name == "left":
self.ball_left(ball_string)
elif ball_string.name == "middle-left":
self.ball_left(ball_string)
elif ball_string.name == "middle":
... |
def predictions_zero_angle(self, img):
img = img
return img, self.get_predictions(img)
def predictions_90_angle(self, img):
img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
return img, self.get_predictions(img)
def predictions_menos90_angle(self, img):
img = cv2.rotate(img, cv2.R... | This function determines if an image is a DFS file by analyzing it at four rotation angles (0°, 90°, -90°, 180°). It evaluates prediction scores, extracts regions of interest, performs OCR, and selects the angle with the highest punctuation confidence. If valid, it returns DFS status, confidence, optimal angle, and cor... | def get_dfs_angle_attributes(self, img):
is_dfs_file = 0
img_zero, predictions_zero = self.predictions_zero_angle(img)
img_90 , predictions_90 = self.predictions_90_angle(img)
img_menos90, predictions_menos90 = self.predictions_menos90_angle(img)
img_180 , predictions_180 = se... |
def initialize():
way = mount_route()
return way
def show(way):
for i in range(routeQtd):
print(f"Route {i + 1}\n")
aux = way[i].firstRouter
while aux is not None:
print(f"IP: {aux.ip} - Latency to next router: {aux.nextTime}ms - Last octet binary: {aux.lastBinOc} - Fitn... | The code executes a genetic algorithm (GA) for route optimization, initializing a population of routes and evolving them over 200 generations. It collects and displays metrics (total time, fitness) for each route per generation, plots results, and selects top-performing routes based on fitness. User input determines if... | def main():
generations_to_run = 200
# INITIALIZING THE ROUTES POPULATION
way = [initialize() for _ in range(routeQtd)]
print(f"Generation 0:\n\n") # Initial generation
show(way)
print(f"Do you want to continue route crossover? 1-yes, 0-no (Remaining generations: {generations_to_run}) ")
... |
def sample_xtree_heuristic(self):
n = self.number_of_nodes()
# Add goal to the list of nodes
self.add_node(n, self.goal[0], self.goal[1])
# Pick the node closer to the goal
xtree = self.nearest(n)
# Remove goal from the list of nodes
self.remove_node(n)
re... | The code extends a tree structure by sampling a heuristic-guided tree (xtree), obtaining the number of nodes (n), sampling random coordinates (x, y), connecting the tree with these coordinates, and returning the updated coordinates and parent node for further tree expansion in pathfinding or planning algorithms. | def extend(self):
xtree = self.sample_xtree_heuristic()
n = self.number_of_nodes()
x, y = self.sample_xrand()
self.connect(xtree, n)
return self.x, self.y, self.parent |
def runSimulation(class1, class2, simOrNo, rows=False, creatures=10):
start = time.time()
simulation = Darwin(class1, class2, simOrNo, rows, creatures)
simulation.setup()
# This draws everything
while not simulation.isOver:
for event in pygame.event.get():
if event.type == pyga... | The code runs a Darwinian evolutionary simulation, allowing users to choose between executing a single simulation or multiple trials. It initializes Pygame for a visual interface, processes user inputs for parameters like rows, creatures, and runs, and evaluates two classes (Rover and Apex) by simulating competitions. ... | def main():
try:
run = bool(
int(
input(
"Would you like to see the simulation or the results? -> 1/0\n>>"
)))
except:
print("I said 1/0")
times = 1 if run else int(
input("How many times would you like the program to ru... |
def get_UUdag(self, A, B, C, D, which):
"""
From the Q matrix this gets the isometry and the
singular values from the eigenvalues.
"""
# q = self.make_q_from_triads(A, B, C, D)
s1 = self.getS(A)
s2 = self.getS(B)
r2, r3 = self.getR23(C, D, B)
if w... | The function `update_triads` computes and applies isometries (left, right, front, back) to update tensor triads in a quantum tensor network. It truncates these isometries based on the bond dimension (`self.dbond`) and the singular values from `get_UUdag`. Depending on flags (`self.imp`, `self.nnimp`), it either creates... | def update_triads(self, getV=True):
"""
updates the triads starting from computing
Q upto updating the individual triads.
"""
# make the left isometry
resleft, Uleft = self.get_UUdag(self.A, self.B, self.C, self.D, which='lf')
# make the right isometry
re... |
def update_triads(self,):
"""
updates the triads starting from computing
Q upto updating the individual triads.
"""
q = self.getQ()
if (self.A.shape[0]**2 < self.dbond):
U = getU(q, self.A.shape[0]**2)
# print(U.shape)
# assert np.allc... | The main task of the code is to perform coarse-graining along the x and y directions by updating triads and normalizing data (if enabled). When `all_vols` is True, it returns logarithmic norms and an impurity tensor ratio (if applicable) to represent volume-related properties after processing. | def coarse_grain(self, normalize=True, all_vols=False):
""" Does the coarse graining along a single direction."""
# print("Coarsening second dimension...")
dirs = ['x', 'y']
for d in dirs:
print("Doing " + d)
self.update_triads()
if normalize:
... |
def makeX1(self,):
mid = np.tensordot(self.B, self.C, axes=([1], [1]))
mid = np.tensordot(mid, mid, axes=([1,2], [2,1]))
ends = np.tensordot(self.A, self.D, axes=([0,1],[2,1]))
full = np.tensordot(mid, ends, axes=([0,3],[0,1]))
full = np.tensordot(full, ends, axes=([0,1], [1,0]))... | The main task of the code is to perform coarse-graining in three spatial directions (x, y, z). It generates system states (X), updates triad structures, and normalizes data if specified. If `all_vols` is True, it returns logarithmic norms and impurity ratios (or just norms) for volume analysis. | def coarse_grain(self, normalize=True, all_vols=False):
"""The main coarse graining function."""
# print("Coarsening third dimension...")
dirs = ['x', 'y', 'z']
for d in dirs:
print("doing " + d)
X = self.makeX1()
self.Xlist.append(X)
print... |
def _create_mask(qlen, mlen, dtype=tf.float32, same_length=False):
"""create causal attention mask."""
attn_mask = tf.ones([qlen, qlen], dtype=dtype)
mask_u = tf.matrix_band_part(attn_mask, 0, -1)
mask_dia = tf.matrix_band_part(attn_mask, 0, 0)
attn_mask_pad = tf.zeros([qlen, mlen], dtype=dtype)
... | The code defines a Transformer-XL model with XLNet support, processing input tokens via attention mechanisms, memory caching, and segment/positional embeddings. It constructs a computation graph for multi-layer transformers with dropout, feed-forward networks, and bidirectional attention, returning output tensors and c... | def transformer_xl(inp_k, n_token, n_layer, d_model, n_head,
d_head, d_inner, dropout, dropatt, attn_type,
bi_data, initializer, is_training, mem_len=None,
inp_q=None, mems=None,
same_length=False, clamp_len=-1, untie_r=False,
... |
def reinitialize_constructor_parameters(self):
self.task_type = ""
def check_for_issue_in_prism_tlog(self, pname, folder, tlog_dict, prism_tasks, *args):
#issue validation against input_tags
for prism_input_tags in args:
for var_name, var_value in prism_input_tags.__dict__.i... | The main task of the code is to parse tlog data for different Prism components (e.g., PRISM_TOMCAT, PRISM_DEAMON, PRISM_SMSD) by determining log folders, initializing a DaemonLogProcessor, and processing error logs based on thread/status values. It categorizes logs, checks for issues using predefined tags, and triggers... | def parse_tlog(self, pname, tlog_header_data_dict, ctid_map=None):
"""
tlog parser method
"""
self.reinitialize_constructor_parameters()
folder = ""
if pname == "PRISM_TOMCAT":
folder = os.path.join(self.outputDirectory_object, "{}_issue_prism_tom... |
def wrap_note(text: str) -> str:
return "\n".join([textwrap.fill(p, AGS_INFO_WIDTH) for p in text.replace("\\n", "\n").splitlines()])
def make_image(path, options):
if util.is_file(path):
return
size = (320, 256)
scale = (1, 0.5)
if isinstance(options, dict) and "ops" in options:
if ... | This function creates and organizes entries in a database/collection by generating directory structures, handling notes/images, and sorting entries based on parameters like ranking, ordering, and release dates. It processes input entries, queries a database, creates placeholder entries for missing data, and invokes `ma... | def make_entries(
db: Connection, collection: EntryCollection, ags_path, entries, path,
note=None, image=None, ordering=None, rank=None, template=None, hidden=False
):
# make dir
base_path = ags_path
if path:
for d in path:
base_path = util.path(base_path, d[:AGS_LIST... |
def StudentDistillation(model, config):
teachers = [i for i in range(0,config.teachers)]
max_accuracy, teacher_weights = AED(model, config, teachers)
if config.evaluation == 'aed-loo':
recursive_accuracy(model, config, max_accuracy, teachers)
elif config.evaluation == 'lightts':
rec... | The code initializes a student model (InceptionModel) with fixed layer configurations and applies different training/evaluation strategies based on the 'evaluation' parameter in the config. It supports knowledge distillation methods like 'lightts', 'aed-loo', and 'fp-student' (with fixed-precision settings), or falls b... | def RunStudent(config):
config.layer1 = config.layer2 = config.layer3 = 3
model_s = InceptionModel(num_blocks=3, in_channels=1, out_channels=[10,20,40],
bottleneck_channels=32, kernel_sizes=41, use_residuals=True,
num_pred_classes=config.num_classes,config=config)
model... |
def advance(self):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
# print(self.current_tok.type)
return self.current_tok
def expr(self):
return self.bin_op(self.term, (def_var['TT_PLUS'],def_var['TT_MINUS'])) | This function parses expressions by handling unary operators, numbers, and parentheses. It constructs abstract syntax tree nodes (UnOpNode, NumberNode) for operations and values, validates syntax, and returns parsed nodes or syntax errors when invalid tokens are encountered. | def factor(self):
res = ParseResult()
tok = self.current_tok
if tok.type in (def_var['TT_PLUS'],def_var['TT_MINUS']):
res.register(self.advance())
factor = res.register(self.factor())
if res.error:
return res
return res.success(UnO... |
def shuffle_stim(stim):
global seed, task
i=0
if task == 'recog':
i = 0
if task == 'act':
i = 1
if task == 'style':
i = 2
stim1 = stim.copy()
stim2 = stim.copy()
stim3 = stim.copy() #?edit out if only 2 runs
random.seed(seed[i])
random.shuffle(stim1)
r... | The code conducts a recognition training task where participants identify natural images. It shuffles stimuli, presents images, records responses and reaction times, evaluates accuracy, and ends the trial if 10 consecutive correct answers are achieved. Data is saved after each trial, with feedback provided. | def recog_train():
global task, task1, spec
task="recog"
task1="train"
test_stim=shuffle_stim(nat_stimuli)
msg(t.r1)
msg(t.r2)
msg(t.r3)
print(f"current task is {task} {task1}")
i = 0
correct_count = []
end_trial=False
while not end_trial:
global reaction_time
... |
def shuffle_stim(stim):
global seed, task
i=0
if task == 'recog':
i = 0
if task == 'act':
i = 1
if task == 'style':
i = 2
stim1 = stim.copy()
stim2 = stim.copy()
stim3 = stim.copy() #?edit out if only 2 runs
random.seed(seed[i])
random.shuffle(stim1)
r... | The code conducts a recognition test by presenting shuffled stimuli to participants, recording their responses and reaction times, and saving the data for analysis. It loops through 'n_times' trials, displaying each stimulus, capturing responses, and logging details like trigger names, reaction times, and answers, with... | def recog_test(n_times):
test_stim = shuffle_stim(out_stimuli)
global task, task1
task="recog"
task1="test"
msg(t.r4)
msg(t.r5)
print(f"current task is {task} test")
for i in range(n_times):
global reaction_time, trigger_name
trigger_name = test_stim[i]+'_'+task
m... |
def shuffle_stim(stim):
global seed, task
i=0
if task == 'recog':
i = 0
if task == 'act':
i = 1
if task == 'style':
i = 2
stim1 = stim.copy()
stim2 = stim.copy()
stim3 = stim.copy() #?edit out if only 2 runs
random.seed(seed[i])
random.shuffle(stim1)
r... | This function conducts a training task where participants identify natural images. It shuffles stimuli, presents each image, records responses and reaction times, checks accuracy, and tracks correct answers. If 10 consecutive correct responses occur, the trial ends. Feedback and data are saved after each trial, with a ... | def act_train():
global task, task1, acti
task="act"
task1="train"
test_stim=shuffle_stim(nat_stimuli)
i = 0
msg(t.m1)
msg(t.m2)
msg(t.m3)
correct_count =[]
end_trial = False
while not end_trial:
global reaction_time
nxt_img = test_stim[i % len(test_stim)]
... |
def shuffle_stim(stim):
global seed, task
i=0
if task == 'recog':
i = 0
if task == 'act':
i = 1
if task == 'style':
i = 2
stim1 = stim.copy()
stim2 = stim.copy()
stim3 = stim.copy() #?edit out if only 2 runs
random.seed(seed[i])
random.shuffle(stim1)
r... | This code conducts a psychological experiment task ('act' test) by presenting shuffled stimuli, recording participants' reaction times, and saving trial data. It initializes global variables, triggers events, displays stimuli, captures responses, and logs results including reaction time, answer, and trigger details. Th... | def act_test(n_times):
test_stim = shuffle_stim(out_stimuli)
global task, task1
task="act"
task1="test"
msg(t.m4)
msg(t.m5)
print(f"current task is {task} test")
for i in range(n_times):
global reaction_time, trigger_name
#trigger
trigger_name = test_stim[i]+'_'+... |
def shuffle_stim(stim):
global seed, task
i=0
if task == 'recog':
i = 0
if task == 'act':
i = 1
if task == 'style':
i = 2
stim1 = stim.copy()
stim2 = stim.copy()
stim3 = stim.copy() #?edit out if only 2 runs
random.seed(seed[i])
random.shuffle(stim1)
r... | This function conducts a training task where participants identify a specific style in natural images. It shuffles stimuli, presents images, records responses and reaction times, checks accuracy, and saves data. The trial ends when 10 consecutive correct answers are achieved or after 20 trials with a break message. | def style_train():
test_stim=shuffle_stim(nat_stimuli)
global task, task1
task="style"
task1="train"
msg(t.s1)
msg(t.s2)
msg(t.s3)
print(f"current task is {task} train")
i = 0
correct_count = []
end_trial=False
while not end_trial:
global reaction_time
nxt... |
def shuffle_stim(stim):
global seed, task
i=0
if task == 'recog':
i = 0
if task == 'act':
i = 1
if task == 'style':
i = 2
stim1 = stim.copy()
stim2 = stim.copy()
stim3 = stim.copy() #?edit out if only 2 runs
random.seed(seed[i])
random.shuffle(stim1)
r... | The main task of the code is to conduct a psychological/cognitive test where participants respond to visual stimuli. It shuffles stimuli, displays them, records reaction times, evaluates accuracy, and saves data including stimulus details, response time, answer, and accuracy for analysis. The loop runs multiple trials,... | def style_test(n_times):
test_stim = shuffle_stim(out_stimuli)
global task, task1
task="style"
task1="test"
msg(t.s4)
msg(t.s5)
print(f"current task is {task} test")
for i in range(n_times):
global reaction_time, trigger_name
trigger_name = test_stim[i]+'_'+task
m... |
def msg(txt):
win.flip()
message = visual.TextStim(win, text = txt, height = 0.9,wrapWidth= 50)
message.draw()
win.flip()
key = event.waitKeys()
if 'escape' in key:
save_and_escape(task, task1, reaction_time, response, accurate, out_image, species, action, nat_image)
def recog(times_proc... | The code defines an experiment function that executes different sequences of tasks (recognition, action, style, and message display) based on the input GROUP parameter. Each group (A-F) triggers a unique order of these tasks, followed by a standardized exit procedure displaying a goodbye message and terminating the exp... | def experiment(GROUP,procent):
msg(t.i1)
msg(t.i2)
msg(t.i3)
if GROUP == 'A':
recog(procent)
msg(t.r6)
act(procent)
msg(t.m6)
style(procent)
if GROUP == 'B':
act(procent)
msg(t.m6)
style(procent)
msg(t.s6)
recog(procent)... |
def modelMultiScaleDiscriminator(self, name=None):
x1 = Input(shape=self.img_shape)
x2 = AveragePooling2D(pool_size=(2, 2))(x1)
#x4 = AveragePooling2D(pool_size=(2, 2))(x2)
out_x1 = self.modelDiscriminator('D1')(x1)
out_x2 = self.modelDiscriminator('D2')(x2)
#out_x4 = se... | This code initializes a CycleGAN model for domain adaptation, configuring discriminators (D_S, D_T) and generators (G_S2T, G_T2S) with cyclic loss, adversarial training, and data handling. It sets hyperparameters, compiles models with Adam optimizers, prepares training/test data, and initializes GPU settings for traini... | def __init__(self, lr_D=2e-4, lr_G=2e-4, img_shape=(240, 240, 3), domain_shape = (240, 240, 1),
date_time_string_addition='', image_folder='MR'):
self.img_shape = img_shape
self.hinge = hinge
# self.gram_loss = gram_loss
self.domain_shape = domain_shape
self.... |
def pad_function(example):
padded_inputs = example["input_ids"] + [tokenizer.pad_token_id] * (1024 - len(example["input_ids"]))
padded = {}
padded["input_ids"] = padded_inputs
padded["attention_mask"] = example["attention_mask"] + [0] * (1024 - len(example["attention_mask"]))
padded["labels"] = padd... | The main task of the code is to preprocess and fine-tune a model on a dataset by filtering, tokenizing, padding, and saving processed data, followed by training a model with specified hyperparameters and pushing the trained model to a hub with a custom description. | def main():
global index
datasets = DatasetDict({"train": dataset_train, "validation": dataset_val})
datasets = datasets.filter(filter_function, num_proc=TOKENIZATION_N_JOBS, desc="Filtering dataset")
# Print number of samples in train dataset
print(len(datasets["train"]))
datasets["train"] = da... |
def evaluate_global(cur_state:State)->int:
"""Return evaluate score of a state"""
score = cur_state.game_result(cur_state.global_cells.reshape(3, 3))
if (score != None): return 10000 * score
return heuristic_for_X(cur_state) + heuristic_for_O(cur_state)
def get_valid_moves_test(cur_state, player, previo... | The code implements the Minimax algorithm with alpha-beta pruning to evaluate game states recursively. It determines the optimal score for a player by exploring valid moves, alternating turns, and pruning suboptimal branches. At depth 2, it returns a global evaluation of the state. For player 1 (maximizer), it selects ... | def minimax(cur_state, depth, player, previous_move, alpha, beta)->int:
"""Return a score that state can lead to"""
if depth == 2: return evaluate_global(cur_state)
valid_moves = get_valid_moves_test(cur_state, player, previous_move)
# print(valid_moves)
if player == 1:
bestVal = -np.inf
... |
def X_move(cur_state):
if cur_state.previous_move == None:
return UltimateTTT_Move(4, 1, 1, 1)
total_X = count_X(cur_state)
idx_move_block = 3 * cur_state.previous_move.x + cur_state.previous_move.y
if total_X <= 7:
return UltimateTTT_Move(idx_move_block, 1, 1, 1)
if total_X == 8:
... | The code's main task is to select the optimal move for the current player using the minimax algorithm. It evaluates all valid moves by simulating each on a copied game state, compares their minimax scores against the current best move, and updates the best move if a better option is found. The function returns the move... | def select_move(cur_state, remain_time):
if cur_state.player_to_move == 1:
return X_move(cur_state)
player = cur_state.player_to_move
pre_move = cur_state.previous_move
valid_moves = get_valid_moves_test(cur_state, -1, pre_move )
best_move = valid_moves[0]
for move in valid_moves:
... |
def get_empty_board():
return [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
def print_board(board):
row_separator = " -------------------"
print(" col1 col2 col3 ")
print(row_separator)
for i in range(0, 3):
print(f"row{i + 1}| {board[i][0]} | {board[i][1]} | {board[i]... | The code simulates a Tic-Tac-Toe game by alternating turns between players 'x' and 'o', checking for a win after each move, and declaring a tie if all 9 moves are made without a winner. It uses helper functions to manage the game board, player input, win detection, and game state updates. | def playGame():
board = get_empty_board()
print_board(board)
gameover = False
turn = 0
while not gameover:
takeTurn("x", board)
turn += 1
print_board(board)
if isWinner("x", board):
print("x wins!")
gameover = True
if not gameover and... |
def take_turn(board, player):
print_board(board)
print(f"your turn {player}")
row, col = get_valid_input()
if board[row][col] == "_":
board[row][col] = player
else:
print("your chosen spot is occupied, please choose another")
return take_turn(board, player)
def check_for_win... | The code implements a simple tic-tac-toe game where two players take turns marking a 3x3 board with 'X' and 'O'. It alternates turns, checks for a winning condition after each move, and ends the game when a player wins or the board is full, displaying the final board state and "Game Over". | def play_game():
board = [list("___"), list("___"), list("___")]
player1 = "X"
player2 = "O"
game_over = False
while not game_over:
take_turn(board, player1)
game_over = check_for_win(board, player1)
if not game_over:
take_turn(board, player2)
game_o... |
def create_board():
return [list("___"), list("___"), list("___")]
def take_turn(letter, board):
print_board(board)
print(f"your turn {letter}")
row = get_valid_input("which row?: ")
col = get_valid_input("which column?: ")
if board[row][col] == "_":
board[row][col] = letter
else:
... | The code defines a function `play_game()` that initializes a game board, alternates turns between two players ("x" and "o"), checks for a win after each move, and ends the game when a player wins or the board is full. It prints the final board state once the game concludes. | def play_game():
board = create_board()
gameover = False
turn_num = 0
while not gameover:
take_turn("x", board)
turn_num += 1
gameover = check_for_win(board, "x", turn_num)
if not gameover:
take_turn("o", board)
turn_num += 1
gameover... |
def create_board():
return list("_" * 9)
def take_turn(board, letter):
print_board(board)
print(f"your turn {letter}")
spot = get_valid_input("which spot?: ")
if board[spot] == "_":
board[spot] = letter
else:
print("your chosen spot is occupied, please choose another")
... | This code defines a function to play a two-player game on a board. It alternates turns between players 'x' and 'o', using functions to take turns and check for a win after each move. The loop continues until one player wins, at which point the game ends. | def play_game():
board = create_board()
player1 = "x"
player2 = "o"
game_over = False
while not game_over:
take_turn(board, player1)
game_over = check_for_win(board, player1)
if not game_over:
take_turn(board, player2)
game_over = check_for_win(board... |
def get_number_of_players():
try:
choice = input("How many players? (1 or 2): ")
return int(choice)
except ValueError:
print("Input must be the number 1 or 2")
return get_number_of_players()
def take_turn(board, player):
print_board(board)
print(f"Your turn {player}")
... | The code defines a Tic-Tac-Toe game that initializes a board, alternates turns between player 'X' and 'O' (human or computer), checks for wins after each move, and allows replay. It handles single-player vs. computer or two-player modes, displays the board, and prompts the user to play again after the game ends. | def play_game():
print("---------------")
print("- TIC-TAC-TOE -")
print("---------------")
board = list("_" * 9)
game_over = False
player1 = "X"
player2 = "O"
players = get_number_of_players()
while not game_over:
# X take turn
take_turn(board, player1)
game... |
def check_energenie_cal(verbosity=1,modulator_state=False):
'''
check for the status of the calsource Energenie sockets
and switch on/off the modulator
'''
retval = {}
retval['ok'] = True
retval['error_message'] = ''
retval['message'] = ''
errmsg_list = []
msg_list = []
erro... | The code checks network connectivity to machines, including handling the modulator's state (on/off) based on the fulltest flag. It pings each machine, collects status messages, and aggregates errors. If any machine fails, it updates the error log. For full tests, it ensures the modulator is turned off afterward. The fu... | def check_network(verbosity=1,fulltest=False):
'''
ping the machines on the network
'''
retval = {}
retval['ok'] = True
retval['error_message'] = ''
retval['message'] = ''
errmsg_list = []
msg_list = []
if verbosity>0: print('\n============ checking network access ============')
... |
def check_power(verbosity=1):
'''
check if the components attached to the Energenie power bar are switched on
'''
retval = {}
retval['ok'] = True
retval['error_message'] = ''
retval['message'] = ''
errmsg_list = []
msg_list = []
if verbosity>0: print('\n============ checking for ... | The function `hk_ok` performs a series of system checks (power, network, storage, temperature, etc.) and aggregates their statuses. It constructs error messages for failed checks, sends alerts via Telegram if issues exist, and returns a dictionary containing detailed results, overall success status, and combined messag... | def hk_ok(verbosity=1,fulltest=False):
'''
check that housekeeping is okay
'''
retval = {}
ok = True
message = ''
retval['power'] = check_power(verbosity=verbosity)
retval['network'] = check_network(verbosity=verbosity,fulltest=fulltest)
retval['mounts'] = check_mounts(verbosity=ver... |
def find_amazon_links(url):
# Send a GET request to the URL
try:
response = requests.get(url)
response.raise_for_status() # Check for HTTP request errors
except requests.exceptions.HTTPError as err:
print(f"HTTP Error: {err}")
return []
except requests.exceptions.Request... | The main task of the code is to process input ASINs or URLs to fetch Amazon product items, optionally outputting results in JSON format or generating HTML. It parses command-line arguments, extracts ASINs from URLs, retrieves item data, and uses replacement ASIN mappings to generate structured output. | def main():
# Create the parser
parser = argparse.ArgumentParser(description='Process -asins or -url options.')
# Add the arguments
parser.add_argument('-a', '--asins', type=str, help='The ASINs')
parser.add_argument('-u', '--url', type=str, help='The URL')
parser.add_argument('--json', acti... |
def _filon_fft(x, f, k, dx):
# Get the weights
theta = dx*k
wt, wn = _filon_wtn(theta)
# Compute the integral
I = wt*np.fft.fftshift(np.fft.fft(f)) + wn*(f[-1]*np.exp(1j*k*x[-1]) - f[0]*np.exp(1j*k*x[0]))
I *= dx
return I
def _filon_cos(x, f, k, dx):
N = len(x)
a, b = np... | The function `fourier_integrate` computes the Fourier integral of a function `f(x)` over a given `x` domain, using either FFT-based Filon's method or direct sine/cosine transforms. It evaluates $\int f(x) e^{-ikx} dx$ for specified or generated `k` values, returning the integral result (`F`) and corresponding `k` value... | def fourier_integrate(x, f, k = None, nk = None, fft = True, indvar = True):
"""Calculate the integral
:math:`\int_{x_0}^{2n\Delta x} f(x) exp(-1 i k x) dx`.
Parameters
----------
x : array
values of x-axis to integrate along
f : float
functions values along x-axis
k : array
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.