dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def min_num_bits(a):
if a is undefined:
return undefined
return math.ceil(math.log(a, 2))
def _one(string, *, name="A"):
a = Int(string, name)
if NBits.value == -1:
NBits.value = min_num_bits(a.int)
one_comp = Int(ones_complement(a.out), f"~{name} ({NBits.value} bits)")
one_comp.... | The function `_two` computes and returns a list of integer operations between two inputs (`first` and `second`). It generates results for subtraction, addition, bitwise operations (OR, AND, XOR), two's complement, Hamming distance, and bit shifts. It also sets `NBits.value` based on the minimum bit requirements of the ... | def _two(first, second):
a = Int(first, "A")
b = Int(second, "B")
if NBits.value == -1:
NBits.value = max(min_num_bits(a.int), min_num_bits(b.int))
return [
*_one(first, name="A"),
*_one(second, name="B"),
Int(a.int - b.int, "A - B"),
Int(b.int - a.int, "B - A")... |
def checklen(strings, n):
if len(strings) != n:
raise JcoTerminate(f"Should have {n} inputs, got {len(strings)}: {strings}")
def tab(rows, **kwargs):
return tabulate(rows, tablefmt=Format.value, headers=["", "Dec", "Hex", "Bin"])
def _two(first, second):
a = Int(first, "A")
b = Int(second, "B")
... | The function processes input arguments by validating their count, transforms each data element by invoking its `row()` method if available, or using the data directly otherwise, then passes the resulting list to the `tab` function for further processing. | def two(*args, **kwargs):
checklen(args, 2)
return tab(
[data.row() if hasattr(data, "row") else data for data in _two(*args, **kwargs)]
) |
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def isfloatlist(value):
try:
possible_list = value.split(',')
for f in possible_list:
float(f)
return True
except ValueError:
return False
def refine(df,column,h_null,thr... | This Django view processes POST requests to validate statistical inputs (p-value, hypothesis, data), performs data refinement using a 'refine' function, and returns results or error messages based on validation. It converts CSV data to floats, checks input validity, and renders 'result.html' with refined data or 'faile... | def index(request):
if request.method == "POST":
desired_p = request.POST.get('p')
hyp = request.POST.get('h')
possible_csv = request.POST.get('data')
if len(desired_p) > 0:
if isfloat(desired_p):
desired_p = float(desired_p)
# check for va... |
def parse_arguments() -> argparse.Namespace: # pragma: no cover
"""Parse CLI arguments
:return: Dictionary of parsed arguments
"""
parser = argparse.ArgumentParser(description="Upload sbom metadata to Pyxis")
parser.add_argument(
"--pyxis-graphql-api",
default=os.environ.get("PYX... | The main task of the code is to upload an SBOM file to a Pyxis GraphQL API, validating the input file's existence, generating a hexadecimal image ID from the filename if unspecified, and handling retries if enabled. It configures logging, checks file validity, and executes the upload process with error handling for mis... | def main(): # pragma: no cover
"""Main func"""
args = parse_arguments()
log_level = logging.DEBUG if args.verbose else logging.INFO
pyxis.setup_logger(level=log_level)
if not os.path.isfile(args.sbom_path):
msg = f"sbom file does not exist: {args.sbom_path}"
LOGGER.error(msg)
... |
def fit(self, Tr_x, Tr_y):
'''
Trains the classifier which will be used in the fitness function
'''
if self.model is None:
self.training_X = Tr_x
self.training_Y = Tr_y
self.model = self.createModel()
hyper_X = self.convert(Tr_x)
self.model.fit(hyper_X,Tr_y)
def getTrainingPredictions(self):
... | The code calculates and returns an individual's fitness based on the specified type (Accuracy, Pearson, MSE, WAF, or 2FOLD) by training a model on provided data, evaluating predictions, and computing the corresponding metric. For 2FOLD, it splits data, trains two models, and averages their accuracies. The result is sto... | def getFitness(self, tr_x = None, tr_y = None):
'''
Returns the individual's fitness.
'''
if self.fitness is None:
if not tr_x is None:
self.training_X = tr_x
if not tr_y is None:
self.training_Y = tr_y
if self.fitnessType == "Accuracy":
self.fit(self.training_X, self.training_Y)
self... |
def getTrainingPredictions(self):
if self.trainingPredictions is None:
self.trainingPredictions = self.predict(self.training_X)
return self.trainingPredictions
def getTestPredictions(self, X):
if self.testPredictions is None:
self.testPredictions = self.predict(X)
return self.testPredictions
def predict... | This function calculates the Mean Squared Error (MSE) between predicted values and actual values Y. Depending on the 'pred' parameter, it retrieves training, test, or custom predictions. It returns the negative of the computed MSE, likely for optimization purposes where lower values indicate better performance. | def getMSE(self, X,Y,pred=None):
'''
Returns the individual's accuracy.
'''
if pred == "Tr":
pred = self.getTrainingPredictions()
elif pred == "Te":
pred = self.getTestPredictions(X)
else:
pred = self.predict(X)
return -1 * mean_squared_error(pred, Y) |
def getTrainingPredictions(self):
if self.trainingPredictions is None:
self.trainingPredictions = self.predict(self.training_X)
return self.trainingPredictions
def getTestPredictions(self, X):
if self.testPredictions is None:
self.testPredictions = self.predict(X)
return self.testPredictions
def predict... | The function calculates the accuracy of a model's predictions by comparing them against true labels. It determines predictions based on the 'pred' parameter: training predictions if 'Tr', test predictions if 'Te', or uses input data X otherwise. It returns the accuracy score using sklearn's accuracy_score metric. | def getAccuracy(self, X,Y,pred=None):
'''
Returns the individual's accuracy.
'''
if pred == "Tr":
pred = self.getTrainingPredictions()
elif pred == "Te":
pred = self.getTestPredictions(X)
else:
pred = self.predict(X)
return accuracy_score(pred, Y) |
def getTrainingPredictions(self):
if self.trainingPredictions is None:
self.trainingPredictions = self.predict(self.training_X)
return self.trainingPredictions
def getTestPredictions(self, X):
if self.testPredictions is None:
self.testPredictions = self.predict(X)
return self.testPredictions
def predict... | The function `getWaF` calculates an individual's **Weighted Average F1 Score (WAF)** by evaluating predictions (`pred`) against true labels (`Y`). Depending on the `pred` input ("Tr", "Te", or default), it retrieves training, test, or custom predictions. It then computes the **F1 score** with the `weighted` average to ... | def getWaF(self, X, Y,pred=None):
'''
Returns the individual's WAF.
'''
if pred == "Tr":
pred = self.getTrainingPredictions()
elif pred == "Te":
pred = self.getTestPredictions(X)
else:
pred = self.predict(X)
return f1_score(pred, Y, average="weighted") |
def getTrainingPredictions(self):
if self.trainingPredictions is None:
self.trainingPredictions = self.predict(self.training_X)
return self.trainingPredictions
def getTestPredictions(self, X):
if self.testPredictions is None:
self.testPredictions = self.predict(X)
return self.testPredictions
def predict... | This function calculates Cohen's Kappa score to evaluate agreement between predicted labels (from training, testing, or custom input) and true labels Y, returning the individual's kappa value as a measure of classification accuracy. | def getKappa(self, X, Y,pred=None):
'''
Returns the individual's kappa value.
'''
if pred == "Tr":
pred = self.getTrainingPredictions()
elif pred == "Te":
pred = self.getTestPredictions(X)
else:
pred = self.predict(X)
return cohen_kappa_score(pred, Y) |
def get_receiver_all_chat_counter_objects(chat_counter_list, account_list, myself_email):
receiver_chat_counters = []
copied_chat_counter_list = deepcopy(chat_counter_list)
all_matched_chat_counters = find_all_matched_chat_counters(copied_chat_counter_list, "receiver_email", myself_email, 0, len(copied_chat... | Your return The code retrieves and processes chat data for a specific room. It fetches accounts, chat counters, and chats, sorts them, filters chats by the room slug, determines sender/receiver details, and renders the chat interface with the data. | def get(self, request, room_slug):
accounts = Account.objects.values()
account_list = list(map(lambda i: i, accounts))
myself_email = request.session.get("email", None)
quick_sort(account_list, "id", 0, len(account_list) - 1)
chat_counters = ChatCounter.objects.values()
... |
def load_deps():
"""
Read the dependencies from `.[core]`.
"""
return list(map(upgrade_core, metadata().get_all('Requires-Dist')))
def clean(vendor):
"""
Remove all files out of the vendor directory except the meta
data (as pip uninstall doesn't support -t).
"""
ignored = ['ruff.toml... | The function `update_setuptools` manages dependencies for the `setuptools` package by loading required dependencies, cleaning the `_vendor` directory, and installing the dependencies into it. This ensures the correct versions of dependencies are maintained for `setuptools` operations. | def update_setuptools():
vendor = Path('setuptools/_vendor')
deps = load_deps()
clean(vendor)
install_deps(deps, vendor) |
def get_cmake():
"""Find CMake using registry."""
import winreg
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Kitware\CMake") as key:
root = pathlib.Path(winreg.QueryValueEx(key, "InstallDir")[0])
return root / 'bin\\CMake.exe'
def get_msbuild():
"""Use VSWhere to find MSBuild."... | The main task of the code is to build executables for multiple platform-target combinations using CMake and MSBuild. It creates temporary directories for each build, executes the build process, and then copies Win32-specific executables to default names in the output directory, ensuring standardized executable naming a... | def main():
# check for executables early
get_cmake()
get_msbuild()
for platform, target in itertools.product(BUILD_PLATFORMS, BUILD_TARGETS):
with tempfile.TemporaryDirectory(dir=REPO_ROOT) as arena:
do_build(arena, platform, target)
# copy win32 as default executables
for... |
def pick_a_host():
if os.environ.has_key("RCC_RSH_HOSTS"):
hosts = os.environ["RCC_RSH_HOSTS"].split()
elif os.environ.has_key("RCC_SSH_HOSTS"):
hosts = os.environ["RCC_SSH_HOSTS"].split()
else:
raise Exception("No remote hosts available!")
# TODO: this is the simplest thing whic... | The function `run_remotely` executes code compilation tasks on a remote server. It checks if the host is "localhost" and runs locally if true. Otherwise, it constructs and executes commands to compile code remotely via SSH, transfers input files using SCP, compiles on the remote host, and retrieves output files back. T... | def run_remotely(argv, rsh="ssh", rcp="scp"):
host = pick_a_host()
if host == "localhost":
run_locally(argv)
return
cmd = make_E_cmd(argv)
sys.stderr.write("rcc[-E]: %s\n" % cmd)
assert 0 == os.system(cmd)
cmd = make_rcp_i_cmd(argv, host, rsh=rsh, rcp=rcp)
sys.stderr.wr... |
def fields_check(location, cuisine, people, date, time, phone):
if location and location_check(location):
return location_check(location)
if cuisine and cuisine_check(cuisine):
return cuisine_check(cuisine)
if people and people_check(people):
return people_check(people)
if da... | The function processes a recommendation intent by extracting user inputs (location, cuisine, date, time, etc.), validating fields, and either eliciting corrections for invalid inputs or delegating/finalizing the request. It handles dialog validation and fulfills the intent by sending data to SQS, returning a confirmati... | def recommendation_intent(intent_request):
location = intent_request['currentIntent']['slots']["city"]
cuisine = intent_request['currentIntent']['slots']["dish"]
date = intent_request['currentIntent']['slots']["date"]
time = intent_request['currentIntent']['slots']["time"]
people = intent_request['c... |
def setup(conn, addr):
msg = server_recive(conn, addr)
if msg == "[ROLL THE DICE!]":
g = generate_prime(100)
p = generate_prime(50)
server_send(conn, addr, str(g))
server_send(conn, addr, str(p))
print("[PARAMETERS SETUP]")
return g, p
def server_recive(conn, addr... | This code handles a client connection in a cryptographic protocol. It receives a commitment value, calculates a roll, verifies it against client-provided values, and either accepts/rejects the commitment. If accepted, it sends the result; otherwise, rejects. The process involves cryptographic checks using group element... | def handle_client(conn, addr):
print(f"[CLIENT CONNECTED]: {addr}")
g, p = setup(conn, addr)
c = int(server_recive(conn, addr))
print("[RECIVED COMMIT]")
#print(f"[ALICE COMMIT] = {c}")
roll = CalcRoll(g, p, conn, addr)
if roll != 0:
r = int(server_recive(conn, addr))
a ... |
def _get_role(self, role_name: str) -> Dict[str, str]:
with self.console.status("[bold]Fetching role..."):
role = self.iam.get_role(RoleName=role_name)
role = self._filter_role_attributes(role["Role"])
self._console_print("[bold green]Role fetched.")
return role
def _get_... | The code initializes an IAM role management system by fetching an AWS IAM role and its associated policies, then constructs a role object with those policies for further processing or analysis. It sets up logging verbosity, establishes an IAM client, and prepares role data for operations like policy evaluation or displ... | def __init__(self, role_name: str, verbose: bool = False) -> None:
self.console = Console()
self.verbose = verbose
self.iam = boto3.client("iam")
self.role_name = role_name
self.role = self._get_role(self.role_name)
self.policies = self._get_role_policies(self.role_name)
... |
def is_float_list(lst):
if not isinstance(lst, list) or len(lst) == 0:
raise TypeError("The vector values are not a list type")
for item in lst:
if not isinstance(item, int) and not isinstance(item, float):
return False
return True
def is_list_list(lst):
if not isinstance(lst... | The code initializes a Vector object by validating and processing input values. It handles lists (flat or 2D rectangular), integers (size), or ranges to construct a structured vector with appropriate shape and values, raising errors for invalid inputs. | def __init__(self, values):
self.values = []
if isinstance(values, list):
if is_float_list(values):
self.shape = (1, len(values))
self.values.append(values.copy())
elif is_list_list(values) and is_rectangular(values):
self.shape = (... |
def remove_from_pop(how_many_to_kill, population, our_map):
ranked_pop = sort_population(population, our_map)
survival_of_the_fittest = ranked_pop[: (len(population) - how_many_to_kill)]
return np.array(survival_of_the_fittest)
def crossover(a, b):
c = []
for i in range(1, N - 2):
if (a[i]... | The function `breeding` generates a new population for evolutionary algorithms by selecting the fittest individuals, performing crossover on pairs to create offspring, applying mutation, and adding new random routes to maintain population size. It ensures survival of top performers, introduces genetic diversity through... | def breeding(population, our_map):
fittest = remove_from_pop(how_many_to_kill, population, our_map)
children = []
keep = 4
for i in range(0, 4):
children.append(population[fittest[i]])
for i in range(4, len(fittest) - 1, 2):
child_1 = crossover(population[fittest[i]], population[f... |
def create_generation(pop_size, our_map):
population = []
for i in range(0, pop_size):
population.append(create_new_route())
return population
def best_in_population(population, our_map):
best = sort_population(population, our_map)[0]
best_route = population[best]
return best_route
de... | The code implements a genetic algorithm to optimize route-finding on a map. It initializes locations, generates an adjacency matrix, creates a population, and iteratively evolves routes over generations. The best routes and their fitness are tracked, visualized, and plotted to show improvement over time. | def main():
#our_map = initialise_map(lower_limit)
names_of_locations_temp = ["kelseys", "the fat pug", "the town house", "the old library", "the clarendon",
"the benjamin satchwell", "murphy's bar", "The Royal Pug", "the white house",
"The Drawing B... |
def _save_dirfmt(self, var, fmt):
"""Save the directory format to the site's data_dir,
returns a new directory format mounted on the saved location.
"""
data_dir = self.sphinx_env.app.q2_usage['data_dir']
dir_name = self._to_cli_name(var)
save_path = os.path.join(data_dir... | The main task of the code is to generate reStructuredText (RST) instructions for uploading data formats to a Galaxy platform. It processes `DirectoryFormat` objects by collecting files, creating history identifiers, and structuring step-by-step upload guidance. For non-directory formats, it triggers a download. The cod... | def init_format(self, name, factory, ext=None):
if ext is not None:
name = '%s.%s' % (name, ext)
var = super().init_format(name, factory, ext=ext)
data_dir = self.sphinx_env.app.q2_usage['data_dir']
fmt = var.execute()
if isinstance(fmt, model.DirectoryFormat):
... |
def _save_results(self):
fns = {}
data_dir = self.sphinx_env.app.q2_usage['data_dir']
for fn, result in self.recorder.items():
fp = str(data_dir / fn)
if isinstance(result, model.DirectoryFormat):
with tempfile.TemporaryDirectory() as tmpdir:
... | The main task of the code is to generate a structured container node containing saved results, standard output, standard error, and miscellaneous elements. It constructs a compound node with file data, appends stdout/stderr content if provided, and optionally resets output buffers when flush=True. The function returns ... | def render(self, node_id, flush=False, stdout=None, stderr=None, **kwargs):
fns = self._save_results()
files_node = self._construct_file_node(fns)
container_node = nodes.compound('', files_node, ids=[node_id],
classes=['exec-usage'])
if stdout:
... |
def menu(self):
print('Write action (buy, fill ,take, remaining, exit):')
action = input()
return action
def show_machine(self):
print(f'''\nThe coffee machine has:
{self.machine_water} of water
{self.machine_milk} of milk
{self.machine_beans} of coffee beans
{self.machin... | This code implements a menu-driven interface for managing a coffee machine. It allows users to check machine status, purchase drinks, restock supplies, withdraw cash, or exit. The loop processes user choices, executes corresponding actions like making drinks or updating machine resources, and maintains the machine's st... | def start(self):
while True:
choice = self.menu()
if choice == 'exit':
break
elif choice == 'remaining':
self.show_machine()
elif choice == 'buy':
choice_buy = self.menu_buy()
if choice_buy == 'back':... |
def _new_account(self):
account = Account()
cur = self.conn.cursor()
cur.execute("""
INSERT INTO card (id, number, pin, balance)
VALUES (?, ?, ?, ?)
""", (account.account_number, account.card_number, account.pin, account.balance))
self.conn.commit()
... | This code implements a menu-driven banking application allowing users to create accounts, log in, and manage transactions. It features nested loops for main menu and logged-in operations, including balance checks, income additions, transfers, account closure, and logout. Database interactions handle account data, ensur... | def menu(self):
end_menu = 0
while not end_menu:
print(f'''\n1. Create an account
2. Log into account
0. Exit
''')
choice = int(input())
if choice == 0:
end_menu = 1
elif choice == 1:
self._new_account()
elif cho... |
def mouse_coordinates_boundary(image1, image2):
resulting_coordinates = []
# Copy image
images = [image1.copy(), image2.copy()]
for image in images:
cv2.namedWindow('Image Window')
# Mouse click handler
def mouse_callback(event, x, y, flags, param):
if event == cv... | The code blends two images using a Laplacian pyramid approach. It creates pyramids for both images, merges corresponding layers by horizontally combining halves, then reconstructs the final blended image through upsampling and layer addition, resulting in a seamless composite of the input images. | def blend_images(left, right, n):
# Assume boundaries
boundaries = mouse_coordinates_boundary(left, right)
resized_left, resized_right = resize_and_pad(left, right, boundaries)
laplacianPyramid_left = laplacianPyramid(resized_left, n)
laplacianPyramid_right = laplacianPyramid(resized_right, n)
... |
def laplacianPyramid(I_input, n):
# Construct Gaussian pyramid
gaussian_pyramid = gaussianPyramid(I_input, n)
# Construct Laplacian pyramid
laplacian_pyramid = []
# Bottom to top construction
for i in range(n - 1):
level_up = expand(gaussian_pyramid[i + 1])
difference = cv2.sub... | The main task of the code is to blend two images using a Laplacian pyramid technique based on a user-specified seam position determined by a mouse click. The code captures the click coordinates, resizes and aligns the images, generates a bitmask for blending, constructs Laplacian and Gaussian pyramids, combines image l... | def mouse_handler_onClick(event, x, y, flags, params):
if event == cv2.EVENT_LBUTTONDOWN:
print(f"PRINTING x: {x}")
print(f"PRINTING x, y {(x,y)}")
#x_resize = x
#cv2.destroyAllWindows()
# Image width - coordinate of mouse click
overlap_reg... |
def sidebar_toggle(self):
new_state = False if self.sidebarDockWidget.isVisible() else True
self.sidebarDockWidget.setVisible(new_state)
def onBury(self): # self is browser
if anki_21_version < 45:
self.editor.saveNow(lambda b=self: _onBury__pre_45(b))
elif anki_21_version < 58:
_onBury... | The code creates and configures a QToolBar ("Fastbar") with icons, text, and actions for a browser interface. It connects toolbar buttons to functions, adjusts action names for compatibility, applies night mode styling, and adds the toolbar to the window. Actions include toggling features, managing notes, and add-ons, ... | def make_and_add_toolbar(self): # self is browser
fbar = QToolBar("Fastbar")
fbar.setObjectName("Fastbar")
fbar.setIconSize(QSize(15, 15))
fbar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextUnderIcon)
self.form.actionToggle_Sidebar.triggered.connect(lambda _, b=self: sidebar_toggle(b))
s... |
def split_sentences(self):
"""
ROUGE requires texts split into sentences. In case the texts
are not already split, this method can be used.
"""
from pyrouge.utils.sentence_splitter import PunktSentenceSplitter
self.log.info("Splitting sentences.")
ss = PunktSente... | The main task of the code is to convert plain text summaries into ROUGE format, optionally split them into sentences, and evaluate system summaries against model summaries using ROUGE metrics. It combines conversion and evaluation steps, returning ROUGE output as a string. | def convert_and_evaluate(self, system_id=1,
split_sentences=False, rouge_args=None):
"""
Convert plain text summaries to ROUGE format and run ROUGE to
evaluate the system summaries in system_dir against the model
summaries in model_dir. Optionally split texts... |
def get_profile_form(self):
form_kwargs = {}
if self.request.method == "POST":
form_kwargs["data"] = self.request.POST
form_kwargs["files"] = self.request.FILES
return ProfileRegistrationForm(**form_kwargs)
def form_valid(self, user_form, profile_form):
result = s... | This code handles form submission by validating both user and profile forms. If valid, it processes them via `form_valid`; otherwise, it returns invalid responses using `form_invalid`.) | def post(self, request, *args, **kwargs):
user_form = self.get_form()
profile_form = self.get_profile_form()
if user_form.is_valid() and profile_form.is_valid():
return self.form_valid(user_form, profile_form)
else:
return self.form_invalid(user_form, profile_form... |
def get_profile_form(self):
form_kwargs = {"instance": self.object.profile}
if self.request.method == "POST":
form_kwargs["data"] = self.request.POST
form_kwargs["files"] = self.request.FILES
return ProfileChangeForm(**form_kwargs)
def form_valid(self, user_form, profile_... | This code handles a POST request by validating two forms (user and profile) associated with a specific object. If both forms are valid, it proceeds to the `form_valid` method; otherwise, it triggers `form_invalid`, ensuring data integrity before updating the object. | def post(self, request, *args, **kwargs):
self.object = self.get_object()
user_form = self.get_form()
profile_form = self.get_profile_form()
if user_form.is_valid() and profile_form.is_valid():
return self.form_valid(user_form, profile_form)
else:
return s... |
def __log_msg(self, message):
"""
Log a message for multiprocessing: append process name
"""
return ': '.join([f"[{self.__process_name}]", message])
def _make_gav_substitute(self, component, version, artifact):
"""
Return a dictionary for GAV substitutes
:param st... | The code processes an artifact by generating a target GAV (Group:Artifact:Version) from a template, checking if it already exists in a Maven repository, and copying/registering it if absent. It logs details, substitutes variables, sanitizes the GAV, skips duplicates unless forced, and uses CI type mappings for registra... | def process_artifact(self, artifact, component, version):
"""
Process artifacts
:param dict artifact: artifact properties from Dms
:param str version: component version
:param str component: DmsComponentID
:param dict params: configuration params
"""
loggi... |
def _make_dms_api_call_with_retries(self, method, *args, **kwargs):
"""
Make DMS API call with set amount of retries on error
:param method: method reference
:return: result of the method call
"""
_attempt = 0
while True:
_attempt += 1
if h... | The main task of the code is to retrieve and process artifacts for a specified component version by making a DMS API call, logging the number of retrieved artifacts, and iterating through each artifact to pass it to the `process_artifact` method for further handling. | def process_version(self, version, component):
"""
Process versions of component
:param str version: component version
:param str component: DmsComponentID
"""
artifacts = self._make_dms_api_call_with_retries(self.dms_client.get_artifacts, component, version) or list()
... |
def __log_msg(self, message):
"""
Log a message for multiprocessing: append process name
"""
return ': '.join([f"[{self.__process_name}]", message])
def _make_dms_api_call_with_retries(self, method, *args, **kwargs):
"""
Make DMS API call with set amount of retries on err... | The main task of the code is to process a DMS component in a separate process by checking its enabled status, logging deprecated parameters, retrieving its versions via API, and processing each version. It handles exceptions by logging errors and returning messages, ensuring non-blocking execution. If disabled, it skip... | def process_component(self, component):
"""
Process component
To be called in separate process
:param str component: DMS component ID
:return: 'None' on success, raised exception on failure
"""
self.__process_name = component
if not self._components[compo... |
def get_rob_id_by_type(self, rob_list, theta):
ll = []
for rob in rob_list:
if rob.theta == theta:
ll.append(rob.id)
return ll
def partition_user_by_type(self, rob_list, theta, prob=None):
"""
This function partitions the user for type theta robots giv... | The function computes the expected locational energy for a service provider (SP) by aggregating contributions from all robots and users. It iterates over robot types, partitions users by type, and calculates weighted sums of quality-of-service (QoS) values based on distances between user positions and robot locations. ... | def compute_expected_L(self, rob_list, prob=None):
"""compute SP's expected locational energy."""
if prob is None:
prob = self.user_prob
f = 0
# get robot types
for theta in range(self.K):
rob_idx = self.get_rob_id_by_type(rob_list, theta)
user... |
def predict_coordinates_of_cities(img, th=0.53):
original_img=cv.imread('train/all.jpg')
original_img_grayscale=cv.cvtColor(original_img, cv.COLOR_BGR2GRAY)
template=original_img_grayscale [1191:1245, 3477:3531]
img_grayscale=cv.cvtColor(img, cv.COLOR_BGR2GRAY)
correlation=cv.matchTemplate(img_gray... | The code's main task is to analyze an input image and return three predictions: coordinates of city centers, the number of trains, and scores associated with specific points in the image. It combines results from three sub-functions to provide a comprehensive analysis of the image content. | def predict_image(img):
city_centers = predict_coordinates_of_cities(img)
n_trains = predict_ntrains(img)
scores = predict_points(img)
return city_centers, n_trains, scores |
def __populateFS(self):
self.__fileSystem.createTree()
def __initialize(self):
stopwatch = time.time() # starts the stopwatch
# sync done when initial load occurs
# next goal is to download what is on google drive but not your computer
self.__googleDrive.createTree() # creates google drive
gFiles = self.__g... | The code's main task is to initialize and configure a system by populating the file system (`__populateFS`), performing initial setup (`__initialize`), and executing routine checks (`__routineCheck`) to ensure proper functionality. This method orchestrates pre-launch preparations, including data structure setup, resour... | def launch(self):
self.__populateFS()
self.__initialize()
self.__routineCheck() |
def GenerateTextXmlAndAttach(self, name, value, parentElement: Element):
element = SubElement(parentElement, name)
if value is not str:
value = str(value)
element.text = value
def GenerateXmlForSize(self):
sizeXML = Element("size")
depth = len(self.Image.getbands())
... | The main task of the code is to generate an XML structure for image annotations. It creates an "annotation" element, populates metadata like folder, filename, path, source database, image size, segmentation status, and iterates through labels to add corresponding XML elements. The result is a hierarchical XML tree repr... | def GenXml(self) -> Element:
if self.Image is None:
raise ValueError("Data writer Image value set to None")
top = Element("annotation")
path = self.Image.filename
# strips the file name off of the path returns the first folder
folder = os.path.basename(os.path.dirnam... |
def generate_nodes(self, env, n=3, areaX=10, areaY=10):
for i in range(n):
isLBR = False
name = 'Node{}'.format(i + 1)
position = (random.uniform(0, areaX), random.uniform(0, areaY)) # Random position between (0, 0) and (10, 10)
sigRange = 2
if i == 0... | The code simulates and visualizes a network by generating nodes and connections, then continuously updates the plot with a specified interval while maintaining a 1-second simulation time step. | def run(self):
self.generate_nodes(self.env, NUM_NODES, AREA_X, AREA_Y)
self.generate_connections()
while True:
self.plot_network() # Update the plot
plt.pause(self.plot_interval) # Pause for plot_interval seconds
yield self.env.timeout(1) |
def get_playable_cards(self, player=None):
"""
function to see what cards a player can play
:param player: player to check
:return: a list of cards a player can play
"""
if player is None:
player = self.current_player
playable_cards = []
card... | The code implements a reinforcement learning agent for a card game, using a Q-table to select actions (play/draw) via epsilon-greedy exploration. It updates Q-values based on reward signals, tracks hand states, and chooses optimal moves by evaluating card colors and playable actions, while maintaining game state transi... | def assess_hand(self, player=None):
if player is None:
player = self.current_player
if self.colour_to_play == "black" and self.previous_play[1] == [-1]:
if random() < self.epsilon:
colour = randint(0, 3)
else:
poss_colours = {"red": 0,... |
def _setup_argsparser(self):
self.argsparser = argparse.ArgumentParser(description='Logic runner for {0}'.format(self.__class__.__name__))
self.argsparser.add_argument('--dryrun', dest='dryrun', action='store_true')
self.argsparser.add_argument('--no-dryrun', dest='dryrun', action='store_false')... | The code initializes an object by configuring command-line arguments, retrieving the system hostname, loading data, setting up a template structure, and initializing metadata. It performs setup tasks essential for the object's operation, including parsing inputs, preparing data, and organizing structural components. | def __init__(self):
self._setup_argsparser()
self.hostname = socket.gethostname()
self._read_data()
self._setup_template()
self._setup_metadata() |
def printArr(self):
out = "["
for i in range(self.MAX_SIZE - 1):
out += "'" + str(self.arr[i]) + "', "
out += "'" + str(self.arr[self.MAX_SIZE - 1]) + "']"
print(out)
def getPointerString(self):
return "-" * self.getPointerPositionInString() + ("^" if not self.is_Emp... | The code's main task is to print the array's elements either horizontally (when `printVertical` is False) or vertically (when True), along with the stack pointer's position and value. It formats elements with quotes, aligns them by length, and marks the current pointer position. Vertical output centers elements, adds s... | def print(self):
if not self.printVertical:
self.printArr()
print(self.getPointerString())
print("value of the pointer: " + str(self.stackPointer))
else:
values = []
maxLen = 0
for i in range(self.MAX_SIZE):
value = ... |
def get_accelerations(self, coords) -> np.ndarray:
"""
Get accelerations from a set of coordinates. The pairwaise distance
vectors and distances (vector norm) will be determined first. The
atom pairs that are within distance cutoff will be selected, and the
Lennard Jones poten... | The method initializes the first time step in a simulation by calculating accelerations and pair potentials using Taylor series expansion. It updates coordinates with initial velocity and acceleration terms, applies periodic boundary conditions, and stores initial coordinates for reference. | def _init_step(self) -> None:
"""The first two steps calculated using the taylor series expansion
for t=0 and t+∆t"""
self.accl = self.get_accelerations(self.init_coords)
self.pair_potentials = self._compute_pair_potentials()
self.coords = self.init_coords+self.velo*self.dt+self.... |
def get_accelerations(self, coords) -> np.ndarray:
"""
Get accelerations from a set of coordinates. The pairwaise distance
vectors and distances (vector norm) will be determined first. The
atom pairs that are within distance cutoff will be selected, and the
Lennard Jones poten... | This function advances a molecular dynamics simulation by one time step using the Verlet algorithm. It calculates accelerations, computes pair potentials, updates coordinates with Verlet integration, applies periodic boundary conditions (PBC) to positions and displacements, computes new velocities from coordinate diffe... | def step(self) -> None:
"""
Advance the simulation for one time step ∆t. New velocities,
accelerations, coordinates, and last coordinates will be updated."""
self.accl = self.get_accelerations(self.coords)
self.pair_potentials = self._compute_pair_potentials()
new_coords... |
def _apply_pbc_coord(coords, box_len) -> None:
"""Apply periodic boundary conditions on coordinates. Any out of bound
coord will be wrapped and place to the other side of the box. The new
coords will be assigned to the self.coords array directly"""
mask1 = coords > box_len
mask... | The function performs a Velocity Verlet integration step in molecular dynamics simulations. It updates particle coordinates using current velocities and accelerations, applies periodic boundary conditions, recalculates accelerations based on new coordinates, computes pair potentials, and updates velocities with the new... | def step_velocity_verlet(self) -> None:
self.coords = self.coords+self.velo*self.dt+self.accl*self.dt**2/2
self._apply_pbc_coord(self.coords, self.box_len)
self.velo = self.velo+self.accl*self.dt/2
self.accl = self.get_accelerations(self.coords)
self.pair_potentials = self._compu... |
def _init_coords(self, box_len, n_cells) -> np.ndarray:
"""
Initialize coordinates in face centered cubic unit cells
"""
cell_len = box_len/n_cells
x_corner = np.linspace(0, box_len-cell_len, n_cells) # corner atom spacings
x_face = np.linspace(cell_len/2, box_len-cell_le... | This code initializes a molecular dynamics simulation for Argon atoms arranged in a face-centered cubic (FCC) lattice. It calculates system dimensions, atom coordinates, and initial velocities based on input parameters like temperature, number of unit cells, and density. The Lennard-Jones potential parameters and force... | def __init__(
self,
n_cells : int,
temp : float = 120,
dt : float = 1e-14, # seconds
density : float = 1.16, # g/cm^3 @ 130K
lennard_jones_cutoff : float = 2.5 # 2.5 sigma is set as lennard jones potential cutoff
):
"""
Initialize the system by specify... |
def extractMeshSizes(data):
# the mesh sizes should be in the first col of the data
return np.unique(data[:, 0])
def extractRomSizes(data):
# the rom sizes should be in the second col of the data
return np.unique(data[:, 1])
def computeTimingsStat(data, label, statType):
nRows, nCols = data.shape[0], data.sha... | The main task of the code is to compare timing data between C++ and Python implementations by loading, processing, and validating data from two files. It converts timing units, verifies mesh/ROM sizes match, computes statistical averages, and generates either regular or stacked bar plots to visualize performance differ... | def main(cppFile, pyFile, romName, barType, statType):
# check that files exists
if not os.path.isfile(cppFile):
raise Exception('The file {} does not exist. '.format(cppFile))
if not os.path.isfile(pyFile):
raise Exception('The file {} does not exist. '.format(pyFile))
# load data
cppData, pyData = ... |
def read_vasprun(directory):
directory = os.path.abspath(directory)
cwd = os.getcwd()
os.chdir(directory)
replace_vasprun(directory)
vasprun = Vasprun('./vasprun.xml')
os.chdir(cwd)
return vasprun
def copy_vacuum_files(directory, copy_to_dir, restart=False):
vac_dir = directory + '/VAC'... | This function initializes a GDC (Grand Canonical Dynamics) simulation directory by creating a solvent-specific folder structure, copying vacuum or initial files based on convergence status, and invoking `add_gdc2` to set up solvent parameters. It processes input parameters, ensures directory paths, checks for existing ... | def initialize_gdc(directory, dz=5, epsilon=78.4, Ionic_strength=1, NSW=100, restart = False, dict_of_additional_tags = {}):
directory = os.path.abspath(directory)
if directory[-1] == '/':
directory = directory[0:-1]
cwd = os.getcwd()
vac_dir = directory + '/VAC'
vac_dir = os.path.abspath(va... |
def check_convergence(directory):
directory = os.path.abspath(directory)
if directory[-1] == '/':
directory = directory[0:-1]
try:
vasprun = read_vasprun(directory)
if vasprun.converged == True:
return True
else:
return False
except:
return... | The function initializes a 'VAC' directory for vacuum calculations by creating or updating it with necessary files, checking convergence, copying CONTCAR to POSCAR, removing Vaspsol tags, and applying user-defined INCAR tags. It ensures proper setup for subsequent computations while managing directory structure and inp... | def initialize_vacuum(directory, dict_of_additional_tags={}):
cwd = os.getcwd()
directory = os.path.abspath(directory)
if directory[-1] == '/':
directory = directory[0:-1]
vac_dir = directory + '/VAC'
if os.path.exists(vac_dir):
convergence = check_convergence(vac_dir)
if con... |
def initialize_solvent2(directory, solvent='water', epsilon=78.4, calc_type='linear', Ionic_strength=0, NSW=100, restart = False, dict_of_additional_tags = {}):
directory = os.path.abspath(directory)
if solvent != 'water':
try:
props = solvent_properties(solvent)
epsilon = props[... | The function initializes solvent parameters for a computational simulation by setting up directories, modifying input files, and configuring solvent-related settings. It converts paths to absolute, initializes solvent data, removes specific tags, copies structural files, and adds solvent details. The process prepares a... | def vacuum_init_solvent(directory,
solv_dir,
solvent='water',
epsilon=78.4,
Ionic_strength = 1,
calc_type='linear',
NSW=100,
dict_of_additional_ta... |
def initialize_gdc(directory, dz=5, epsilon=78.4, Ionic_strength=1, NSW=100, restart = False, dict_of_additional_tags = {}):
directory = os.path.abspath(directory)
if directory[-1] == '/':
directory = directory[0:-1]
cwd = os.getcwd()
vac_dir = directory + '/VAC'
vac_dir = os.path.abspath(va... | The function `calculate_gdc` executes a VASP-based computational task involving solvent modeling. It generates a directory structure based on input parameters (e.g., solvent properties, ionic strength), prepares input files, runs simulations, and processes results. Key steps include initializing the calculation, modify... | def calculate_gdc(directory, dz=5, epsilon=78.4, Ionic_strength=1, restart=False, NSW=100, dict_of_additional_tags={}):
cwd = os.getcwd()
directory = os.path.abspath(directory)
solvent = 'dz_' + str(dz) + '_epsilson_' + str(epsilon) + '_Ionic_' + str(Ionic_strength)
tags = list(dict_of_additional_tags.k... |
def initialize_vacuum(directory, dict_of_additional_tags={}):
cwd = os.getcwd()
directory = os.path.abspath(directory)
if directory[-1] == '/':
directory = directory[0:-1]
vac_dir = directory + '/VAC'
if os.path.exists(vac_dir):
convergence = check_convergence(vac_dir)
if con... | The function `calculate_vacuum` performs a vacuum calculation using VASP by setting up a directory structure, handling restarts by removing old files, initializing the calculation with additional tags, executing the VASP run, and returning the parsed `vasprun.xml` results or 'Failed' on errors. | def calculate_vacuum(directory, restart=False, NSW=100, dict_of_additional_tags={}):
cwd = os.getcwd()
directory = os.path.abspath(directory)
try:
if directory[-1] == '/':
directory = directory[0:-1]
vac_dir = directory + '/VAC'
if restart == True:
try:
... |
def solvent_properties(solvent_name):
properties = {}
df = solvent_dataframe()
for col in df.columns[1::]:
properties[col] = df[df['Solvent'] == solvent_name][col].to_numpy()[0]
return properties
def add_solvent(directory, solvent='water', epsilon = 78.4, Ionic_strength = 0, calc_type='linear', ... | The code sets up and executes a VASP solvation calculation, configuring solvent properties, directory structure, and computational parameters. It checks for existing results or restarts, initializes the system, runs the simulation (linear/non-linear), and returns the parsed VASP output. | def calculate_solvent(directory, solvent='water', calc_type='linear', epsilon=78.4, Ionic_strength=0, restart=False, NSW=100, dict_of_additional_tags={}):
cwd = os.getcwd()
directory = os.path.abspath(directory)
if solvent != 'water':
try:
props = solvent_properties(solvent)
... |
def multiple_photo_folders():
#define layout for folder creation Window
layout = [[sg.Text("How many folders need to be created?"),
sg.Input("", k="-IN-")],
[sg.Button("OK")]]
window = sg.Window(" ", layout)
while True:
event, values = window.read()
if event ==... | The code creates a GUI to prompt users for options related to photo renaming and folder handling. Based on checkbox selections, it directs execution to specific functions: `multiple_photo_folders()`, `photo_renamer()`, or `multiple_photo_folders_mover()`. It enforces single-choice logic for each question and displays e... | def main():
#defines layout for first window of module
layout = [[sg.Text("Would you like to rename photos?"),
sg.Checkbox("Yes", key="-YES-"), sg.Checkbox("No", k="-NO-")],
[sg.Text("Are multiple folders needed for renaming?"),
sg.Checkbox("Yes", k="-YES_1-"), sg.Checkbox... |
def create_parser(prog_name):
parent_parser = create_parent_parser(prog_name)
parser = argparse.ArgumentParser(
parents=[parent_parser],
description="Provides subcommands to manage weather application",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
subparsers = parser... | The main task of the code is to parse command-line arguments, configure logging, and execute corresponding command handlers (set/show/list) based on user input. It initializes a parser, processes arguments, checks for valid commands, and invokes the appropriate function, exiting with an error for invalid commands. | def main(prog_name=os.path.basename(sys.argv[0]), args=None):
if args is None:
args = sys.argv[1:]
parser = create_parser(prog_name)
args = parser.parse_args(args)
verbose_level = 0
setup_loggers(verbose_level=verbose_level)
if not args.command:
parser.print_help()
sys.... |
def count_rate_uncertainty(counts, bkg_counts, real_time, bkg_rt, roi):
"""
Calculate uncertainty in count rate
:param counts: count array
:param bkg_counts: background count array
:param real_time: observation time of detector
:param bkg_rt: background time
:param roi: region of interest
... | The function `calculate_and_plot_model` processes spectral data by subtracting background counts, calculating count rates and uncertainties, and fitting a specified model (e.g., Gaussian or custom) to the data. It generates plots of the full spectrum and a zoomed-in region, overlays the fitted model, and optionally dec... | def calculate_and_plot_model(source, detector, spectrum, background, roi, zoomed_params, model, slice_index,
added_function_params, **kwargs):
"""
Put everthing together - run model API and plot model
:param source: name of the source
:param detector: name of the detector
... |
def read_all_angle_files(spectrum_file_path, config_file_path, bkg_file, detector, sources, file_list, **kwargs):
"""
Read every file for every source for the detector and create a dictionary of date, time and peak areas +
uncertainties
:param spectrum_file_path: path to source folders
:param confi... | The main task of the code is to calculate absolute efficiencies and their uncertainties for each source and angle by combining measured peak areas with time-dependent activity values. The function processes detector-specific data, applies decay corrections, and computes efficiency using peak-area-to-activity ratios, pr... | def calculate_abs_eff(spectrum_file_path, config_file_path, bkg_file, detector, sources, file_list):
"""
Create a dictionary of absolute efficiencies for all data for the detector
:param spectrum_file_path: path to source folders
:param config_file_path: config file path
:param bkg_file: background ... |
def calculate_abs_eff(spectrum_file_path, config_file_path, bkg_file, detector, sources, file_list):
"""
Create a dictionary of absolute efficiencies for all data for the detector
:param spectrum_file_path: path to source folders
:param config_file_path: config file path
:param bkg_file: background ... | The function plots absolute efficiency vs. energy for a detector, fits a model to the data, and adjusts energy ranges by excluding the first Americium peak (due to high uncertainty or low efficiency) for specific detectors (NaI, BGO, HPGe). It compiles efficiency values and uncertainties from multiple sources, generate... | def abs_efficiency_plot(spectrum_file_path, config_file_path, bkg_file, detector, sources, file_list, energies,
e_range):
"""
Plot absolute efficiency vs energy and fit model
:param spectrum_file_path: path to source folders
:param config_file_path: config file path
:param bk... |
def calculate_int_eff(spectrum_file_path, config_file_path, bkg_file, detector, sources, file_list):
"""
Create a dictionary of intrinsic efficiencies for all data for the detector
:param spectrum_file_path: path to source folders
:param config_file_path: config file path
:param bkg_file: background... | The function plots intrinsic efficiency vs. energy for a detector, fits a logarithmic model to the data, and adjusts the dataset by excluding the first Americium peak (due to high uncertainty) for specific detectors. It uses log scales for both axes, displays measured efficiencies with error bars, and overlays the fitt... | def int_efficiency_plot(spectrum_file_path, config_file_path, bkg_file, detector, sources, file_list, energies,
e_range):
"""
Plot intrinsic efficiency vs energy and fit model
:param spectrum_file_path: path to source folders
:param config_file_path: config file path
:param b... |
def get_year_week_today():
year, weeknumber, weekday = datetime.now().isocalendar()
if weekday == 7:
# todo bug with weeknumber=1
weekday = 0
weeknumber += 1
return year, weeknumber, weekday
def get_active_weeks_of_metric(metric):
events = LogEvent.query.filter(LogEvent.metric_id... | The function `view_metric` retrieves a metric by ID, checks the current week, updates active weeks for the metric, gathers data for each active week, and renders a template with the metric and weekly data for display. | def view_metric(metric_id):
metric = Metric.query.filter_by(id=metric_id).first()
year, weeknumber, weekday = get_year_week_today()
active_weeks = get_active_weeks_of_metric(metric)
if (year, weeknumber) not in active_weeks:
active_weeks.append((year, weeknumber))
weeks = []
for yea... |
def get_bit_complexity(ped_tree,mem_ids):
"""
calculate the bit complexity of a pedigree
based on a list of member ids.
"""
n = 0
f = 0
g = []
for id in mem_ids:
indv = ped_tree.indvs[id]
#check if parents are in the pedigree
if indv.p_id in mem_ids and indv.m_id ... | The function prompts the user to select a source from available options, validates inputs, and determines a target pedigree size. It then identifies a SubPedigree of the specified size by combining valid subpedigrees, ensuring complexity constraints are met. The result is a joined SubPedigree meeting the user's criteri... | def get_user_selection(ped_tree,args,source_options):
"""
Prompts user for source selection and target pedigree
size. Returns a SubPedigree of the proper size.
"""
selected_source = None
if args.source != None: #use preselected source if given in command line
selected_source = args.sou... |
def parse_args(description): #argument parsing
parser = Parser()
parser.add_argument("struct_filename", \
help="input .txt file with pedigree structure")
parser.add_argument("germ_filename", \
help="input GERMLINE .match file")
parser.add_argument("-o", "--output_filename", \
he... | The code processes pedigree data by parsing arguments, constructing a pedigree tree, integrating IBD information, and allowing user selection of a subpedigree. It then generates output files and a ped file based on the chosen subpedigree, excluding specified entries and handling user-defined parameters for file creatio... | def main():
#parse arguments
args = parse_args("pedigree args")
# construct pedigree data structure
ped_tree = PedigreeTree(args.struct_filename)
left_out = []
# construct IBDs data structures (type: list)
IBDs = IBD.get_IBDs(args.germ_filename, left_out) # toggle to leave out
# assi... |
def get_current_date():
# Get the current date in the format 'YYYY-MM-DD'
return datetime.now().strftime('%Y-%m-%d')
def get_steam_username(api_key, user_id):
base_url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/"
url = f"{base_url}?key={api_key}&steamids={user_id}"
try:
... | The code processes user statistics from DynamoDB to determine weekly "spooky awards" for Steam users, comparing current stats with those from the previous week. It identifies winners, runners-up, and third-place users for specific stats, handles ties, updates a DynamoDB award table, and sends results via a Discord bot.... | def handler(event, context):
# Initialize DynamoDB client
dynamodb = boto3.resource('dynamodb')
user_table_name = os.environ['USER_CACHE_TABLE']
stat_table_name = os.environ['USER_STAT_TABLE']
user_table = dynamodb.Table(user_table_name)
stat_table = dynamodb.Table(stat_table_name)
api_key =... |
def reset_history(self):
self.state_action_history = {}
def act(self, state, actions, epsilon=0):
"""
returns an action index either randomly or using the model to pick an action with highest Q-value
:param state: state text
:param actions: actions to be considered
:param... | The code plays games using simulators for a specified number of episodes, collecting rewards and optionally storing experiences for training. It processes each simulator, selects actions via an epsilon-greedy strategy, handles errors, and returns average rewards per simulator. | def play_game(self, simulators, episodes=1, store_experience=True, initialize_only=False, epsilon=1):
"""
Uses the model to play the game. Each simulator is used to play the game exactly episodes times.
:param simulators: a list of games (their simulators) to play the game with (more simulators ... |
def load_benchmark(benchmark_id: str):
"""
Loads the data related to a specific benchmark.
The data returned from this function contains:
- the config which was used
- the experiment definitions
- the Jobs objects related to the benchmark
- ids for the experiment and the benchmark
- ou... | The code benchmarks machine learning algorithms by running them on multiple datasets, collecting performance metrics (e.g., absolute error), and storing results for comparison. It generates unique benchmark IDs, handles algorithm configurations, executes experiments, captures job outputs, calculates scores, and optiona... | def benchmark(
algorithm_config: Union[dict, str],
algorithm_name: str = "algorithm",
# dataset_config: Union[dict, str] = None, # TODO
# dataset_name: str = None, # TODO
# cloud: bool = False, # TODO
target_metric: str = "abs_error",
session: boto3.Session = boto3.Session(),
save_ben... |
def init_params(self,neuron_count_per_layer):
#Set a random seed for consistent results
np.random.seed(42)
num_layers = len(neuron_count_per_layer)
params = [None for i in range(2*(num_layers-1))]
for i in range(1,num_layers):
#Initialize weights of ith layer
... | This code trains a neural network with a specified architecture [9,30,30,25,1] using gradient descent. It initializes parameters, preprocesses input/output data, and iterates 15,000 times with a learning rate of 0.01. Each iteration performs forward propagation to compute activations, then backward propagation to updat... | def fit(self,X,Y):
'''
Function that trains the neural network by taking x_train and y_train samples as input
'''
#Number of epochs
num_itertations = 15000
#Learning rate
alpha = 0.01
#Network architecture
neuron_count_per_layer = [9,30,3... |
def init_params(self,neuron_count_per_layer):
#Set a random seed for consistent results
np.random.seed(42)
num_layers = len(neuron_count_per_layer)
params = [None for i in range(2*(num_layers-1))]
for i in range(1,num_layers):
#Initialize weights of ith layer
... | The code trains a neural network using Adam optimization to minimize a cost function over 750 epochs. It initializes network parameters, processes input data, and iteratively performs forward and backward propagation to update weights. Training stops early if the cost drops below 3, preventing numerical underflow. The ... | def fit(self,X,Y):
'''
Function that trains the neural network by taking x_train and y_train samples as input
'''
#Number of epochs
num_itertations = 750
#Learning rate
alpha = 0.02
#Network architecture
neuron_count_per_layer = [9,30,30,... |
def get_node(self,key,*args):
"""
T.get_node(key,...) -> Node. Produces the Node in T with key
attribute key. If there is no such node, produces None.
"""
if len(args) == 0:
start = self.Root
else:
start = args[0]
if not start:
... | This code deletes a node with the specified key from a tree. It identifies the node, then handles three cases: if it's a leaf (no children), it calls _delete_leaf; if it has one child, _delete_leaf_parent is used; if it has two children, _delete_node is invoked. The method ensures proper removal while maintaining tree ... | def delete(self,key):
"""T.delete(key) <==> del T[key]. Deletes the node
with key attribute key from T.
"""
node = self.get_node(key,self.Root)
if node:
if not (node.left or node.right):
self._delete_leaf(node)
elif not (node.left and nod... |
def get_main_activity(filename):
manifest_path = DECOMPILED_APK + '/' + filename_cutter(filename) + MANIFEST_FILE
tree = ET.parse(manifest_path)
root = tree.getroot()
activities = []
for activity in root.iter('activity'):
activities.append(activity.attrib)
try:
activityMain = c... | This code modifies an Android application's main activity by injecting specified functionalities (e.g., permissions, methods) based on the injection_type parameter. It replaces placeholders with the app's package path, inserts injected code into the onCreate method, and adds socket client code if client_payload is 'cli... | def mainActivity_modifier(file, injection_type, client_payload):
# print(string)
activityMainPath, path = get_main_activity(file)
path_mod = path.replace(".", "/")
# print("PATH:", path)
package = get_package(file)
print(activityMainPath)
injection = query(injection_type)
# print(injecti... |
def callback(result, error):
global counter
# TODO: what can we assert?
print(result, error)
counter += 1
if counter == 9:
loop.remove_handler(dns_resolver.handle_events)
dns_resolver.close()
def is_valid_hostname(hostname):
... | This function resolves a hostname to an IP address by checking if it's an IP directly, exists in /etc/hosts, or matches cached entries. If not, it validates the hostname and initiates a DNS query (QTYPE_A) while managing callback registrations for asynchronous result handling. It ensures compatibility with Python 3 by ... | def resolve(self, hostname, callback):
if type(hostname) != bytes: # Compatible with Python 3
hostname = hostname.encode('utf8') # Convert to bytes
if not hostname: # Raise exception if hostname is empty
... |
def parse_response(data):
try:
if len(data) >= 12:
header = parse_header(data)
if not header:
return None
res_id, res_qr, res_tc, res_ra, res_rcode, res_qdcount, \
res_ancount, res_nscount, res_arcount = header
qds = []
... | This function processes DNS response data to resolve hostnames to IP addresses. It parses the response, checks for A/AAAA records, caches valid IPs, and triggers callbacks. If no IP is found, it switches to IPv6 queries based on prior status, ensuring correct query type handling and avoiding redundant requests. | def _handle_data(self, data):
response = parse_response(data) # Parse data received from socket to response
if response and response.hostname:
hostname = response.hostname
ip = None
for answer in response.answers:
if ans... |
def _sample_vanilla_occlusion(self, image_paths):
image_path_s, image_path_t = random.choices(image_paths, k=2)
image_path_o = random.choice(self.s_occlusion)
Xs = self.source_transforms(PIL.Image.open(image_path_s))
pil_t, pil_o = self._get_occluded_target_gt(image_path_t, image_path_o)... | This method randomly selects a data sampling strategy based on predefined probabilities, handling multiple data categories (e.g., vanilla, edited_target, source_as_gt, target_as_gt). It uses conditional checks to apply occlusion or attribute variations (e.g., beard, fat, bald) and calls corresponding sub-methods like _... | def __getitem__(self, item):
o = random.random()
if o < self.p_accumulated[0]: # vanilla
if random.random() < self.p_vanilla_occlusion: # with occlusion
return self._sample_vanilla_occlusion(self.data_dict["vanilla"])
else: ... |
def _compute_gradients(self, input_vector, target):
layer_1 = np.dot(input_vector, self.weights) + self.bias
layer_2 = self._sigmoid(layer_1)
prediction = layer_2
derrorpred = 2 * (prediction - target)
dpredlay1 = self._sigmoid_deriv(layer_1)
dlayer1_dbias = 1
dl... | The code trains a model using stochastic gradient descent by randomly selecting data points, computing gradients, updating parameters, and tracking cumulative errors every 100 iterations. It returns a list of these errors to monitor training progress. | def train(self, input_vectors, targets, iterations):
cumulative_errors = []
for current_iteration in range(iterations):
# Pick a data instance at random
random_data_index = np.random.randint(len(input_vectors))
input_vector = input_vectors[random_data_index]
... |
def _check_nested_floats(thelist):
"""
Returns True if thelist is a (nested) list of floats
INTERNAL HELPER
If thelist recursively contains anything other than a list, tuple, int, or float,
this function returns false.
:param message: A custom error message (OPTIONAL)
:type me... | The main task of the code is to verify if two nested lists or tuples of floats (`expected` and `received`) are numerically equivalent within a tolerance, using NumPy's `allclose` method. It first ensures both inputs are valid sequences of the same dimension and contain numeric values. If not, it raises errors with spec... | def assert_float_lists_equal(expected, received,message=None):
"""
Quits if the lists (or tuples) of floats ``expected`` and ``received`` differ
This function takes two numbers and compares them using functions from the numerical
package ``numpy``. This is a scientific computing package that allo... |
def _check_nested_floats(thelist):
"""
Returns True if thelist is a (nested) list of floats
INTERNAL HELPER
If thelist recursively contains anything other than a list, tuple, int, or float,
this function returns false.
:param message: A custom error message (OPTIONAL)
:type me... | The function `assert_float_lists_not_equal` verifies that two lists/tuples of floats (`expected` and `received`) are not approximately equal using NumPy's `allclose` method. It first checks if inputs are valid sequences of numbers, raising errors for non-numeric or non-sequence inputs. If valid, it compares the lists; ... | def assert_float_lists_not_equal(expected, received,message=None):
"""
Quits if the lists (or tuples) of floats ``expected`` and ``received`` are the same
This function takes two numbers and compares them using functions from the numerical
package ``numpy``. This is a scientific computing package... |
def integer_sorter(integers: list, unsort: bool) -> list:
"""Sort the given list of integers, or return it unsorted if the
unsort flag is set."""
integers if unsort else integers.sort()
return integers
def integer_dict(integers: list, groupFlag: bool, pf_flag: bool) -> dict:
"""Return a dict of inte... | The main task of the code is to process command-line arguments, sort integers with optional flags, generate formatted integer groups, measure display widths, and print results. It also prints prime numbers up to a given value and simplified radical forms if specified. | def main():
args = parser.parse_args()
integers, n, unsortFlag, groupFlag, pfFlag, radical = vars(args).values()
if sorted_ints := integer_sorter(integers, unsortFlag):
int_dict = integer_dict(sorted_ints, groupFlag, pfFlag)
lls, width = measure_width(sorted_ints)
print_integers(int... |
def compile(self, partten: str) -> None:
self.reader = Reader(partten) # type: ignore
assert isinstance(self.reader, Reader)
self.nfa = None
self.isRact = False
self.isHat = False
self.isDoller = False
self.isMaxMatch = False
assert isinstance(self.reader... | This code performs string substitution by replacing non-overlapping matches of a pattern in the input text with a replacement string. It either replaces up to 'count' occurrences (if count > 0) or all occurrences (if count ≤ 0), recompiling the pattern and searching iteratively until no more matches are found, then ret... | def sub(self, pattern: str, repl: str, text: str, count=0) -> str:
if count > 0:
for i in range(count):
self.compile(pattern)
matchRange = self.search(text)
if not matchRange:
break
text = getNewText(matchRange, repl... |
def _load_sets(self):
self.tfs = None
#full training set, no normalisation
self.full_train_set = None
#full testing set
self.full_test_set = None
NameError("template class, no loading")
def get_train_dl(self,force=False):
if force: #force will regenerate the dls -... | This code initializes a data loader with configurable batch sizes, normalization, and validation strategies (k-fold cross-validation or a single validation split). It sets up training, validation, and test data loaders, ensuring mutual exclusivity between k-fold and single-split validation. The class loads datasets, ha... | def __init__(self,
batch_size_train=64,
batch_size_valid=64,
batch_size_test=1,
normalise=False,
k_cv=None,
v_split=None
):
self.batch_size_train = batch_size_train
self.batch_size_test = batch_size_test
#bool to... |
def _fill_and_sort(df: pandas.DataFrame) -> pandas.DataFrame:
"""
Fill: df has been joined against ChoirGenius, which may not be 1:1, so we
want to fill in NAs where we can.
Sort: always by SATB, then by Name.
"""
replacements = {
"color": df.color.fillna("black"),
"sort_key": d... | The main task of the code is to generate a projected attendance report for an upcoming rehearsal by merging roster data with projected attendance, calculating subtotals for confirmed attendees, marked absences, and unmarked entries, and formatting the results into an HTML email body with a descriptive subject line. The... | def generate_projected_attendance_report(
projected_attendance: pandas.DataFrame,
roster: pandas.DataFrame,
today: date,
cycle_to: date,
) -> Tuple[str, str]:
"""Returns: subject (txt), body (HTML)"""
join = roster.merge(projected_attendance, on="Name", how="outer", indicator="projected")
j... |
def _fill_and_sort(df: pandas.DataFrame) -> pandas.DataFrame:
"""
Fill: df has been joined against ChoirGenius, which may not be 1:1, so we
want to fill in NAs where we can.
Sort: always by SATB, then by Name.
"""
replacements = {
"color": df.color.fillna("black"),
"sort_key": d... | The function generates an HTML attendance report for a choir, comparing actual and projected participation, highlighting absences, participants, and inconsistencies. It categorizes singers by status (e.g., active, maybe, absent), summarizes rehearsal attendance, flags unexcused absences, and includes warnings for data ... | def generate_attendance_report(
actual_attendance: pandas.DataFrame,
projected_attendance: pandas.DataFrame,
roster: pandas.DataFrame,
cycle_to: date,
) -> Tuple[str, str]:
"""Returns: subject (txt), body (HTML)"""
concerts = [c for c in roster.columns if isinstance(c, date)]
past_rehearsa... |
def _array_to_bytes(array: np.ndarray) -> bytes:
"""
encodes a numpy array to bytes using an own protocol
protocol usage:
- write-time (8 bytes)
- numpy dtype index (integer, 8 bytes)
- number of dimension (integer, 8 bytes)
- length of axis (array dimension) 0 (... | The main task of the code is to write a NumPy array into a memory-mapped (mmap) file, handling cases where the array's data type, shape, or dimensions differ from the existing mmap. If changes are detected, the mmap is silently recreated, which may impact performance. The array data and mmap name are then written to th... | def write(self, array: np.ndarray) -> None:
"""
write a numpy array into the mmap file, it might be from any type, shape or dimension
Important Note:
a mmap will be silently re-created if type, dimension or shape will be changed. the other process will read
the first lin... |
def bytes_to_str(b: bytes) -> str:
"""
converts bytes to a string
:param b:
:return:
"""
return b.decode('utf-8')
def _create_ndarray_mmap(self) -> bool:
"""
creates two mmap:
- the mmap with tag 'name' just holds the mmap-tag-name of ndarray
- the mmap o... | (The code reads shared memory using `mmap` and `numpy.frombuffer`, returning a view of the buffer as a NumPy array. It checks data validity by comparing timestamps at the buffer's start and end. If invalid or outdated, it returns the existing array; otherwise, it reads the buffer, converts it to a NumPy array, and upda... | def read(self) -> Tuple[bool, np.ndarray]:
"""
reading the shared memory with mmap and numpy's frombuffer, which returns a view of the buffer and not a copy.
Citing the documentation from numpy.frombuffer:
"This function creates a view into the original object. This should be safe in ge... |
def _array_to_bytes(array: np.ndarray) -> bytes:
"""
encodes a numpy array to bytes using an own protocol
protocol usage:
- write-time (8 bytes)
- numpy dtype index (integer, 8 bytes)
- number of dimension (integer, 8 bytes)
- length of axis (array dimension) 0 (... | This code initializes an object to handle memory-mapped NumPy arrays for reading/writing, setting up attributes like the array data, access mode ('r'/'w'), memory-mapped file descriptors, buffer sizes, and validation flags. It converts the input array to bytes, creates a memory-mapped file for the array's name, and ini... | def __init__(self, name: str, array: np.ndarray = np.ndarray((0, ), dtype=np.uint8),
r_w: Union[str, None] = None):
"""
:param name:
:param array:
:param r_w: 'r' or 'w' for 'read' or 'write' functionality, must be specified
"""
object.__init__(self)
... |
def check_pyversion() -> None:
"""Make sure python is 3.6 <= version < 3.8."""
pyversion = float(str(sys.version_info[0]) + '.' + str(sys.version_info[1]))
if not pyversion >= 3.6:
text = f'''FAIL: You are using python {pyversion}. This pipeline was built with python 3.7.
FAIL: use 3.6 <= python ve... | The main task of the code is to calculate genetic diversity measures across populations using parallel processing. It processes variant data, launches IPython clusters for distributed computation, attaches necessary data/functions to engines, computes statistics, writes results to files, and cleans up temporary files. ... | def main(pidiv_buffer:dict={}):
from tqdm import tqdm as pbar
# make sure it's not python3.8
check_pyversion()
# get args
args = get_pars()
# get ploidy dict
# global ploidy # for debugging send_windows()
ploidy = get_ploidy(args)
# iterate through pops
for pop in ploidy:
... |
def get_pi_calculator(b:int, n:int, snps:dict, pidiv_buffer:dict={}, amnm_buffer:dict={}) -> (float, dict):
"""Calculate Tajima's pi.
Parameters
----------
b - The minimum count of the minor allele, input by user.
poolsize (->n) - The haploid number of the pool which has been sequenced.
snps - ... | This function calculates Tajima's D for a genomic window using allele frequency data, coverage thresholds, and precomputed buffers. It computes π (nucleotide diversity) and θ (theta) from SNP data, then derives D by dividing their difference by a coverage-adjusted divisor. Parameters include allele count thresholds, po... | def get_D_calculator(b:int, n:int, mincoverage:int, snps:dict, pidiv_buffer:dict={}) -> (float, dict):
"""Calculate Tajima's D (corrected).
Parameters
----------
b - The minimum count of the minor allele.
poolsize (->n) - The haploid number of the pool which has been sequenced.
mincoverage - Th... |
def acquire_next_instruction(self) -> str:
assert self.icounter + 1 <= 1024, "Instruction memory border violation!"
return self.instr_memory[self.icounter * INSTRWORD : (self.icounter + 1) * INSTRWORD].hex()
def execute_non_arg_instruction(self, instr: str):
global takt
specific = bin2op... | The main task of the code is to process and execute instructions by determining their type (non-argument or argument) based on the first character of the instruction string, then invoking the corresponding method. It also increments a counter without altering internal state variables. | def execute_instruction(self):
instr: str = self.acquire_next_instruction()
if instr[0] == "1":
self.execute_non_arg_instruction(instr)
self.tick() # No internal changing of icounter
else:
self.execute_arg_instruction(instr) |
def H2(msg, hash_func=hashlib.sha3_256):
"""
Hashes a message into an elliptic curve point.
PARAMS
------
msg: (str or list) message(s) to be hashed.
hash_func: (function) Cryptographic hash function that recieves an input
and outputs a digest.
... | The code generates a **ring signature** for a message using a signing key from a list of public keys, ensuring anonymity. It computes signature components (c₀, s, Y) through elliptic curve operations, random values, and cryptographic hashing. The process involves iterating through public keys to create a linked, untrac... | def ring_signature(siging_key, M, y, G=SECP256k1.generator, hash_func=hashlib.sha3_256):
"""
Generates a ring signature for a message given a specific set of
public keys and a signing key belonging to one of the public keys
in the set.
PARAMS
------
signing_key:... |
def H2(msg, hash_func=hashlib.sha3_256):
"""
Hashes a message into an elliptic curve point.
PARAMS
------
msg: (str or list) message(s) to be hashed.
hash_func: (function) Cryptographic hash function that recieves an input
and outputs a digest.
... | The function generates a **ring signature** to anonymously sign a message using a private key from a set of public keys. It computes a signature (c₀, s, Y) that hides the signer's identity while ensuring linkability. Key steps include hashing public keys, generating random values, and combining elliptic curve operation... | def ring_signature(siging_key, M, y, G=SECP256k1.generator, hash_func=hashlib.sha3_256):
"""
Generates a ring signature for a message given a specific set of
public keys and a signing key belonging to one of the public keys
in the set.
PARAMS
------
signing_key:... |
def keyGen():
# key Generation
x1 = 32076546148956423627106248222626084294972657934863549023221256992304541353107
#print('x1', x1)
y1 = SECP256k1.generator * x1
#print('y1', y1)
#print('\n')
x2 = 74795400463534456695435033379044030273893345165242468307267086552055671981939
#print('x2',... | The main task of the code is to verify a ring signature in a cryptographic protocol. It retrieves a generated key, filters elements based on server-provided public keys (a, b, c), reads a message and signature components (c₀, s), computes linkability (Y), and checks the validity of the ring signature. It also verifies ... | def main():
k = keyGen()
#arr1 = [y1,y2,y3,y4];
arr1 = [k[0],k[1],k[2],k[3]]
#print(arr1)
#getting pk from server
#read value of "a" from text file
f = open("/home/rimjhim/front_end/JWT_token/token_simplify/Ring/Ring_Server/pk1.txt", "r")
aa = f.read()
a = i... |
def keyGen():
# key Generation
x1 = 32076546148956423627106248222626084294972657934863549023221256992304541353107
#print('x1', x1)
y1 = SECP256k1.generator * x1
#print('y1', y1)
#print('\n')
x2 = 74795400463534456695435033379044030273893345165242468307267086552055671981939
#print('x2',... | The main task of the code is to generate a ring signature by shuffling a set of keys, combining a message with a nonce, and writing the resulting signature components to files. It involves key generation, data shuffling, message processing, and ring signature creation using a private key. The shuffled keys and signatur... | def main():
#key generation
k = keyGen()
#getting pk list from server
#a = int(sys.argv[1])
#print(a)
#b = int(sys.argv[2])
#print(b)
#c = int(sys.argv[3])
#print(c)
data_random = unique_rand(1, 3, 2)
#print(data_random)
data_random.append(0)
#print(data_ra... |
def _add_connection(self, conn):
self.connections[conn.address] = conn
id_message = { "key" : self.next_id,
"operation" : "id",
"meta" : None }
conn.sendMessage(json.dumps(id_message))
self.next_id += 1
def _remove_connection(self, conn):
... | This method processes operations from a queue in a loop, handling tasks like adding/removing connections, posting data, updating entries, handling messages, managing queries, and cleaning queries. It uses a timeout to avoid blocking, and dispatches each operation to corresponding private methods based on its name. Unre... | def op_queue_thread(self):
while True:
try:
op = self.op_queue.get(block=True, timeout=0.5)
if op["name"] == "add_connection":
self._add_connection(op["data"])
elif op["name"] == "remove_connection":
self._remove... |
def parse_url(self):
parsed = urlparse(self.path)
qs = parse_qs(parsed.query, keep_blank_values=True)
comps = parsed.path[1:].split("/")
return (comps, qs)
def get_key(self, qs=None):
if qs and "key" in qs:
return qs["key"][0]
return self.headers["X-CVL-Object... | This code handles HTTP GET requests for a server API, processing URLs like /object (to retrieve metadata/data), /list (filtered object keys), /events (event mode), /ts (time-series queries), /info (system info), and /trust (certificate trust confirmation). It uses query parameters or headers to determine data type, sen... | def do_GET(self):
try:
"""
Basic API for getting data (meta is default and need not be specified):
GET /object?[meta || data][&key=<key>]
The key can also be sent as an HTTP-header (X-CVL-Object-Key)
"""
comps, qs = self.parse_... |
def send_404(self):
self.send_mime(bytes("Not found", encoding="utf-8"), "text/plain", 404)
def parse_url(self):
parsed = urlparse(self.path)
qs = parse_qs(parsed.query, keep_blank_values=True)
comps = parsed.path[1:].split("/")
return (comps, qs)
def get_key(self, qs=None):
... | This function handles POST requests by performing operations like publishing, deleting, controlling, querying, or updating data via a manager. It checks if the manager is read-only, parses the request, validates the operation, executes the corresponding action (e.g., updating key-value pairs or querying responses), and... | def do_POST(self):
global manager
if manager.read_only:
self.send_404()
return
try:
comps, qs = self.parse_url()
key = self.get_key()
post_data = self.load_post_data()
if len(comps) != 1:
self.send_404()
... |
def send_404(self):
self.send_mime(bytes("Not found", encoding="utf-8"), "text/plain", 404)
def parse_url(self):
parsed = urlparse(self.path)
qs = parse_qs(parsed.query, keep_blank_values=True)
comps = parsed.path[1:].split("/")
return (comps, qs)
def get_key(self, qs=None):
... | This code handles PUT requests to publish data via a web server. It checks if the manager is read-only, parses the URL, retrieves the key and data, and updates the manager with the data if the operation is "publish" and data exists. Otherwise, it returns a 404 error. Error handling also triggers a 404 on exceptions. | def do_PUT(self):
global manager
if manager.read_only:
self.send_404()
return
try:
comps, qs = self.parse_url()
key = self.get_key()
data = self.load_data()
#print(f"Loaded {len(data)} bytes of data for key '{key}'")
... |
def monthly_rate_today():
dt = ClubDetails.objects.all()
today = date.today()
start_date = today
monthly_rate = 0
months_in_operation = 0
form = DetailsForm()
if dt and dt.count() > 0:
dt = dt[0]
start_date = dt.start_date
monthly_rate = dt.monthly_contribution
... | This code generates PDF reports for admin dashboards and user profiles in a Django application. It checks user authentication and permissions, retrieves financial data (loan rates, contributions, expenses), and renders templates into PDFs using xhtml2pdf or WeasyPrint. Admin reports include operational metrics, while u... | def get(self, request, what=None):
if not request.user.is_authenticated():
return redirect('login_user')
if not what:
raise Resolver404('Not Found')
if what == 'admin_dashboard':
if not request.user.user_type == "admin":
raise PermissionDeni... |
def pick_neighbour_for_himmelblau(solution_tuple, multiplicative_constant):
"""Picks a solution in the neighbourhood of solution_tuple for
the himmelblau function
Parameters
----------
solution_tuple: tuple
A two element tuple containing the x an y coordinates of a
solution to the h... | This function uses simulated annealing to minimize the Himmelblau function starting from given initial coordinates. It employs a multiplicative constant to generate neighboring solutions, iterates based on a temperature schedule, and returns the final optimized solution after plotting objective values per temperature. | def himmelblau_simulated_annealing_solver(initial_x, initial_y, multiplicative_constant, iteration_size, temp_params):
"""Runs the simulated annealing algorithm to minimize the himmelblau
function, starting from the initial solution initial_x and initial_y
Parameters
----------
initial_x: float
... |
def get_user_move(self):
move = int(input('Select Location (0-8) : '))
if move in self.possible_moves:
return move
else:
print("Invalid Input!")
return self.get_user_move()
def get_easy_move(self):
from random import randint
if len(self.possibl... | The main task of the code is to determine the current player's type and return a move value between 0-8 by delegating to specific methods like get_user_move() or AI-level-specific functions (easy, medium, hard). It uses conditional checks on self.current_player to route to the appropriate move-generation logic. | def get_move(self):
from setup import PlayerType
# This function returns any value between 0 and 8
if self.current_player == PlayerType.user.value or self.current_player == PlayerType.otherUser.value:
return self.get_user_move()
elif self.current_player == PlayerType.easyAI.v... |
def print_board(self):
print(self.board[0], self.board[1], self.board[2])
print(self.board[3], self.board[4], self.board[5])
print(self.board[6], self.board[7], self.board[8])
def execute_move(self, move):
if self.current_player == self.playerX:
self.board[move] = 'X'
... | The code's main task is to execute a game loop where players take turns making moves, checking for a win or draw after each move, updating the game board, and switching players until the game ends. It prints the board state, determines the winner, and announces the result as "Tie!", "X Wins!", or "O Wins!" based on the... | def play_game(self):
self.print_board()
while not self.game_ended:
self.execute_move(self.get_move())
self.check_winner()
self.is_draw()
self.print_board()
print('')
self.switch_player()
if self.winner == '-':
pr... |
def generate_inner_circle(self, which_inner: int = 0):
"""
Draw the inner circle with a radius a fraction of the outer circle.
That fraction is given as the ratio.
"""
if not self.options.draw_inner_circles:
return
inner_center = self._get_inner_center(which_... | The main task of the code is to generate additional inner circles, their associated dots, and polygons for a star pattern. It iterates from a specified starting index, calculating the number of circles based on the star's sides and skip value, then calls methods to draw each inner circle, its dot, other dots, and polyg... | def generate_other_inner_circles(self, starting_from: int = 1):
"""
Draw the additional inner circles and their dots and polygon.
"""
count = self.star.sides - self.star.skip
for which_inner in range(starting_from, count):
self.generate_inner_circle(which_inner)
... |
def _gen_all_dots_pos(self):
"""
Generate all positions for all dots on all inner circle.
Fills a 2D array called inner_dots_pos indexed by inner circle
and dots.
"""
self.inner_dots_pos = self._gen_all_dots_for_rot(self.circle_rotation_pos, self.circle_rotation_pos_steps... | The main task of the code is to animate inner circles and their associated polygons by updating rotation positions, regenerating dot positions, reallocating the scene, and redrawing outer circles, inner circles, stars, and inter-circle polygons to create dynamic visual motion. | def animate_all(self):
"""
Animate all the inner circles and their polygons.
"""
self.circle_rotation_pos = (self.circle_rotation_pos + 1) % (self.circle_rotation_pos_steps * self.star.sides)
self._gen_all_dots_pos()
self.reallocate_scene()
self.generate_outer_cir... |
def RK4_orbit(model,filename, runtime=100000, deltat=100, x_0=-(R_E+408e3), y_0=0, v_x_0=0, v_y_0=7.66e3):
'''Calculates orbit using RK4 method.'''
iterations = int(runtime/deltat) #number of iterations
#initialise empty arrays
x_vals = []
y_vals = []
v_x_vals = []
v_y_vals = []
... | The code provides a menu-driven interface for selecting and executing predefined RK4 numerical integration scenarios (circular, elliptical, or moon hourglass orbits). It processes user input to trigger orbit simulations with fixed parameters, generates trajectory plots, energy graphs, and mission reports for each selec... | def default_menu(model):
'''Menu function for choosing between pre-coded RK4 scenarios.'''
Def_Input = '0'
print('For each scenario, a single successful orbit is completed.')
while Def_Input != 'q':
def_question = '''
Characteristic orbits menu (RK4):
Enter a choice - "1" (c... |
def simp_inputting():
'''Takes user input for overarching simulation parameters.'''
runtime = posint('Enter simulation run time: ')
deltat = posflt('Enter timestep: ')
return runtime, deltat
def change_var():
'''Menu function to investigate effect of changing parameters on resulting or... | The code generates multiple orbital trajectory plots by varying initial conditions (position, velocity, or time step) using the RK4 method, visualizing how different parameters affect the orbit, and saving each set of results as a PDF with labeled legends. | def trial_error():
'''Generates array of plots for different initial values.'''
runtime, deltat = simp_inputting() #gets runtime and time step
variable, model = change_var()
x_0, y_0, v_x_0, v_y_0 = initial_values_input() #gets initial values
num_tries, val_range = trial_er... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.