dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def LocalMaxPeakShow(self, final=False):
# Remove existing _LocalMaxPeak layers
string_list = [layer.name for layer in self.viewer.layers]
for i in string_list:
if (str(self.clusterComboBox.currentText()) + "_LocalMaxPeak") in i:
self.viewer.layers.remove(i)
... | This function removes existing watershed layers, ensures required mask and local max peak layers are present, then generates and displays new watershed segmentations using the mask and peak data. It applies the Watershed algorithm iteratively for each LocalMaxPeak layer, adding labeled outputs with specific naming, opa... | def WatershedPreview(self, final=False):
# Remove any existing watershed layer
for i in [layer.name for layer in self.viewer.layers if "Watershed" in layer.name]:
self.viewer.layers.remove(i)
# Make sure mask and local max peak layers exist
if not (str(self.clusterComboBox.c... |
def load_cache():
"""
Function that deserialize scan object
If no file found, new object is returned
"""
try:
with open(get_cache_path(), 'r') as f:
scan_json = f.read()
if scan_json:
return Scan.parse_raw(scan_json)
else:
ret... | The code's main task is to parse command-line arguments, perform a network scan using the provided IP address, process scan results into structured data models, handle errors, and output results with optional verbosity. It loads a scan cache, iterates through hosts, protocols, and ports, populates data objects, prints ... | def main():
"""
Main function that parses command line arguments, initiates a network scan, and prints scan results.
"""
# Parse command line parameters
parser = argparse.ArgumentParser()
parser.add_argument("ipaddress", help="IP address or network range")
parser.add_argument("-v", action="... |
def reserve_session(self):
pin = str(self.pin)
timecode = str(get_tc())
url = "https://kahoot.it/reserve/session/"+pin+"/?"+timecode
r = self.s.get(url, verify=False)
try:
data = json.loads(r.text)
self.kahoot_raw_session = r.headers['x-kahoot-session-token']
self.challenge = self.... | The code establishes a connection to a Kahoot session by reserving it, setting up session parameters, performing handshakes, and subscribing to topics like "controller," "player," and "status." It sends multiple subscription payloads in a structured loop, then finalizes the connection. If the session reservation fails,... | def connect(self):
if self.reserve_session():
self.set_kahoot_session()
self.ping_session()
self.clientid = self.handshake()
self.run_connect_first()
subscribe_order = ["subscribe", "unsubscribe", "subscribe"]
subscribe_text = ["controller", "player", "status"]
for x in ran... |
def address_in_cidr(ip_address, endpoint):
cidr_notation = str(all_ones(endpoint))
return ".".join(ip_address) + "/" + cidr_notation
def number_of_subnets(ip_address, endpoint):
a = all_ones(endpoint)
if int(ip_address[0]) >= 192 and int(ip_address[0]) <=223:
x = a - 24
else:
x = a -... | The code calculates and returns subnet-related information for a given IP address and endpoint, including CIDR notation, number of subnets, addressable hosts per subnet, valid subnets, broadcast addresses, and first/last IP addresses of each subnet. It utilizes helper functions to compute these values, providing a stru... | def mask_for_subnet(ip_address, endpoint):
return{
# The endpoint will return the following json structure.
"address_cidr" : address_in_cidr(ip_address, endpoint),
"num_subnets": number_of_subnets(ip_address, endpoint),
"addressable_hosts_per_subnet": addressable_hosts(endpoint),
"valid_subnets": valid_subn... |
def exception(*args, printFlag=None):
"""log exception message with the stack: Log.exception(e) """
if gLogger:
error('***** EXCEPTION >>>>>')
error(*args)
error(traceback.format_exc(limit=12))
error('<<<<< EXCEPTION *****')
elif printFlag is None or printFlag:
print(... | This function initializes a logger with configurable settings, including log file rotation, directory structure (under date or not), and cleanup of old log files. It sets up a logger with a specified name, configures a rotating file handler, and ensures only the latest log files are retained based on the history count. | def initLogger(pwd, logDirName, appName, filePrefix, historyCnt=100,
fPutLogsUnderDate=False, loggerName=DEFAULT_LOGGER_NAME, autoRestTime=False):
""" Initialize logging
- pwd: pathname of working directory under which we put logs
- logDirName: put all logs into this dir, i.e. 'Logs'
... |
def _analyze_audio(
mlaudio: MLAudio, skip_beat_analysis=False
) -> Tuple[np.ndarray, np.ndarray, float, np.ndarray]:
"""Performs the main audio analysis required
Args:
mlaudio (MLAudio): the MLAudio object to perform analysis on
skip_beat_analysis (bool, optional): Skips beat analysis if t... | The function identifies optimal loop points in an audio track by analyzing beats, applying duration constraints, and filtering candidate loops based on similarity and loudness. It adjusts loop boundaries to minimize audio artifacts and returns the best LoopPair candidates, prioritizing longer loops for similar sequence... | def find_best_loop_points(
mlaudio: MLAudio,
min_duration_multiplier: float = 0.35,
min_loop_duration: Optional[float] = None,
max_loop_duration: Optional[float] = None,
approx_loop_start: Optional[float] = None,
approx_loop_end: Optional[float] = None,
brute_force: bool = False,
disable... |
def valid_input(prompt, options):
while True:
option = input(prompt).lower()
if option in options:
return option
print_pause('Sorry,that is invalid. Please try again Captain.')
def display_name():
print_pause("Mission Space-USS Maverick")
print_pause("\nWelcome Captain!")... | The main task of the code is to allow the user to replay the game. The `replay()` function prompts the user to play again, and if they choose "1", it restarts the game by calling `display_name()`, `story()`, `equip()`, and `explore()` before recursively invoking `replay()`. If the user declines, it exits the game with ... | def replay():
again = valid_input("\nWould you like to play again? Type 1:>", ['1'])
if again == "1":
display_name()
story()
equip()
explore()
replay()
return
else:
print("Thanks for playing!")
exit(0) |
def reset_states(self):
self.recent_action = None
self.recent_observation = None
def take_action(self, observation):
states = self.memory.get_recent_states(observation)
q_values = self.compute_q_values(states)
action = self.policy.select_action(q_values, self.step, self.training)... | The code trains a reinforcement learning agent over multiple episodes by interacting with an environment, collecting rewards, and updating the model through learning steps. It supports action repetition, weight saving, visualization, and logs metrics like reward per step and mean squared error (MSE) for each episode. | def fit(self, nb_episodes, action_repetition=1, save_weights=True, save_weights_step=1000, weights_folder=None,
visualize=False, visualize_sleep=0.02):
self.training = True
self.step = 0
self.episode = 0
if save_weights and weights_folder is None:
weights_folder =... |
def reset_states(self):
self.recent_action = None
self.recent_observation = None
def take_action(self, observation):
states = self.memory.get_recent_states(observation)
q_values = self.compute_q_values(states)
action = self.policy.select_action(q_values, self.step, self.training)... | This code runs a test phase for a reinforcement learning agent, executing a specified number of episodes. It evaluates the agent's policy by interacting with the environment, accumulating rewards, and optionally visualizing each step. The agent processes observations, takes actions, and updates its model based on the e... | def test(self, nb_episodes, action_repetition=1, visualize=False, visualize_sleep=0.02):
self.training = False
self.step = 0
self.episode = 0
while self.episode < nb_episodes:
episode_start_time = time.time()
episode_step = 0
episode_reward = 0
... |
def pruneHello() -> None:
"""Removes nodes from incoming neighbors if they haven't been heard from recently.
"""
global hellosReceivedFrom
global lastPruneHelloTime
if (timeCheckPassed(lastPruneHelloTime, PRUNE_HELLO_REOCCURRENCE_SEC)):
# print("PRUNING INCOMING NEIGHBORS")
remove: L... | The main task of the code is to execute pruning operations by sequentially calling three specialized pruning functions: pruneHello(), pruneLSA(), and pruneJoin(). This function serves as a wrapper to aggregate and trigger these operations, likely for data processing, optimization, or cleanup tasks, though the exact sco... | def prune() -> None:
"""Call all pruning functions.
"""
pruneHello()
pruneLSA()
pruneJoin()
return |
def updateMCastTableForRoot(root: int) -> int:
"""Updates the MCast Table with the latest information for a single root.
Args:
root (int): The root to be updated.
Returns:
int: If there is no way for the node to hear from the root, then the root is returned. Otherwise, there is a way to he... | This function handles join messages in a multicast tree by either updating the MCast table for a root node, forwarding the message through intermediate nodes, or writing join details to a file. It checks if the current node is the root, parent, or next intermediate node in the path, performing appropriate actions like ... | def handleJoinMessage(id: int, sid: int, pid: int, intermediateNodes: List[int]) -> None:
"""Add MCast information into the MCast Table or forward the join message.
Args:
id (int): The ID of the node wiishing to join.
sid (int): The ID of the root of the tree.
pid (int): The ID of the ... |
def timeCheckPassed(lastTime: float, reoccurrenceTime: float) -> bool:
"""Determines whether an event should happen based on the last time it happened and how often it should happen.
Args:
lastTime (float): The last time the event occurred.
reoccurrenceTime (float): How often the event should o... | The function sends JOIN messages to maintain multicast tree paths. It periodically checks a timer, and if triggered, sends JOIN messages to the parent on the source's shortest path tree (SPT) and to all parents in the multicast (MCast) table. For a receiver node, it retrieves the MCast table entry for the source, sends... | def sendJoinMessage() -> None:
"""Sends JOIN message to parent on the SPT of the source and sends JOIN messages to each parent in the MCast Table.
"""
global lastRefreshParentMessageTime
if (timeCheckPassed(lastRefreshParentMessageTime, REFRESH_PARENT_MESSAGE_REOCCURRENCE_SEC)):
# ... |
def handleHelloMessage(id: int) -> None:
"""Adds a node to the incoming neighbors.
Args:
id (int): Node to be added.
"""
# Mark the node as having received a HELLO message from
hellosReceivedFrom.add(id)
# If the node is not in this node's incoming neighbors
# add it and add it to... | The main task of the code is to read messages from an input file, parse their type and parameters, and route them to the appropriate handler functions (e.g., handleHelloMessage, handleLSAMessage). It processes each line by splitting it into components, converts values to integers or lists, and handles edge cases like m... | def handleMessages() -> None:
"""Reads from the input file, parses the message, and hands the message off to the appropriate handler.
"""
newLines = inputFile.readlines()
# Nothing new
if (len(newLines) < 1):
return
# For each new message, parse the message and hand the message... |
def sendHelloMessage() -> None:
"""Sends HELLO message.
"""
global lastHelloMessageTime
if (timeCheckPassed(lastHelloMessageTime, HELLO_MESSAGE_REOCCURRENCE_SEC)):
# print("SENDING HELLO")
writeToFile(outputFile, [f"hello {nodeNum}\n"])
lastHelloMessageTime = time.time()
retu... | The main task of the code is to initiate and run a link state protocol for a specified duration (RUN_MINUTES). It periodically sends hello, link state advertisement (LSA), join, and multicast messages, processes incoming messages, and performs pruning to maintain network state. The loop continues until the runtime expi... | def participate() -> None:
"""Start the link state protocol. Runs for RUN_MINUTES minutes.
"""
# print("NODE NUM: " + str(nodeNum))
endTime = time.time() + 60 * RUN_MINUTES
while (time.time() < endTime):
sendHelloMessage()
sendLSAMessage()
sendJoinMessage()
sendMCast... |
def log_output(message, end='\n'):
with open(logFilePath, 'a', encoding='utf-8') as f:
f.write(message + end)
print(message, end=end)
def snapshot_registry(hive, path):
# Take a snapshot of registry keys and values
snapshot = {}
try:
with winreg.OpenKey(hive, path, access=winreg.KEY_... | The code monitors Windows registry changes by comparing current and previous states of specified registry keys, logging discrepancies, and checking for suspicious entries. It iterates through predefined registry paths, captures snapshots, detects modifications, and alerts on potential security risks, while handling use... | def monitor_registry():
# Initialize the previous state dictionary to hold snapshots of registry keys
previous_states = {}
try:
for category, paths in REGISTRY_LOCATIONS.items():
log_output(f"Checking {category}...")
for entry in paths:
hive, path = entry[:2... |
def make_move(self, col) -> bool:
for row in range(self.rows - 1, -1, -1):
if self.board[row][col] == ' ':
self.board[row][col] = self.current_player
return True
return False
def display_board(self) -> None:
for row in self.board:
print('|'... | This function attempts to make a move in the specified column. If successful, it displays the board, checks for a win, logs the result, and switches players. If the board is full, it logs a draw. If the move is invalid (e.g., full column), it logs an error. Returns True on valid moves with outcomes, False otherwise. | def make_and_display_move(self, col) -> bool:
if self.make_move(col):
self.display_board()
if self.check_winner():
logger.info(WIN_MESSAGE.format(player=self.current_player))
return True
if all(cell != ' ' for row in self.board for cell in row)... |
def display_board(self) -> None:
for row in self.board:
print('|'.join(row))
print('-' * (self.cols * 2 - 1))
print(' '.join(str(i) for i in range(self.cols)))
def get_valid_column_input(self) -> int:
while True:
try:
col = int(input(MOVE_PROMPT.fo... | The code's main task is to execute a game loop where it displays the game board, repeatedly prompts for a valid column input, and attempts to make a move. If the move is successfully made and displayed, the loop terminates. This handles user interaction and game progression until a valid move completes the process. | def execute(self) -> None:
self.display_board()
while True:
col = self.get_valid_column_input()
if self.make_and_display_move(col):
break |
def build_parser() -> ArgumentParser:
"""
Builds an `ArgumentParser` that contains enough information to put together a `Context`.
Note that the `CustomArgumentParser` we use supports assigning arguments through
environment variables named the same as the `metavar` attribute, so one would assign
`IB... | The main task of the code is to parse command-line arguments, build a context, create an application instance, and synthesize CloudFormation (CF) templates for a parameterized application. It leverages functions like `build_parser`, `build_context`, and `build_app` to configure and generate infrastructure-as-code resou... | def main():
"""
Parses arguments and synthesizes CF for our parameterized application.
"""
parser = build_parser()
args = parser.parse_args()
ctx = build_context(args)
app = build_app(ctx)
app.synth() |
def update_stage(self, index):
try:
value = int(self.stages[index].text())
if value < 0:
return
# update
self.stagesValues[index] = value
self.update_ratio()
self.set_ratio_label()
except ValueError:
pass... | The code initializes a GUI for a drivetrain configuration and performance analysis tool. It sets up combo boxes for motor, wheel, and transmission selection, input fields for parameters like robot mass and battery voltage, and layouts for gear ratio inputs and simulation results. The interface connects user inputs to u... | def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setGeometry(200, 200, 1400, 840)
self.setWindowTitle("Improved Ratio Calculator")
self.setWindowIcon(QIcon('assets/T4K_RGB_round[colour]_transparent.png'))
# motor choice
motor_ch... |
def m_to_ft(value):
return 3.2808399 * value
def get_a_coefficient(self):
# (motor_torque * G * n) / R
return (self.get_motor_torque() * self.ratio * self.numMotor) / \
(data.kNominalBatteryVoltage / self.motor.stallCurrent)
def get_b_coefficient(self):
# 1 / (kv * r)
... | The main task of the code is to calculate and return the acceleration in feet per second squared by applying a coefficient to the difference between battery voltage and a velocity-dependent term, then converting the result from meters to feet using the `m_to_ft` function. | def get_acceleration(self):
return m_to_ft(self.get_a_coefficient() * (self.batteryVoltage - self.get_b_coefficient() * self.velocity)) |
def get_motor_torque(self):
# (kt) / (m * r * u)
return (2 * self.motor.kT) / (self.mass * self.wheel.diameterM * self.get_losses())
def torque_to_current(self, torque):
return torque / self.motor.kT
def get_acceleration(self):
return m_to_ft(self.get_a_coefficient() * (self.batteryVolta... | The main task of the code is to simulate a motor-driven system's kinematics and electrical parameters over time steps. It iterates through data points, updating velocity, distance, torque, and current values, while tracking maximum acceleration, velocity, torque, current, and power metrics. The results are logged into ... | def iterate(self):
for _ in data.kXValues:
# update kinematics
self.torque = self.get_motor_torque()
self.current = self.torque_to_current(self.torque)
self.acceleration = self.get_acceleration()
self.velocity += self.acceleration * data.kTimeStep
... |
def bounding(self, image_loc, label):
if not self.button.isChecked():
self.open()
return
image = cv2.imread(image_loc)
classify = sqlite3.connect('classification.db')
classify_cur = classify.cursor()
coco = "SELECT coco_boxes, coco_classes FROM data WHER... | This code initializes a GUI window to display an image with scrollable view, sets up a toolbar with a toggle action to show/hide bounding boxes, and connects the action to a method for rendering boxes on the image. It configures UI components like QLabel, QScrollArea, and QToolBar, and sets the window title based on th... | def __init__(self, image_loc):
super().__init__()
self.showMaximized()
self.image_loc = image_loc
self.scaleFactor = 0.0
self.imageLabel = QLabel()
self.imageLabel.setStyleSheet("background-color : white")
self.imageLabel.setAlignment(Qt.AlignmentFlag.AlignCent... |
def lowerColumn(list_of_strings):
"""
INPUT: A list of strings
OUTPUT: Same list with strings lower case
"""
return list(map(str.lower, list_of_strings))
def removePunctuation(list_of_strings):
"""
INPUT: A list of strings
OUTPUT: Same list but with punctuation removed
"""
retur... | The function `optimizeSearch` determines if a user's input matches an exact column name in a dataframe or provides the closest estimated columns. It processes the input by normalizing column names (lowercasing, removing punctuation) and checks for an exact match. If found, it returns the corresponding column's definiti... | def optimizeSearch(userInput):
"""
INPUT: A dataframe, the user's input
OUTPUT: Either the definition of the exact column name or a estimated column based on
PURPOSE: To determine whether the user is searching for a column or for simply a definition
"""
df = database_query.searchDataFrame()
... |
def save_link():
f = open(DATA_LINK, "w")
global database
if len(sys.argv) > 1: # database path given as first arg of daemon
database = os.path.abspath(sys.argv[1])
f.write(database)
f.close()
try:
# file already exists, load
loaded_snapshot = read_csv_database()
exc... | The main task of the code is to handle commands from a named pipe (FIFO) to add, delete, or update events in a loop. It sets up signal handling for graceful shutdown, creates a named pipe if it doesn't exist, and continuously reads commands from the pipe, executing corresponding functions based on the received operatio... | def run():
# Do not modify or remove this function call
signal.signal(signal.SIGINT, quit_gracefully)
# Creating a named pipe
if not os.path.exists(PIPE_FILE):
os.mkfifo(PIPE_FILE)
save_link()
# Main loop
while not daemon_quit:
# Open named pipe and csv
pipe = open... |
def WORD_SIZE():
return 3
def expand_key(k, t):
ks = [0 for i in range(t)]
ks[0] = k[len(k)-1]
l = list(reversed(k[:len(k)-1]))
for i in range(t-1):
l[i%3], ks[i+1] = enc_one_round((l[i%3], ks[i]), i)
return(ks)
def encrypt(p, ks):
x, y = p[0], p[1]
for k in ks:
x,y = enc... | This function constructs a unitary matrix U for the Speck cipher by mapping each input x to its encrypted output y using a given key and number of rounds. It generates a permutation matrix where U[y][x] = 1, representing the encryption's bijective transformation. The list f records the output y for each input x, while ... | def speck_unitary(num_rounds,k) :
n = 2 * WORD_SIZE()
ks = expand_key(k, num_rounds)
U = np.zeros((2**n,2**n), dtype = complex)
f = []
for x in range(2**n):
r = x%(2**WORD_SIZE())
l = int(x / 2**WORD_SIZE())
ct = encrypt((l,r),ks)
y = ct[1]+(2**WORD_SIZE())*ct[0]
... |
def do_basic_fields(output_dict, root_element, root_path, domain, domain_meta_dict, error_fields_set):
for (field_tag, field_details_dict) in domain_meta_dict.items():
logger.info((f" FIELD domain:'{domain}' field_tag:'{field_tag}'"
f" {field_details_dict}"))
type_tag = fie... | The function `parse_domain_for_single_root` parses metadata fields from an XML `root_element` for a specified domain, validates against domain-specific configurations, and returns structured output or `None` if invalid. It processes basic, derived, domain-specific, and hash fields, checks if the domain matches a config... | def parse_domain_for_single_root(root_element, root_path, domain, domain_meta_dict, error_fields_set):
""" Parses for each field in the metadata for a domain out of the root_element passed in.
You may have more than one such root element, each making for a row in the output.
If the configuration ... |
def mainPrintMessage(self, message):
# self.main_message.append(self.printLineSeperator())
self.main_message.append(message)
self.main_message.append(self.printLineSeperator())
def embedIpythonInterpreter(self):
"""embed an IPyton QT Console Interpreter"""
self.ipyConsole = QIPyt... | This code initializes a GUI application by loading a UI layout, setting up version information, embedding an IPython interpreter, configuring network data visualization tools, and connecting UI actions (e.g., loading networks, running simulations) to corresponding functions. It prepares tabs for data inspection, result... | def __init__(self):
super(mainWindow, self).__init__()
uic.loadUi("resources/ui/main.ui", self)
self.mainPrintMessage(
"Welcome to pandapower version: "
+ pp.__version__
+ "\nQt vesrion: "
+ QT_VERSION
+ "\nGUI version: "
+... |
def DisplayUnsur():
st.header('Daftar Unsur Kimia')
st.write('')
col1, col2, col3, col4 = st.columns(4, gap='small')
daftar_data_unsur = list(data_unsur.items())
daftar_data_unsur.insert(50,('I',126.904))
with col1:
for i in range(0,21):
st.write('{} : {}'.format(daftar_data_... | The code defines a Streamlit app function `BrianGanteng()` that displays a sidebar menu with three options: 'Daftar Unsur', 'Kalkulator Senyawa', and 'Latihan Soal'. Based on user selection, it calls corresponding functions to display elements, calculate compounds, or provide exercises. The main task is to create an in... | def BrianGanteng():
pilihan = st.sidebar.selectbox('Menu', ['Daftar Unsur', 'Kalkulator Senyawa', 'Latihan Soal'])
if pilihan == 'Daftar Unsur': DisplayUnsur()
elif pilihan == 'Kalkulator Senyawa': GilaCuyBrianGantengBanget()
elif pilihan == 'Latihan Soal': BrianGantengPunyaNisa() |
def check_out_path(out_path):
if os.path.exists(out_path):
overwrite = (
input(
"Output JSON {} already exists. Overwrite? [Y/N]: ".format(
out_path)
).lower()
== "y"
)
if not overwrite:
logging.info("Skippin... | The code saves records to JSON files in a specified directory. It creates the directory if it doesn't exist, then generates two types of files: one summarizing the best GEMM strategies per parameter, and individual files for each strategy containing performance data (timing metrics) grouped by GEMM parameters, either o... | def save_to_jsons(self, out_dir, only_best_config=True):
""" Save records to an output directory of JSON files.
The directory is organized such that each strategy gets its own JSON file.
The directory also includes a JSON file to define the best strategy per GEMM Param.
"""
if no... |
def html_select_for_enum_type(name, d: FieldDesc):
"""convert an enum type to a html select dropdown"""
# id = ".".join([x for x in (d["parent"], d["fieldname"]) if x is not None])
el_id = d.qualified_name()
el_name = el_id
print(d.inner_type)
print(",".join([e.value for e in d.inner_type]))
# FIXME: add... | This function generates HTML input elements for primitive data types based on their handler type. It routes to specialized helpers for enums, basic types (str/int/datetime/bool/float), and constrained numeric types. Unrecognized handlers trigger a warning and error, ensuring proper UI rendering for form fields in a sch... | def html_for_primitive_type(name, d: FieldDesc, **kwargs):
"""convert a primitive type (str, int, etc) to HTML
name: str, name of the type
# FIXME: remove
"""
if d.handler == "enum":
return html_select_for_enum_type(name, d)
elif d.handler in ("str", "int", "datetime", "bool", "float"):
retu... |
def html_for_primitive_type(name, d: FieldDesc, **kwargs):
"""convert a primitive type (str, int, etc) to HTML
name: str, name of the type
# FIXME: remove
"""
if d.handler == "enum":
return html_select_for_enum_type(name, d)
elif d.handler in ("str", "int", "datetime", "bool", "float"):
retu... | The main task of the code is to generate HTML form elements for a dictionary type, enabling dynamic key-value pair input and management. It creates editable fields for keys and values, handles various data types (primitive, basemodel, nested dicts), and constructs collapsible sections with add/remove buttons. The HTML ... | def html_for_dict_type(name, d: FieldDesc):
"""convert a dict to HTML
this type requires an editable key-value pair
and new key types to be created in the front end
NB: the `key` elements name-attribute are formatted `_<fieldname>-key`
`value` elements name-attribute are formatted `_<fieldname>-... |
def _load_existing_token(self):
self.access_token, self.access_token_secret = _AuthData.get()
return self.access_token is not None and self.access_token_secret is not None
def apply_auth(self) -> OAuth1:
return OAuth1(self.client_key,
client_secret=self.client_secret,
... | The code's main task is to retrieve or generate an access token via OAuth authentication. It attempts to load an existing token, otherwise opens an authorization URL in a browser, prompts the user for a Twitter PIN, obtains the access token, saves it, and returns the authenticated object. | def dance(self):
"""
Get the access token, save it, and return it
"""
if self._load_existing_token():
auth_object = self.apply_auth()
if self.check_auth(auth_object):
return auth_object
auth_url = self.get_authorization_url()
br... |
def parse(line):
ax, ay = line.split(',')
return int(ax), int(ay)
def sum_distances(point, coords):
return sum([distance(point, p) for p in coords])
def test_row(middle_x, y, coords, max_distance):
x = middle_x
while True:
if sum_distances((x, y), coords) < max_distance:
x += 1
... | The main task of the code is to count the number of coordinates within a specified maximum distance from a dynamically adjusted central point. It calculates an initial central point, verifies the distance, and iteratively expands upwards and downwards, adjusting the central x-coordinate based on valid rows, to accumula... | def part2(lines, max_distance=10000):
coords = [parse(line) for line in lines]
sum_x = sum([c[0] for c in coords])
sum_y = sum([c[1] for c in coords])
middle_x = sum_x // len(coords)
middle_y = sum_y // len(coords)
print("x: {}, y: {}".format(middle_x, middle_y))
middle_d = sum_distances(... |
def count(inf):
inFile = open(inf, 'r')
if inFile.readline() == '':
inFile.close()
return array_list.empty_list()
else:
inFile.close()
inFile = open(inf, 'r')
new = array_list.empty_list()
for temp in inFile:
for char in range (len(temp)):
index = ord(te... | The code performs Huffman encoding on the input file, writing the encoded data to the output file. It counts character frequencies, builds a Huffman tree, generates codes, writes header information (character lengths and frequencies), and encodes the input text using the generated codes. Edge cases like empty input are... | def huffman_encode(inf, outf):
hb_writer = HuffmanBitsWriter(outf)
c = count(inf)
x = build_leaf(c, comes_before)
if linked_list.length(x) == 0:
hb_writer.write_byte(0)
hb_writer.close()
return ''
lst = build_nodes(x)
new = chr_code(lst, c)
y = build_leaf(c, comes_before_character... |
def build_leaf(x, func):
#convert array into linked list
new = linked_list.empty_list()
for index in range (x.capacity):
if(array_list.get(x, index)) != None:
leaf_node = Leaf(chr(index), array_list.get(x, index))
new = linked_list.insert_sorted(new, leaf_node, func)
return new
def b... | This function decodes a Huffman-encoded file into the original text by reconstructing the Huffman tree from frequency data, traversing the tree based on encoded bits, and writing the decoded characters to an output file. | def huffman_decode(inf, outf):
hb_reader = HuffmanBitsReader(inf)
outFile = open(outf, 'w')
new = array_list.empty_list()
char_num = hb_reader.read_byte()
if char_num == 0:
hb_reader.close()
outFile.close()
return None
for i in range(char_num):
index = hb_reader.read_byte()
... |
def count(inf):
inFile = open(inf, 'r')
if inFile.readline() == '':
inFile.close()
return array_list.empty_list()
else:
inFile.close()
inFile = open(inf, 'r')
new = array_list.empty_list()
for temp in inFile:
for char in range (len(temp)):
index = ord(te... | The code tests the correctness of a Huffman coding implementation by comparing the frequency counts of characters from a file ('test.txt') against expected values, constructing Huffman tree nodes, and verifying generated binary codes match predefined expected codes stored in an array list. It ensures the count, build_l... | def test_count(self):
y = array_list.empty_list()
y = array_list.add(y, ord(' '), 3)
y = array_list.add(y, ord('a'), 4)
y = array_list.add(y, ord('b'), 3)
y = array_list.add(y, ord('c'), 2)
y = array_list.add(y, ord('d'), 1)
y.size = 0
self.assertEqual(count('test.txt'), ... |
def build_leaf(x, func):
#convert array into linked list
new = linked_list.empty_list()
for index in range (x.capacity):
if(array_list.get(x, index)) != None:
leaf_node = Leaf(chr(index), array_list.get(x, index))
new = linked_list.insert_sorted(new, leaf_node, func)
return new
def b... | This test decodes Huffman-encoded data by reading frequency counts from a binary file, reconstructing a frequency table, building a Huffman tree, and verifying the decoded size matches the expected value of 29. It checks if the decoding process correctly restores the original data size. | def test_length_of_decode(self):
hb_reader = HuffmanBitsReader('test_encoded.bin')
new = array_list.empty_list()
char_num = hb_reader.read_byte()
for i in range(char_num):
index = hb_reader.read_byte()
occ = hb_reader.read_int()
new = array_list.set(new, index, occ)
... |
def defaultFilters(self):
return {}
def customFilters(self):
return {}
def openResouceList(self, refresh=True):
if refresh:
self.updateView()
self._w = self.list_view | This code initializes a UI component for managing a resource list, setting up default and custom filters from a session, and populates a list box with data from openResouceList(). It configures filters, initializes a list walker, and sets up the UI widget for displaying resources with filter support. | def __init__(self):
self.session = Session.instance()
self.resource_name = type(self).__name__
if not self.resource_name in self.session.resource_filters:
self.session.resource_filters[self.resource_name] = self.defaultFilters()
if not self.resource_name in self.session.resou... |
def updateView(self, fetch = True):
self.lw.clear()
if fetch:
self.fetchResources()
count = 0
headings = self.getHeadings()
table = u.Columns([])
# TODO: Make a nice table for it
#for header in headings:
# table.contents.append((u.Filler(u.... | This code handles specific keypress events in a UI component. It triggers actions like updating the view (key 'r'), opening a filter editor (keys 'f' or '/'), and confirming an action (Enter when focused on actionEdit). It delegates unhandled keys to the parent class and returns the key otherwise. | def keypress(self, size, key):
# Have to invert this logic so that the downstream edits can get all the keystrokes first
if not super().keypress(size, key):
return
if key == "r":
self.updateView()
elif key == "f" or key == "/":
self.openFilterEdit()
... |
def __AirlightEstimation(self, HazeImg):
if (len(HazeImg.shape) == 3):
for ch in range(len(HazeImg.shape)):
kernel = np.ones((self.airlightEstimation_windowSze, self.airlightEstimation_windowSze), np.uint8)
minImg = cv2.erode(HazeImg[:, :, ch], kernel)
... | The code's main task is to correct a hazy image by estimating airlight, computing boundary constraints, calculating the transmission map, and applying dehazing. It returns the corrected image and the computed transmission map for further analysis or visualization. The process involves multiple private methods that hand... | def remove_haze(self, HazeImg):
self.__AirlightEstimation(HazeImg)
self.__BoundCon(HazeImg)
self.__CalTransmission(HazeImg)
haze_corrected_img = self.__removeHaze(HazeImg)
HazeTransmissionMap = self._Transmission
return (haze_corrected_img, HazeTransmissionMap) |
def get_from_continious(self, action):
length = int(round((action[0] / 2 + 0.5) * (self.length - 1), 0))
breadth = int(round((action[1] / 2 + 0.5) * (self.breadth - 1), 0))
position = length + breadth * self.length
return position
def get_state(self):
state = self.terminal.get_co... | The main task of the code is to simulate a container terminal operation in a reinforcement learning environment. It handles loading/unloading containers based on the action type (discrete/continuous), updates the state, calculates rewards (penalties for full slots, success bonuses), tracks steps, and determines episode... | def step_v2(self,
action: np.array
) -> Tuple[np.array, float, bool, bool, str]:
reward = 0.
if self.act_type == 'discret':
position = action.item()
elif self.act_type == 'continuous':
position = self.get_from_continious(action)
if self.n... |
def cut_mixer(data, target):
target = target.unsqueeze(dim=1)
mix_data = data.clone()
mix_target = target.clone()
u_rand_index = torch.randperm(data.size()[0])[:data.size()[0]].cuda()
u_bbx1, u_bby1, u_bbx2, u_bby2 = rand_bbox_1(data.size(), lam=np.random.beta(4, 4))
for i in range(0, mix_data.... | (The code computes a combined supervised and unsupervised loss using CutMix augmentation for semi-supervised learning. It generates pseudo-labels via an EMA model, applies CutMix to unlabeled data, and calculates a supervised loss on labeled samples and a cutmix loss on augmented unlabeled data, returning their sum for... | def compute_cutmix(h, w, imgs, labels, criterion, model, ema_model, image_u, threshold):
with torch.no_grad():
pred = ema_model(image_u)
pred = F.interpolate(pred, (h, w), mode="bilinear", align_corners=False)
pred = F.softmax(pred, dim=1)
pred_logit, pred_label = torch.max(pred, dim... |
def execute_short_circuit(app, bus=None):
'''
Excecutes a short circuit study in the appropriate settings.
If a bus object is passed in, it only calculates the fault at that particlar bus, this was primarily
used for testing
'''
if not bus:
shc = app.GetFromStudyCase('ComShc')
sh... | (The main task of the code is to calculate short-circuit (AFL) values at terminal elements for PIA scenarios in a power system project, then export results to a CSV file and generate a KML file for visualization. It processes multiple study cases, filters buses with GPS data, executes short-circuit calculations, extrac... | def main(app, project):
'''
Calculates the AFL at each terminal element and creates the KML file for viewing
'''
app = pf.GetApplication()
app.ClearOutputWindow()
project = app.GetActiveProject()
if project is None:
logger.error("No Active Project or passed project, Ending Script")
... |
def multiple_modal_select_browser(app, input_list, title):
""" This function allows the user to select a multiple objects from a folder,
if a folder is selected it then allows the user to look in that folder and select
"""
valid_selection = False
is_folder = False
while valid_selection == Fals... | The main task of the code is to perform fault level analysis (PIA) on selected power system study cases under various generator configurations. It prompts users to select study cases, short-circuit sets, buses, and operational scenarios, then runs fault calculations for four scenarios (sync-only, sync+new, all+new, all... | def fault_level_summary_pia(app, project=None):
"""
Description
"""
study_case_folder = app.GetProjectFolder("study")
current_script = app.GetCurrentScript()
#do input checks
#ask user to select study cases they are interested in running
study_cases = multiple_modal_select_browser(app,... |
def rank_routes(self, population):
return sorted(population, key=lambda x: self.get_route_distance(x))
def breed(self, parent1, parent2):
child = []
gene1, gene2 = random.sample(range(1, len(parent1) - 1), 2) # avoid the first and last element
start_gene = min(gene1, gene2)
end_... | The code generates the next generation in a genetic algorithm by selecting elite individuals from the current generation, breeding new children through crossover between randomly chosen elites, applying mutation to the children, and combining the elites with the new offspring to form the next generation. | def next_generation(self, current_gen):
elite = self.rank_routes(current_gen)[:self.elite_size]
rest = current_gen[self.elite_size:]
children = []
for i in range(len(rest)):
parent1 = random.choice(elite)
parent2 = random.choice(elite)
child = self.bre... |
def rank_routes(self, population):
return sorted(population, key=lambda x: self.get_route_distance(x))
def breed(self, parent1, parent2):
child = []
gene1, gene2 = random.sample(range(1, len(parent1) - 1), 2) # avoid the first and last element
start_gene = min(gene1, gene2)
end_... | The main task of the code is to generate the next generation in an evolutionary algorithm by preserving elite individuals from the current generation and creating offspring through breeding and mutation of selected elites. It combines the elites with newly generated children to form the next generation, ensuring divers... | def next_generation(self, current_gen):
elite = self.rank_routes(current_gen)[:self.elite_size]
rest = current_gen[self.elite_size:]
children = []
for i in range(len(rest)):
parent1 = random.choice(elite)
parent2 = random.choice(elite)
child = self.bre... |
def get_legal_actions(self, agent, game_state):
legal_actions = []
x, y = self.get_agent_location(agent, game_state)
for i in range(9):
adj_x = x + self.dRow[i]
adj_y = y + self.dCol[i]
if self.is_valid(adj_x, adj_y) and not game_state[adj_x][adj_y] in self.fo... | The main task of the code is to determine the optimal action for player 'A' in a game by evaluating all legal moves using the minimax algorithm. It calculates scores for each possible action, selects the highest-scoring ones, and randomly chooses one to return as the final move. This implements a decision-making strate... | def get_action(self, game_state):
possible_actions = self.get_legal_actions('A', game_state)
action_scores = [self.minimax('A', 0, self.generate_successor(game_state, 'A', action)) for action
in possible_actions]
max_action = max(action_scores)
max_indices = [ind... |
def alts(
self: Alts,
before,
after,
heap,
productions: list[Production],
state: State,
):
for alt in self.vals:
L = before + [alt] + after
L = flatten(L, state)
heap.push(L)
def cons(
self: Cons,
before,
after,
heap,
productions: list[Production],... | This function processes an expression `e` by dispatching to specialized derivation-handling functions (alts, cons, rep, opt, sym) based on its type. It adds derivations to a grammar or transformation system, using context parameters like `before`, `after`, `heap`, `productions`, and `state` to manage the derivation pro... | def add_derivations(e, before, after, heap, productions, state):
if isinstance(e, Alts):
return alts(e, before, after, heap, productions, state)
elif isinstance(e, Cons):
return cons(e, before, after, heap, productions, state)
elif isinstance(e, Rep):
return rep(e, before, after, hea... |
def write_to_serial_port(self, data, location='1'):
try:
sp = serial.Serial(self.config('serial', location,'address'),self.config('serial', location,'baud'), timeout=0)
sp.flush()
logger.debug("Wrote to serial port: " + data)
sp.write((data + '\r').encode())
te... | The code processes incoming requests to control an audio device via serial communication. It handles commands like setting sources, tuning radio, adjusting volume, muting, and audio equalization (treble/base). It caches values for state tracking, sends appropriate serial commands, and uses callbacks to notify the syste... | def ProcessRequest(self,callbacks,request):
logger.debug("Aton Request: " + str(request))
requestName = request['name'].split('_')
if request['value'] != 'get':
if (requestName[0] == 'source'):
self.write_to_serial_port('&AH66,AUD,' + requestName[2] + ',' + request['value'... |
def get_next_song(self):
logger.debug("Get Next Song")
if self.station_playlist == None:
self.station_playlist = self.station.get_playlist()
try:
song = next(self.station_playlist)
except:
self.station_playlist = self.station.get_playlist()
... | This method processes incoming requests to control Pandora music playback, manage station selections, handle pause/play actions, update song metadata, and trigger next songs. It maintains state via a cache, communicates with VLC for playback, and sends status updates through message queues, ensuring seamless user inter... | def run(self):
while True:
#Wait for either the end of a song or item in queue
try:
request = self.receive_message.get(True, 0.5)
logger.debug("Pandora Request: " + str(request))
if request['name'] == "stationlist":
... |
def load_i3d_pretrained(device=torch.device('cpu')):
filepath = '/home/ysy/ysy/workspace/diffusion_models/video_diffusion/video-diffusion-pytorch-main-2d-channel-atten-cond/check_points/i3d_torchscript.pt'
if not os.path.exists(filepath):
os.system(f"wget {i3D_WEIGHTS_URL} -O {filepath}")
i3d = torc... | The code calculates the Frechet Video Distance (FVD) between two videos by extracting features using a pre-trained I3D model, then computing the Frechet distance between the feature distributions of the two videos to quantify their dissimilarity. | def calculate_fvd(video1,video2):
i3d = load_i3d_pretrained(video1.device)
a_f = get_fvd_feats(video1, i3d, video1.device, bs=10)
b_f = get_fvd_feats(video2, i3d, video2.device, bs=10)
fvd = frechet_distance(a_f,b_f)
return fvd |
def unary(self):
if self.check_token(TokenType.PLUS) or self.check_token(TokenType.MINUS):
self.emitter.emit(self.curr_token.text)
self.next_token()
self.primary()
def check_token(self, kind):
return kind == self.curr_token.kind
def next_token(self):
self.curr_tok... | The `term` method processes multiplication and division operations by repeatedly checking for `*` or `/` tokens. It emits the operator, advances the token stream, and calls `unary()` to handle operands. This loop ensures all sequential multiplicative operations are parsed and emitted in order, forming part of an expres... | def term(self):
self.unary()
while self.check_token(TokenType.ASTERISK) or self.check_token(TokenType.SLASH):
self.emitter.emit(self.curr_token.text)
self.next_token()
self.unary() |
def term(self):
self.unary()
while self.check_token(TokenType.ASTERISK) or self.check_token(TokenType.SLASH):
self.emitter.emit(self.curr_token.text)
self.next_token()
self.unary()
def check_token(self, kind):
return kind == self.curr_token.kind
def next_toke... | The code parses arithmetic expressions with addition and subtraction. It starts by parsing a term, then repeatedly checks for '+' or '-'. When found, it emits the operator, advances the token, and parses another term, effectively building the expression structure by handling operators and operands sequentially. | def expression(self):
self.term()
while self.check_token(TokenType.PLUS) or self.check_token(TokenType.MINUS):
self.emitter.emit(self.curr_token.text)
self.next_token()
self.term() |
def expression(self):
self.term()
while self.check_token(TokenType.PLUS) or self.check_token(TokenType.MINUS):
self.emitter.emit(self.curr_token.text)
self.next_token()
self.term()
def is_comparison_operator(self):
return (
self.check_token(TokenT... | This method parses and emits comparison operators between expressions. It first evaluates an expression, checks for a comparison operator, emits it, and continues parsing subsequent expressions and operators. If no operator is found, it aborts with an error. The loop handles multiple consecutive comparisons, ensuring v... | def comparison(self):
self.expression()
if self.is_comparison_operator():
self.emitter.emit(self.curr_token.text)
self.next_token()
self.expression()
else:
self.abort("Expected comparison operator at: " + self.curr_token.text)
while self.... |
def check_token(self, kind):
return kind == self.curr_token.kind
def next_token(self):
self.curr_token = self.peek_token
self.peek_token = self.lexer.get_token()
def expression(self):
self.term()
while self.check_token(TokenType.PLUS) or self.check_token(TokenType.MINUS):
... | This function parses and emits C code for various statements in a custom language, handling PRINT, IF, WHILE, LABEL, GOTO, LET, and INPUT constructs. It processes tokens, validates syntax, manages symbols, and generates corresponding C code for control flow, variables, and input/output operations. | def statement(self):
# "PRINT" (expression | string)
if self.check_token(TokenType.PRINT):
self.next_token()
if self.check_token(TokenType.STRING):
self.emitter.emit_line(f'printf("{self.curr_token.text}\\n");')
self.next_token()
else:... |
def build_engine(weights):
# For more information on TRT basics, refer to the introductory samples.
with trt.Builder(TRT_LOGGER) as builder, builder.create_network() as network:
builder.max_workspace_size = common.GiB(1)
# Populate the network using weights from the PyTorch model.
popula... | The main task of the code is to perform single-image inference using a TensorRT-optimized Adder Layer model. It loads model weights, builds a TensorRT engine, allocates buffers, executes inference on a test case, and prints the output feature map for validation. The process verifies the TensorRT implementation's correc... | def single_image_inference():
print("####Testing the output of TensorRT implementation of the Adder Layer###")
adder_model = SingleAdder()
weights = adder_model.get_weights()
# Do inference with TensorRT.
with build_engine(weights) as engine:
# Build an engine, allocate buffers and create a... |
def getJgFileAsCleanedLines(filePath):
f = open(filePath, "r")
lines = f.readlines()
return lines
def getLexemData(lexeme, line):
return {
"value": lexeme,
"type": getLexemeType(lexeme),
"line": line,
}
def analyzeStatementSyntax(lexemesInLine):
statement = ""
rawStatement = ""
L... | The code analyzes the syntax of a custom language file by tokenizing each line, categorizing lexemes, and checking for errors. It tracks correct, error-prone, and unidentified statements, logs errors to a file, and returns processed lexemes, line-wise breakdowns, and error counts. The function handles operators, identi... | def analyzeSyntax(filePath):
correctStatements = 0
errorStatements = 0
incorrectStatements = 0
actLineNum = 0
formingLexem = ""
insideString = False
errorLogs = []
lexemes = []
lexemesInLines = []
for line in getJgFileAsCleanedLines(filePath):
lexemesInLine = []
actLineNum += 1
lineInde... |
def combination_to_coordinates_with_width_and_color(combination, flow_paths, slot_coordinates):
"""Transforms a combination into a tuple with its coordinates and width"""
coords_widths = []
for width, path_list, color in flow_paths:
coords = combination_to_coordinates(combination, slot_coordinates)
... | Your return
The function calculates the ratio of overlapping areas to the total area of rectangles generated from a combination's lines. It converts the combination into coordinate-based rectangles, computes their total area, and then determines the overlapping area using `line_overlap`. The result is the overlap rat... | def total_overlap_ratio(combination, flow_paths, slot_coordinates):
"""Calculate the ratio of total overlap"""
comb_width = combination_to_coordinates_with_width_and_color(combination, flow_paths, slot_coordinates)
rect_comb = [] # a list of lists with rectangles, representing the lines
total_overlap =... |
def test(self, epoch, testloader, dist_metric='euclidean', normalize_feature=False,
visrank=False, visrank_topk=10, save_dir='', use_metric_cuhk03=False,
ranks=[1, 5, 10, 20], rerank=False):
r"""Tests model on target datasets.
.. note::
This function has been call... | This function provides a unified pipeline for training and evaluating a model. It handles training over specified epochs, periodic evaluation on test datasets, checkpoint saving, and optional visualization of results. The process includes training with layer-specific freezing, distance metric configuration, and re-rank... | def run(self, save_dir='log', max_epoch=0, start_epoch=0, fixbase_epoch=0, open_layers=None,
start_eval=0, eval_freq=-1, test_only=False, print_freq=10,
dist_metric='euclidean', normalize_feature=False, visrank=False, visrank_topk=10,
use_metric_cuhk03=False, ranks=[1, 5, 10, 20], re... |
def read_dtc1(self):
if self.dtc1_state == 1:
data_to_send = "25500"
elif self.dtc1_state == 0:
data_to_send = "02550"
client.send(bytes('0x62' + '01' + data_to_send, "utf-8"))
def read_dtc2(self):
if self.dtc2_state == 1:
data_to_send = "25500"
... | This function processes received data to determine diagnostic mode and handle specific Diagnostic Trouble Codes (DTCs). It checks for '0x3E0'/'0x3E01' to set diag_mode, extracts DTC identifiers from '0x22' or '0x2E' patterns, and triggers corresponding methods like read_dtcX() or set_ledX() based on extracted values. I... | def recv_handler(self, stop_event):
global client
recv_data = client.recv(1024).decode("utf-8")
# print("Received data:", recv_data)
diag_mode = ""
if recv_data == '0x3E0':
diag_mode = 0
elif recv_data == '0x3E01':
diag_mode = 1
if diag_mod... |
def check_mandatories_valid() -> bool:
if is_structure_valid() and is_image_types_valid(allowed_image_extensions):
print("Structure is valid")
return True
return False
def is_json_valid(json_file : Dict [Any , Any] = json_data) -> bool:
# Check if json file exists
if has_json and not isi... | The main task of the code is to validate if a given folder path contains a valid structure with mandatory files, valid JSON data, and valid YAML files. It changes the working directory to the provided path, checks these conditions, and returns `True` if all validations pass, otherwise `False`. Exceptions during path va... | def is_folder_valid(given_path : str) -> bool:
try:
print("Given Path : ", given_path)
os.chdir(given_path)
if check_mandatories_valid() and is_json_valid(json_data) and is_yaml_valid():
print("Structure and files are valid")
return True
return False
... |
def drawGameState(gameBoard,comSymbol,humSymbol):
"""method to draw the state of the game/ this method draws 3 by 3 game board.
and have the following parameters.
gameBoard:array of numbers(9) to be drawen.
comSymbol:computer as player has x or o symbol.
humSymbol:human as player has x o... | This function initializes the second level of a game, handling human and computer moves. It validates human input, updates the game board, checks for a win/draw, then executes the computer's move using an agent algorithm. It returns the game outcome ("human", "agent", or "draw") based on evaluation results after each m... | def levelTwoGameStarting(gameBoard,player1,player2,x,y):
"""method to start the second level of the game and have the following parameters.
gameBoard:array of numbers(9) current state of the game.
x:computer as player has x or o symbol.
y:human as player has x or o symbol.
player1:-1(pla... |
def drawGameState(gameBoard,comSymbol,humSymbol):
"""method to draw the state of the game/ this method draws 3 by 3 game board.
and have the following parameters.
gameBoard:array of numbers(9) to be drawen.
comSymbol:computer as player has x or o symbol.
humSymbol:human as player has x o... | This function facilitates a two-player game where the computer (agent) and human take turns. It updates the game board with the computer's move, checks for a win/draw, then validates and applies the human's move, rechecking outcomes. It returns "human", "computer", or "draw" based on the game state after both moves. | def levelTwoGameSeconding(gameBoard,player1,player2,x,y):
"""method to start the second level but with different order of the game and have the following parameters.
gameBoard:array of numbers(9) current state of the game.
x:computer as player has x or o symbol.
y:human as player has x or o sym... |
def levelOneGameStarting(gameBoard,player1,player2,x,y):
"""method to start the first level of the game and have the following parameters.
gameBoard:array of numbers(9) current state of the game.
x:computer as player has x or o symbol.
y:human as player has x or o symbol.
player1:-1(play... | The main task of the code is to manage a two-level game process. It initializes the game board, determines player symbols (X/O), and alternates between two game levels. The function handles game progression, checks results after each level, and returns whether the game continues. It first runs Level One, processes outc... | def startingPlayer(gameBoard,x,y,player1=-1,player2=1):
"""method that starts the both level of the game in first order and have the following parameters.
gameBoard:array of numbers(9) current state of the game.
x:computer as player has x or o symbol.
y:human as player has x or o symbol.
... |
def levelTwoGameStarting(gameBoard,player1,player2,x,y):
"""method to start the second level of the game and have the following parameters.
gameBoard:array of numbers(9) current state of the game.
x:computer as player has x or o symbol.
y:human as player has x or o symbol.
player1:-1(pla... | The main task of the code is to manage a two-level game process, alternating between starting and seconding game phases. It initializes game states, determines player symbols (x/o), handles game outcomes via `levelTwoGameStarting` and `levelTwoGameSeconding`, and returns whether the game continues based on results from... | def secondingPlayer(gameBoard,x,y,player1=-1,player2=1):
"""method that starts the both level of the game in second or other order and have the following parameters.
gameBoard:array of numbers(9) current state of the game.
x:computer as player has x or o symbol.
y:human as player has x or o sym... |
def initializeGame(gameBoard):
"""This method initilizes the Game from the gameBoard.
params:gameBoard(current state of the game).
return:None
"""
print("----------WELCOME--------------")
drawGameState(Board,"","")
for i in "---------LEVEL ONE---------":
print(i,end="")
... | This function manages a turn-based game on a 9-element board, allowing a human (player1) and computer (player2) to take turns placing their symbols (-1 and 1). It initializes the game, prompts for player symbol choice, determines who starts based on user input, and alternates turns until the game concludes. The core ta... | def playingGame(gameBoard,player1=-1,player2=1):
"""method that the game based on the give order and have the following parameters.
gameBoard:array of numbers(9) current state of the game.
player1:-1(player)
player2:1(computer)
"""
initializeGame(gameBoard)
playing=True
while T... |
def predict(self, X):
"""
Invokes the transform method on Estimator object on JVM if X and y are on of the supported data types
Parameters
----------
X: NumPy ndarray, Pandas DataFrame, scipy sparse matrix or PySpark DataFrame
"""
try:
if self.estimat... | The `predict_proba` method computes predicted class probabilities for input data `X` by interfacing with a JVM-based estimator. It handles supported data types (NumPy, Pandas, sparse matrices, PySpark DataFrames) by converting `X` to a Java object, invoking `transform_probability` on the JVM model, and converting the r... | def predict_proba(self, X):
"""
Invokes the transform_probability method on Estimator object on JVM if X and y are on of the supported data types
Return predicted class probabilities for X.
Parameters
----------
X: NumPy ndarray, Pandas DataFrame, scipy sparse matrix or ... |
def _fit(self, X):
"""
Invokes the fit method on Estimator object on JVM if X is PySpark DataFrame
Parameters
----------
X: PySpark DataFrame that contain the columns features_col (default: 'features') and label_col (default: 'label')
"""
if hasattr(X, '_jdf') an... | The `fit` method trains a machine learning model by adapting input data (`X` and `y`) to the JVM-based Estimator. It supports NumPy arrays, Pandas DataFrames, and sparse matrices. If `y` is `None`, it calls `_fit` on `X`. For valid inputs, it encodes `y`, validates data consistency (row count, column shape), converts d... | def fit(self, X, y=None, params=None):
"""
Invokes the fit method on Estimator object on JVM if X and y are on of the supported data types
Parameters
----------
X: NumPy ndarray, Pandas DataFrame, scipy sparse matrix
y: NumPy ndarray, Pandas DataFrame, scipy sparse matri... |
def getActiveWindowID():
temp=bash("xdotool getactivewindow")
temp=bash("printf 0x%08x "+temp)
return str(temp)
def AW():
global window
return window[getActiveWindowID()]
def moveWindow(id,x,y):
if isinstance(id,Window):
id=id.id
bash("timeout 0.1 xdotool windowmove --sync "+id+" "+... | This code calculates and saves the border dimensions (left, right, up, down) of the active window by temporarily moving it to (0,0), extracting its position data via xwininfo, and restoring its original position. It stores X/Y offsets and border values in global variables, then writes them to "myfile.txt" for later use... | def borders():
global X0
global Y0
global BORDER
global BORDER_LEFT
global BORDER_RIGHT
global BORDER_DOWN
global BORDER_UP
X0=0
Y0=0
BORDER=0
BORDER_LEFT=0
BORDER_RIGHT=0
BORDER_DOWN=0
BORDER_UP=0
aw=str(getActiveWindowID())
backup=deepcopy( AW() )
... |
def moveWindow(id,x,y):
if isinstance(id,Window):
id=id.id
bash("timeout 0.1 xdotool windowmove --sync "+id+" "+str(x)+" "+str(y))
return loadWindow(id)
def resizeWindow(id,x,y):
if isinstance(id,Window):
id=id.id
bash("timeout 0.1 xdotool windowsize --sync "+id+" "+str(int(x)-... | The function aligns a window's position and size to a grid by adjusting its coordinates and dimensions using remainders. It first moves the window to align its top-left corner, then loops to resize it, ensuring the bottom-right corner aligns with the grid. The process repeats up to twice or until alignment is achieved,... | def roundWindow(w):
if(isinstance(w,int) or isinstance(w,str)):
w=window[str(w)]
remx=math.remainder(w.x,GRID)
remy=math.remainder(w.y,GRID)
w=moveWindow(w,w.x-remx,w.y-remy)
#TODO add rounding of widnow size too
#w=loadWindow(w.id)
#print("x:",remx," y",remy)
i=0
#while int(... |
def moveWindow(id,x,y):
if isinstance(id,Window):
id=id.id
bash("timeout 0.1 xdotool windowmove --sync "+id+" "+str(x)+" "+str(y))
return loadWindow(id)
def resizeWindow(id,x,y):
if isinstance(id,Window):
id=id.id
bash("timeout 0.1 xdotool windowsize --sync "+id+" "+str(int(x)-... | The function adjusts a window's position and size by adding a 10-pixel margin to its coordinates and reducing its dimensions by 20 pixels (10 on each side), then returns the updated window object using its ID. It handles integer/string inputs by mapping them to window objects, ensuring consistent processing for window ... | def unroundWindow(w):
if(isinstance(w,int) or isinstance(w,str)):
w=window[str(w)]
mar=10
w=moveWindow(w,w.x+mar,w.y+mar)
w=resizeWindow(w,w.width-2*mar,w.height-2*mar)
return loadWindow(w.id) |
def moveWindow(id,x,y):
if isinstance(id,Window):
id=id.id
bash("timeout 0.1 xdotool windowmove --sync "+id+" "+str(x)+" "+str(y))
return loadWindow(id)
def resizeWindow(id,x,y):
if isinstance(id,Window):
id=id.id
bash("timeout 0.1 xdotool windowsize --sync "+id+" "+str(int(x)-... | This function swaps the positions and sizes of two windows. It converts input IDs to window objects, creates a backup of the focused window's state, applies the candidate window's properties to the focused window, then applies the backup's properties to the candidate window. Finally, it triggers rounding operations on ... | def swapWindows(focused,candidate):
if(isinstance(focused,int) or isinstance(focused,str)):
focused=window[str(focused)]
if(isinstance(candidate,int) or isinstance(candidate,str)):
candidate=window[str(candidate)]
backup=deepcopy(focused)
moveWindow(focused,candidate.x,candidate.y)
... |
def resizeWindowDirSafe(w,dir):
if(isinstance(w,int) or isinstance(w,str)):
w=window[str(w)]
w=roundWindow(w)
backup=deepcopy(w)
modx=0
mody=0
if dir=="left": modx=-GRID
elif dir=="right": modx=GRID
elif dir =="up": mody=-GRID
elif dir =="down": mody=GRID
w=resizeWindow... | The main task of the code is to resize a focused window in a specified direction (left/right/up/down) while adjusting adjacent windows. It identifies windows to resize (same size/position) and those to move/resize oppositely. It performs operations safely, reverting changes if any step fails. The function ensures tilin... | def resizeM(focused,dir):
print("Tiled resize")
#1.get list of windows at center (only to resize)
#2.get list of windows that are sticking to, and will be needed to be moved and resized
if(isinstance(focused,int) or isinstance(focused,str)):
focused=window[str(focused)]
toResize=[]
to... |
def blahut_arimoto(W, iterations=10):
'''
Computes the channel capacity C(W)= max_Q I(Q, W),
where the mutual information is given by:
I(Q,W) = I(Q) = \sum_x \sum_y Q(x)W(y|x)log(V(x|y)/Q(x)).
Q(x) = P(X=x) <--- want to find this! in order to maximize I(Q, W).
R(y) = P(Y=y) = (QW)(y) = \sum_x W(y|... | This code computes the channel capacity of a biological communication channel using the Blahut-Arimoto algorithm. It constructs a probability matrix from codon-amino acid mappings, applies noise parameters, calculates capacity iteratively, and evaluates a "hunch channel capacity" formula. Results are printed, with opti... | def main(args):
global log, exp
if args.bits:
log, exp = (lambda x: Decimal(x).log10()/Decimal(2).log10(), (lambda x: 2**x))
decimal.getcontext().prec = args.prec
# Get codon table.
rna = Bio.Data.CodonTable.unambiguous_rna_by_id[args.id]
Gx = {**rna.forward_table, **{codon: 'Stop' for codon in rna.st... |
def get_codon_mass(df, taxid):
'''
:df: the genbank_species pd.DataFrame.
:taxid: the taxonomy id for the species.
returns a 64 length numpy array for the codon mass (lexicographic order).
'''
# Extract correct row based on taxonomy id.
tf = df[(df['Taxid'] == taxid) & (df['Organelle'] == 'genomic')]
... | The main task of the code is to plot codon usage for a specific species, incorporating channel noise distribution. It retrieves species-specific codon usage data from a database, generates a noise model based on input parameters, and visualizes the results using a specified base unit (bits, nucleotides, or base e). The... | def disk(args, df):
'''Command if wanting to plot an individual species condon usage.'''
# Get codon usage from database.
Q, species = get_codon_mass(df, args.taxid)
# Generate channel noise distribution.
p = args.p
W = create_channel(p)
print(Q)
# Finally, plot the info.
base = 'bits' if args.bits ... |
def set_bits():
global log, exp
log, exp = np.log2, lambda x: 2**x
def disk(args, df):
'''Command if wanting to plot an individual species condon usage.'''
# Get codon usage from database.
Q, species = get_codon_mass(df, args.taxid)
# Generate channel noise distribution.
p = args.p
W = create_channel(p... | The main task of the code is to process command-line arguments, handle data loading with caching, and execute specified commands (e.g., 'disk', 'cluster') on biological data. It initializes logging/exponential functions based on input type (bits/nucleotides), loads data from CSV or cached pickle files, and routes execu... | def main(args):
global log, exp
assert not (args.bits and args.nucleotides), "pick only one base"
if args.bits:
set_bits()
if args.nucleotides:
log, exp = lambda x: np.emath.logn(len(Nucleotide), x), lambda x: len(Nucleotide)**x
if not args.no_cache and pathlib.Path(PICKLE_FILE).exists():
df = pd... |
def is_prime (num):
if num > 1:
# Iterate from 2 to n / 2
for i in range(2, num//2):
# If num is divisible by any number between
# 2 and n / 2, it is not prime
if (num % i) == 0:
return False
break
el... | The main task of the code is to generate an RSA public-private key pair given two distinct prime numbers p and q. It calculates the modulus n=p*q, Euler's totient z=(p-1)(q-1), and selects a public exponent e coprime to z. The private exponent d is derived from e and z, returning the key pairs ((e,n) public key, (d,n) ... | def generate_keypair(p, q):
if not (is_prime(p) and is_prime(q)):
raise ValueError('Both numbers must be prime.')
elif p == q:
raise ValueError('p and q cannot be equal')
###################################your code goes here#####################################
repeat = 0
n= p*q
... |
def beam_size(beam, pix_size=None):
"""
Calculates the beam spot parameters of a laser spot
from the 2D intensity data
Arguments:
beam: np.ndarray, 2D array holding data for each value
pix_size: size of each data pixel using units from astropy.units
default is 80 micro... | The main task of the code is to visualize and analyze a beam's spot characteristics, including its elliptical shape (center, radii, rotation), background-subtracted intensity distribution, and Gaussian-fitted profiles along the principal axes. It generates plots showing the original image, spot check with ellipse bound... | def spot_plot(beam, pix_size = None, cmap='plasma', just_spot=False):
plt.rc('axes', labelsize=8, titlesize=10)
plt.rc('legend', fontsize=8, handlelength=1)
plt.rc('xtick', labelsize=6)
plt.rc('ytick', labelsize=6)
plt.rc('pcolor', shading='auto')
x_center, y_center, r_x, r_y, phi = beam_size(... |
def create_vars(self):
self.var_info = tkk.StringVar(self)
# Type of variable
self.var_type = tkk.StringVar(self)
self.var_type.trace(
"w", lambda name, index, mode: self.update_type())
# type of interp for data
self.var_type_data = tkk.StringVar(self)
... | This code initializes a GUI application for handling subtitles. It sets up the main window, initializes data structures to store subtitle lists, selection states, and output configurations. The method loads subscript files, creates interface variables, and prepares the main window layout for user interaction with subti... | def __init__(self, master=None, subscript_file=None, output_file=None):
super().__init__(master)
self.master = master
self.pack(pady=10, padx=10)
self.all_subs = list()
self.non_selected_subs = self.all_subs.copy()
self.subs = []
self.description = ''
self... |
def exp(num_trials=40, display_data=False, **param_set):
"""
:param num_trials: the number of trials in the experiment
:param display_data: whether display data
:return:
"""
# prepare exp stimuli
trials = ASP(num_trials)
response_list_DOC = []
response_list_DOI = []
response_l... | This function runs multiple simulations using given parameters, computes the mean and standard deviation of results (prop_data and logodds_data), and returns a dictionary containing these statistics along with parameters. It performs `num_simulation` iterations, aggregates outcomes, and optionally prints mean/std value... | def simulations(num_simulation=2, print_data=False, **param_set):
"""
This function run the simulation with with a set of parameter set
:param num_simulation: int, the number of epochs simulation
:param output_data: True/False, the number of epochs simulation
:return: simulation ... |
def random_image_mirror_left_right(input_layer):
"""
Flip each image left-right like in a mirror, randomly, even at test-time.
This acts as a data augmentation technique. See:
https://stackoverflow.com/questions/39574999/tensorflow-tf-image-functions-on-an-image-batch
"""
return tensorflow.keras... | The code builds a customizable convolutional neural network (CNN) model using hyperparameters to define layers, filters, activation functions, regularization, and architecture choices. It constructs convolutional blocks with optional residual connections, pooling, dropout, and fully connected layers, then compiles the ... | def build_model(hype_space):
"""Create model according to the hyperparameter space given."""
print("Hyperspace:")
print(hype_space)
input_layer = tensorflow.keras.layers.Input(
(im_dim[0], im_dim[1], im_dim[2]))
current_layer = random_image_mirror_left_right(input_layer)
if hype_space... |
def get_edge(self, t2) -> int:
"""
get_edge(t2) -> int - Returns the edge index of this tile that matches t2. If there is no common edge
returns -1.
"""
for i in range(len(self.edges)):
e = self.edges[i]
for e2 in t2.edges:
... | This function reorients the current tile to align with tile t2 by rotating clockwise until the correct edge matches, then flipping if necessary to ensure the edge structure matches. It adjusts orientation based on whether t2 is to the left or above, using edge indices and flips to achieve alignment. | def orient(self, t2, left=False):
"""
orient(t2, left) - reorients this tile to match t2. Left defaults to False and, if true,
indicates that t2 is to the left of this tile. Otherwise it assumes
t2 is above this tile.
"""
# In order,... |
def choice(array, size, replace):
""" Returns a sample of a certain size for a numpy array. """
indices = np.random.choice(len(array), size=size, replace=replace)
sample = array[indices]
return sample
def distance(d1, d2):
""" Returns the distance metric for two direction vectors.
The distance ... | The function uses RANSAC to find the best color-line in a patch by testing random pixel pairs, calculating their RGB line hypothesis, and selecting the line that fits the most pixels within a threshold. It iterates multiple times, tracks the best-fitting line, generates a support matrix, and returns a ColorLine object ... | def ransac(patch, iterations=30, threshold=0.02):
"""Returns the color-line of a patch in vector form.
Iterates over pairs of 2 pixels. The line between each pixel pair in
RGB space is considered a line hypothesis. A certain number (`iterations`)
of these hypotheses are considered. The line that fits t... |
def init_widgets(self):
"""Initializes widgets and their properties"""
# Initialize the logo
self.logo = QLabel(self)
self.logo.setPixmap(QPixmap("images/omnilog_logo.png"))
self.logo.setAlignment(Qt.AlignHCenter | Qt.AlignBottom)
# Initialize the header
self.he... | This code initializes a GUI application's main window by setting up a central widget, defining data structures for a catalog and file management, configuring window properties, layout, and styles, and loading the last used catalog from a previous session to restore user context. | def __init__(self):
super().__init__()
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
# Initialize catalog variables
self.catalog = {"Profile": {"Category Names": {}, "Category Fields": {}, "Icon Paths": {}}, "Data": {}}
# Initialize file var... |
def update_frame_length(self, change_type):
"""Increases or decreases the length and height of the frame"""
if change_type == "increase":
self.frame_length += 65
self.vertical_position -= 30
elif change_type == "decrease":
self.frame_length -= 65
s... | This method initializes category UI elements by creating text fields and buttons for each category name, setting their properties, connecting events, and ensuring at least four categories are displayed by adding empty fields if needed. | def init_categories(self):
for idx in range(len(self.category_names)):
self.update_frame_length("increase")
key = str(idx)
self.row += 1
self.category_fields[key] = QLineEdit()
self.category_fields[key].setText(str(self.category_names[key]))
... |
def init_widgets(self):
"""Initializes widgets and their properties"""
# Initialize the header
self.header = QLabel(self.category + " Fields")
# Initialize, format, and set the event for all buttons
self.buttons = {"add_field": QPushButton(), "remove_field": QPushButton(), "ok"... | The code initializes a modal window for a category, setting up UI components, layout, styles, and category-specific fields to configure the window's behavior and appearance for data entry or display. | def __init__(self, category, category_fields):
super().__init__()
self.row = -1
# Set this window to always be on top when visible
self.setModal(True)
# Initialize category variables
self.category = category
self.category_fields = category_fields
# Init... |
def init_widgets(self):
"""Initializes widgets and their properties"""
# Initialize the header
self.header = QLabel("Manage Categories")
# Initialize, format, and set the event for all buttons
self.buttons = {"add_category": QPushButton(), "remove_category": QPushButton(), "ok"... | This code initializes a UI window for managing categories with icons, setting up modal behavior, category data, icon paths, window dimensions, and calling methods to configure widgets, layout, styles, and category-specific elements. | def __init__(self, category_names, category_icon_paths):
super().__init__()
self.row = -1
# Set this window to always be on top when visible
self.setModal(True)
# Initialize category variables
self.category_names = category_names
# Initialize icon variables
... |
def copy_other_installation_files():
global ALUSUS_ROOT
global INSTALL_PATH
infoMsg("Copying other installation files...")
shutil.rmtree(os.path.join(INSTALL_PATH, "Doc"), ignore_errors=True)
shutil.copytree(
os.path.join(ALUSUS_ROOT, "Doc"),
os.path.join(INSTALL_PATH, "Doc")
)
... | The main task of the code is to create installation packages by cleaning the target directory, copying necessary files, and generating platform-specific packages for Windows, Linux, or macOS. It raises an error if the current system is unsupported. | def create_packages():
global PACKAGES_PATH
global THIS_SYSTEM
infoMsg("Creating installation packages...")
shutil.rmtree(PACKAGES_PATH, ignore_errors=True)
os.makedirs(PACKAGES_PATH)
copy_other_installation_files()
if is_windows():
create_packages_windows()
elif is_linux() or i... |
def contact_list():
recipient_emails = []
print('Sir, once please listen to the contact list')
Text_to_speech('Sir, once please listen to the contact list')
for i in contacts:
print(f'{i}:{contacts[i]}')
Text_to_speech(f'{i}:{contacts[i]}')
while(1):
print('Sir,... | The main task of the code is to compose and send an email by collecting recipients from a contact list, capturing voice inputs for the subject and body using speech-to-text, and then generating the email with the Compose_email function. It relies on Text_to_speech for user prompts and Speech_to_text for input collectio... | def sending_email():
recipients = contact_list()
print('Please speak the subject of the Email:')
Text_to_speech('Please speak the subject of the Email')
subject = Speech_to_text()
print(subject)
print('Please speak the body of the Email')
Text_to_speech('Please speak the body of the Email')
... |
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS2
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def search... | The code initializes a main chat window by loading a UI file, setting up event handlers for user input and actions, and starting a background thread to update the chat window. It connects signals like search, send, and menu actions to corresponding methods, manages user list layout, and enables dark/light mode toggling... | def __init__(self):
super(MainChatWindow, self).__init__()
uic.loadUi(resource_path("ui\\chatting_window.ui"), self)
self.buttons_list = {}
self.search_bar.textChanged.connect(lambda: self.searchList(self.search_bar.text()))
self.v_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
... |
def getPlayerInput(game, currentPlayer):
'''
This function gets player the player input to select the square to play
Inputs: int of current player, instance of local game
Returns: tuple of selected square (row, col)
'''
# get list of numbers that are valid
boardSize = game.size
validInpu... | The main task of the code is to manage a Meta Tic Tac Toe game by initializing the game, alternating player turns, handling local board selections, playing classic/numeric Tic Tac Toe sub-games, updating the meta board state, checking for a meta winner, and repeating until a player wins or the game ends. It includes ga... | def main():
'''
This function calls the other functions to play the game
Input: None
Returns: None
'''
newGame=True
while newGame:
# print the header
line = "----------------------------------"
print(line,"\nStarting new Meta Tic Tac Toe game","\n"+ line+"\n")
... |
def getRequest(name):
temp = name.split(".")
request = ""
for i in range(len(temp)):
print("get request temp:" , temp)
host = temp[i]
host_length = len(host)
if host_length < 10:
host_length = "0" + str(host_length)
print("host length < 10", host_le... | The main task of the code is to resolve a domain name to an IPv4 address using a custom DNS-like protocol. It constructs a request header, sends it to a DNS server (1.1.1.1), parses the hexadecimal response, extracts the IP address via bitwise operations, converts it to a human-readable IPv4 format, and validates it ag... | def getIP(name):
header = "AA AA 01 00 00 01 00 00 00 00 00 00"
request = getRequest(name)
message = header + " " + request
print(message)
message = message.replace(" ","").replace("\n","")
print(message)
data,response = send_message(message, "1.1.1.1", 53)
print("Data", data)
print... |
def checkHostInDict(host):
if host in DNS_table.keys():
return True
else:
return False
def getIPFromTable(host):
return DNS_table[host]
def getIP(name):
header = "AA AA 01 00 00 01 00 00 00 00 00 00"
request = getRequest(name)
message = header + " " + request
print(message)
... | The code establishes a server socket on a specified port to accept client connections. It receives host data, checks a table for existing IP mappings, and retrieves or resolves IPs using helper functions. The result is formatted and sent back to the client, with unresolved hosts marked as errors. The server stores reso... | def connect_to_client(port):
list = []
sock_to_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('',port)
try:
sock_to_client.bind(server_address)
print("{S}: Socket create and bind successful")
except socket.error as err:
print("Error in socket bi... |
def remove_temp_files(*files):
for file in files:
if os.path.exists(os.path.join(temp_path, file)):
os.remove(os.path.join(temp_path, file))
def unpack_files():
if PesFacemodGlobalData.face_fpk != '':
# unpack face_high.fmdl, etc.
if not exec_tool(os.path.join('To... | The code handles PES face model import/export operations in Blender, unpacking files, loading facial/hair/oral models, integrating base scenes, and managing data. It checks file paths, imports models via FmdlManager classes, applies textures, and resets scenes. Operations include importing models, exporting, creating n... | def execute(self, context):
scn = context.scene
if not PesFacemodGlobalData.good_path(scn.face_path):
return {'FINISHED'}
global pes_face, pes_hair, pes_oral, face_type, hair_type, oral_type
if self.face_opname == "import_files":
if len(pes_face) != 0:
... |
def find_diff(mypath, fileAName, fileBName):
try:
# fileA = open(mypath + '/' + fileAName, "rt", encoding="utf-8").readlines()
fileA = mmap_io(mypath, fileAName)
# fileB = open(mypath + '/' + fileBName, "rt", encoding="utf-8").readlines()
fileB = mmap_io(mypath, fileBName)
except... | The main task of the code is to compare buggy and fixed versions of files, extract their differing lines, and save the corrected lines into designated output files. It checks for non-whitespace differences, records timestamps, and writes results while handling edge cases like empty lines by logging warnings and writing... | def generate_file(mypath, output_dir, item):
time_start = datetime.datetime.now()
line_num, fixed_line, buggy_line = find_diff(mypath, item[1]['buggy_file'], item[1]['fixed_file'])
if line_num and not is_whitespace_diff(buggy_line, fixed_line):
time_elapsed = datetime.datetime.now() - time_start
... |
def filter_instances(self, n):
if n < 1: return self.models, self.images
classes = list(set([Path(m).parents[1].name for m in self.models]))
classes.sort()
models = []
for cls in classes:
models += [m for m in self.models if Path(m).parents[1].name == cls][0:n]
... | This code initializes a dataset for 3D object recognition by loading images from a specified path, filtering based on split (train/valid/test), classes, and other parameters. It processes image-model associations, filters instances, generates pairs/triplets for training, and prints statistics like model/image counts an... | def __init__(self, path, split, use_failed=False, classes=None, filter_agree=False, discard_rate=0.0, use_rot=False, use_triplets=True, n_instances=-1):
super(ViewDataset, self).__init__()
assert split in ["train", "valid", "test", "all"], "unknown data set split: {}".format(split)
self.filter_a... |
def compute_predictions(self, pThreshold):
"""Method to compute the predictions.
Args:
pThreshold (float): Threshold used to divide the two classes.
"""
self.predictions_ = np.zeros_like(self.probabilities_, dtype=np.float64)
self.predictions_[self.probabilities_ >=... | This function computes the Receiver Operating Characteristic (ROC) curve by iterating through `pNumSteps+1` thresholds, calculating the False Positive Rate (FPR) and True Positive Rate (TPR) at each threshold using `compute_predictions`, and appending these values to an array. The result is reshaped into a 2D array of ... | def compute_ROC(self, pNumSteps):
roc = np.array([])
for thIter in range(pNumSteps + 1):
curThreshold = float(thIter)/float(pNumSteps)
self.compute_predictions(curThreshold)
roc = np.append(roc, [self.compute_FPR(), self.compute_TPR()])
return roc.reshape(-1, ... |
def __get_text(self):
__txt_file = Path(".results.txt")
if __txt_file.exists():
self.__text = __txt_file.read_text()
else:
with open(self.__pdf_file, 'rb') as file:
self.__text = ""
pdf_reader = PyPDF2.PdfReader(file)
for pa... | This code initializes a class to process a PDF file by extracting text, identifying patterns, and formatting the content, storing results in a dictionary. | def __init__(self, pdf_file=Path("results.pdf")):
self.__results = {}
self.__pdf_file = pdf_file
self.__get_text()
self.__patterns()
self.__format_text() |
def regn_area(self, iR):
"""Get the area of a region.
Parameters
----------
iR : int
Region index.
Returns
-------
regn_area : numpy.float64
Region area.
Examples
--------
>>> xy = numpy.array([[-0.25, -0.25], [0.... | The function `regn_centroid` calculates the geometric centroid of a specified region in a 2D mesh. It computes the weighted average of face centroids, where each face's contribution is proportional to its area. The result is normalized by dividing by the total area of the region, yielding the centroid coordinates as a ... | def regn_centroid(self, iR):
"""Get the centroid of a region.
Parameters
----------
iR : int
Region index.
Returns
-------
regn_centroid : tuple
Region centroid.
Examples
--------
>>> xy = np.array([[0.0, 0.0], [1... |
def draw_primal_mesh(self, ax, color, linestyle):
"""Draw primal mesh, i.e., mesh regions.
Parameters
----------
ax : matplotlib.axes._subplots.AxesSubplot
Axes which the primal mesh has to be added to.
color : str
Supported matplotlib color.
line... | The code generates a plot of a 2D mesh (Mesh2D) with customizable options for visualizing primal and dual meshes, bounding boxes, boundaries, region fills, and node/face/region indices. It uses matplotlib to create a figure, applies specified colors and line styles, and returns the plot objects for further customizatio... | def plot(self,
primal=True, primal_color="b", primal_linestyle="-",
m_dual=False, m_dual_color="r", m_dual_linestyle="--",
c_dual=False, c_dual_color="g", c_dual_linestyle="-.",
bbox=False, boundary=False, regn_to_fill=None,
vrtx_pos=False, face_pos=False... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.