dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def frequency_counter(self, data):
frequency = {}
for char in data:
frequency[char] = frequency.get(char, 0) + 1
return frequency
def build_heap(self, frequency):
for char, freq in frequency.items():
node = Node(char, freq)
heapq.heappush(self.heap, (f... | This code compresses a file using Huffman coding. It reads the input file, calculates character frequencies, builds a Huffman tree, generates binary codes, converts the data into a binary string, and writes the compressed result to a new binary file with '_compressed.bin' extension. | def compress(self):
with open(self.filename, 'rb') as file:
data = file.read()
frequency = self.frequency_counter(data.decode('latin-1'))
self.build_heap(frequency)
self.build_tree()
self.build_codes()
compressed_text = ''.join(self.codes[char] for char in d... |
def __get_hoep(self) -> float:
return self.__get_hoep_detail().sum()
def __get_dist_charge(self, dist_charge=DISTRIBUTION_CHARGE) -> float:
return self.__get_adj_kVA() * dist_charge[str(self.year)][0] * adjust_constant(self.start, self.end)
def __get_net_charge(self, net_charge=TRANSMISSION_NETWORK_CHA... | This function calculates and returns the total bill amount by summing various charge components such as HOEP, distribution, network, connection, global adjustments, market charges, customer charges, administrative fees, and capacity recovery, while subtracting transformer allowance charges. | def bill(self) -> float:
return self.__get_hoep() + self.__get_dist_charge() + \
self.__get_net_charge() + self.__get_conn_charge() + self.__get_global_adjustment() + \
self.__get_whole_market_charge() + self.__get_customer_charge() - \
self.__get_transformer_allowan... |
def isTruePositive(entry):
return entry[3] and entry[1]>=0.5
def isFalsePositive(entry):
return not entry[3] and entry[1]>=0.5
def isFalseNegative(entry):
return entry[3] and entry[1]<0.5
def isTrueNegative(entry):
return not entry[3] and entry[1]<0.5
def confusionMatrix(tp,fp,fn,tn):
total = tp+fp+... | The code generates an HTML report displaying a confusion matrix and a table of results, calculating true positives, false positives, false negatives, and true negatives from input data, then structuring them into a styled HTML document for visualization. | def get_html(results):
tp = sum(1 for x in results if isTruePositive(x))
fp = sum(1 for x in results if isFalsePositive(x))
fn = sum(1 for x in results if isFalseNegative(x))
tn = sum(1 for x in results if isTrueNegative(x))
cm = confusionMatrix(tp, fp, fn, tn)
table = html_table(results)
... |
def read_file(filename):
linelist = list();
with open(filename) as fin:
temp = _read_line(fin)
while temp:
linelist.append(temp)
temp =_read_line(fin);
return linelist
def command_parse(raw_command):
identifier = raw_command[0];
if(identifier == ':'):
return ['label', raw_command[1:], None]
elif(ide... | This code parses command-line arguments to process text using predefined commands. It reads commands from either a file (via -f) or direct inputs (via -e), then applies these commands to input lines from a specified file or standard input, transforming and printing each line accordingly. | def main():
parser = argparse.ArgumentParser(description ='heck');
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-f');
group.add_argument('-e', action='append');
parser.add_argument('filename', nargs='?')
args = parser.parse_args();
if args.f == None:
mylist = args.e
else:
m... |
def menu():
clear()
si()
print(Color.LG+".help "+Color.LC+"to show the commands")
print(Color.LG+"\|/"+Color.LW+" (__)")
print(Color.LW+" `\–––––(oo)")
print(Color.LW+" || (__)")
print(Color.LW+" ||w––|| "+Color.LG+"\|/")
print(Color.LG+"\|/")
print(Color.LC+"Founder:... | The main task of the code is to serve as a command-line interface for launching Layer 4/7 DoS attacks, proxy management, and attack control. It processes user commands to execute attack methods like VSE, SYN, TCP/UDP floods, HTTP/HTTPS attacks, proxy fetching/checking, and attack termination, using Node.js/Python scrip... | def main():
menu()
while True:
cnc = input(Color.LG+"\n\n╔═══"+Color.LW+"aqzxt"+Color.LG+"@"+Color.LW+"cow"+Color.LM+"\n╚══"+Color.LY+"×͜×"+Color.LC+" # "+Color.RESET)
http_proxy1 = "https://www.proxy-list.download/api/v1/get?type=http&anon=elite"
http_proxy2 = "https://api.proxyscrape.... |
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def pgrs():
widgets = [Color.LY+f'Configuring script: '+Color.RESET, progressbar.AnimatedMarker()]
print(Color.LM+"Maybe take some time, please wait.")
bar = progressbar.ProgressBar(widgets=widgets).start()
for i in range(10... | The code generates a CAPTCHA by randomly combining characters and numbers, prompts user input, and validates it. If correct or if the input is "admin" or ".", it proceeds to execute subsequent functions; otherwise, it exits. The CAPTCHA is designed for verification, with admin bypass functionality and colored output fo... | def capcha():
a1 = "You are "
b1 = "human.\n"
c1 = "robot.\n"
admin = "admin"
admin1 = "."
word1 = ("a", "b", "c", "d", "e", "f", "g", "k", "o", "p", "x", "m", "n", "v", "z", "l", "j", "s", "y", "t", "r", "w", "q", "u", "A", "B", "C", "D", "E", "F", "G", "K", "O", "P", "X", "M", "N", "V", "Z", "... |
def value_state_initialization(self):
state1 = self.initial_improved
states = list()
rewards = list()
values = list()
m = len(state1['map'])
n = len(state1['map'][0])
taxis_names = [taxi_name for taxi_name in state1['taxis'].keys()]
number_taxis = state1['... | This code implements a value iteration algorithm to compute the optimal policy in a reinforcement learning scenario. It iteratively updates state values by evaluating all possible actions and their expected future rewards, using transition probabilities to determine the best action for each state. The process repeats o... | def new_value_iteration_algorithm_old(self):
states, rewards, values_t = self.value_state_initialization()
values_t_1 = copy.deepcopy(values_t)
print('starting value iteration')
all_possible_actions = self.create_randoms_action()
t = self.initial["turns to go"]
lst_action... |
def value_state_initialization(self):
state1 = self.initial_improved
states = list()
rewards = list()
values = list()
m = len(state1['map'])
n = len(state1['map'][0])
taxis_names = [taxi_name for taxi_name in state1['taxis'].keys()]
number_taxis = state1['... | The code implements the value iteration algorithm to determine optimal actions for each state in a taxi environment. It iteratively computes expected values by evaluating all possible actions, their resulting states, and transition probabilities. Rewards and values are updated based on maximum expected future rewards, ... | def value_iteration_algorithm(self):
states, rewards, values_t = self.value_state_initialization()
values_t_1 = copy.deepcopy(values_t)
print('starting value iteration')
all_possible_actions = self.create_randoms_action()
t = self.initial["turns to go"]
lst_action = [None... |
def get_column_identifiers(
statement: sqlparse.sql.Statement,
) -> List[sqlparse.sql.Identifier]:
"""Get the column identifiers from a SQL statement"""
identifiers = []
for token in statement.tokens:
if token.ttype is None and type(token) is not sqlparse.sql.Function:
if type(token)... | This function parses a SQL model file to extract and return a list of column names, handling Jinja templates and non-standard SQL common in dbt models by filtering SELECT statements, extracting identifiers, and converting them to column names. | def get_model_columns(model_path: Path) -> List[str]:
"""Parse the model SQL file and return a list of columns names
Args:
model_path (Path): Path to the model SQL file
Returns:
List[str]: List of column names
"""
raw = Path(model_path).read_text()
raw = re.sub(
r"{{[A-... |
def write_log(text):
print(text)
filename = "debug.log"
file_obj = open(filename, "a")
file_obj.write(text)
def plot_data(amt_noise, size, res, equation, wireframe=False, points=True):
x = np.arange(-size, size, res)
y = np.arange(-size, size, res)
x, y = np.meshgrid(x, y)
z = f(x, y, eq... | The code generates 3D plots using a mathematical equation or a trained neural network, based on user input. It retrieves parameters, logs them, plots data, trains a model if enabled, and visualizes results with progress updates. | def go():
amt_moise = noise.get()
size_loc = size.get()
res = resolution.get()
equation = "sin(x*3)+sin(y*3)+2.5"
use_nn_bool = use_or_not.get()
write_log("Amount of Noise: {}\nResolution: {}\nEquation: {}\nSize: {}\n\n". format(amt_moise, res, equation, size_loc))
x, y, z, plot = plot_... |
def get_skype_config():
with open(Path('alert') / 'resources' / 'skype_config.toml', 'rb') as f:
config = tomllib.load(f)
return config
def get_current_data(symbol: str) -> dict:
now = dt.datetime.now().replace(microsecond=0)
curr = get_historical_data(
symbol=symbol,
resolution... | This code continuously fetches financial data for a given symbol, monitors predefined time-based events (e.g., market sessions, breaks), and sends real-time alerts via Skype to specified users. It checks price thresholds against user-defined alerts, triggers notifications when conditions are met, updates alert statuses... | def fetch_continuous_data(
symbol: str,
interval: int = 1,
verbose: bool = True,
live_alert: bool = True,
) -> None:
config = get_skype_config()
sk = Skype(user=config['acc'], pwd=config['pwd'])
admin = sk.chats[config['admin']]
targets = [sk.chats[target_user] for target_user in config[... |
def set_labels(self, labels: ndarray) -> None:
"""Method to set the labels of the dataset.
Parameters
----------
labels : ndarray
array to substitute the current data
"""
self.data["labels"] = labels
def get_labels(self) -> ndarray:
"""This method ret... | The main task of the `unravel` method is to concatenate all features in the dataset by reshaping hand-crafted and deep features into 2D arrays, updating the SmileData instance either in-place or returning a new instance. It also repeats labels based on time duration and marks the dataset as unraveled. The method handle... | def unravel(self, inplace: bool = True) -> Union[None, "SmileData"]:
"""Method to unravel the dataset.
The method unravels the dataset by concatenating all the features in the dataset.
Parameters
----------
inplace : bool, optional
if True, the method will modify th... |
def count_top_conveyor_discs(self):
# count = sum(1 for obj in self.discs if obj.loc == location.TOP_CONVEYOR)
# return count
return len(self._filter_top_conveyor_records())
def get_field_names(self):
record = disc_record() # dummy disc to get the field names
columns = [str(fie... | The main task of the code is to publish conveyor system states by first sending the count of discs on the top conveyor, then combining field names with non-top conveyor records to update the main conveyor publisher with structured data. | def publish(self):
# after all discs are moved, we can publish some new states
self.top_conveyor_publisher.publish(str(self.count_top_conveyor_discs()))
column_names_included = self.get_field_names() + "\n" + self.get_stringified_non_top_conveyor_records()
self.main_conveyor_publisher.p... |
def work(self):
print("Time to work...")
self.cheat -= 2
self.gladness -= 3
self.progress -= 2
self.money += 200
def end_of_day(self):
print(f"Cheating = {self.cheat}")
print(f"Gladness = {self.gladness}")
print(f"Progress = {round(self.progress, 2)}")
... | The code simulates a daily life cycle for an entity, handling events based on the day number and internal attributes (money, progress, gladness). It prints formatted day headers, executes work, study, sleep, or chill actions conditionally, triggers fate/exam events on specific days, and checks survival status. Random d... | def live(self, day):
day_format = "Day " + str(day) + " of " + self.name + " life"
print(f"{day_format:=^50}")
if day != 182:
if day != 181:
if day != 364:
if day != 365:
if self.money <= 150:
if... |
def display_welcome(self):
print("\nWelcome to the epic battle of the millenia! \nMeet the furious fleet of robots:\n")
for robot in self.fleet.fleet_list:
print(robot.name)
print("\nAnd of the Jurassic weight class, give it up for this horrible herd:\n")
for dinosaur in self.herd.herd_list:
... | The `run_game` method executes the game流程 by first displaying a welcome message and introduction, then initiating the game. It proceeds through a standard battle sequence (`battle()`) or a shortcut (`quick_battle()` if enabled), ultimately displaying the winners. The core task is to orchestrate the game's progression f... | def run_game(self):
self.display_welcome() #TESTED
self.introduction() #TESTED
self.begin_game() #TESTED
self.battle() #This is the scenic route to the end.
# Quick_battle() is a shortcut.
#Comment out self.battle() and uncomment quick_battle below
#self.quick_battle()
self.disp... |
def blok_gen(self):
path = 'TestData'
blokken = []
jaar = []
for y in range(4):
for x in range(4):
jaar.append(y + 1)
blokken.append("Blok {}".format(x + 1))
MYarray = np.array([jaar, blokken]).transpose()
blok_columns = ["Jaar", "Blok"]
blok = pd.DataFrame(M... | The main task of the code is to execute a sequence of test functions for generating and validating educational data (blocks, tests, grades, students) and redirecting to a development URL. It calls multiple data generation and validation methods, then returns an HTTP redirect response to "http://62.251.126.253:63343/dev... | def Run_all_gen_test(self):
blok_gen(self)
run_toets_gen(self)
run_cijfer_gen(self)
run_student_gen(self)
DataTest_student(self)
DataTest_blok(self)
DataTest_Jaar_Toets_Resultaat_Pogingen(self)
DataTest_cijfer(self)
return HttpResponseRedirect("http://62.251.126.253:63343/dev.html") |
def get_batches(arr, batch_size, seq_length):
"""Create a batch generator."""
# find the total number of batches that can be made
batch_size_total = batch_size * seq_length
n_batches = len(arr) // batch_size_total
# keep only enough characters to make full batches
arr = a... | This code trains a recurrent neural network (RNN) on character-level data to generate text. It uses Adam optimization, cross-entropy loss, and gradient clipping. The model is trained in batches, with validation splits, tracking loss and perplexity metrics. Periodic validation checks and sample text generation are inclu... | def train(self, epochs=3, batch_size=10, seq_length=50, lr=0.001, clip=5, val_frac=0.1, print_every=10):
"""Train the model."""
# put the model into its training state
self.rnn.train()
# set up the optimizer and cross-entropy metric
opt = torch.optim.Adam(self.rnn.parameters(), l... |
def print_datetime(string):
"""Note that this call will sync across all ranks."""
torch.distributed.barrier()
time_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print_rank_0('[' + string + '] datetime: {} '.format(time_str))
def train_step(forward_step_func, data_iterator,
model, opt... | The function `train` executes a training loop for a neural network model, iterating over training data to update model parameters using a provided optimizer and learning rate scheduler. It tracks losses, manages distributed training aspects (e.g., microbatches), logs progress, performs periodic validation, and handles ... | def train(forward_step_func, model, optimizer, lr_scheduler,
train_data_iterator, valid_data_iterator):
"""Train the model function."""
args = get_args()
timers = get_timers()
# Write args to tensorboard
write_args_to_tensorboard()
# Turn on training mode which enables dropout.
m... |
def print_datetime(string):
"""Note that this call will sync across all ranks."""
torch.distributed.barrier()
time_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print_rank_0('[' + string + '] datetime: {} '.format(time_str))
def setup_model_and_optimizer(model_provider_func):
"""Setup model and... | The main task of the code is to pretrain a model by initializing the training environment, setting up the model, optimizer, and learning rate scheduler, loading training/validation/test datasets, and executing the training loop using a specified forward step function. It handles distributed training setup, data iterati... | def pretrain(train_valid_test_dataset_provider, model_provider,
forward_step_func, extra_args_provider=None, args_defaults={}):
"""Main training program.
This function will run the followings in the order provided:
1) initialize Megatron.
2) setup model, optimizer and lr schedule u... |
def filter_user_tasks(task_list, username):
"""
filters all tasks down into a list of tasks related to one user.
only tasks that havent been completed are included.
param: task_list - list of all task objects.
param: username - the user's name
returns: [{"task_num": assigned task number, "idx_n... | The function allows a user to view their assigned tasks, select a task to edit, and returns a deep copy of the updated task list if edits are made. If no tasks exist or edits fail, it returns -1. | def view_mine(task_list, user_list, user):
"""
allows user to view all assigned tasks and
edit a task.
param: task_list - list of task objects.
param: user_list - list of user objects.
param: user - current user.
returns: a copy of a task object or -1.
"""
# get all tasks for the use... |
def initializer(structure):
weight = []
bias = []
# The total layer shall be n-1, where n denotes the dimension of the structure
for i in range(len(structure) - 1):
w = np.random.rand(structure[i], structure[i + 1]) / 10
b = np.random.rand(1, structure[i + 1]) / 1000
weight.appe... | This code trains a neural network using stochastic gradient descent (SGD) with mini-batches. It initializes the network structure, iterates over epochs, randomly selects samples for gradient updates, performs forward and backward propagation, accumulates gradients, and updates weights/biases using the learning rate. It... | def train(x, y, structure, epochs=10, learning_rate=0.00001, activation_type="relu", sample_number=5000):
# Initialize the network
weight, bias, layers = initializer(structure)
least_avg_loss = 10000000
for epoch in range(epochs):
# For SGD, we randomly pick 10 samples to update the parameters
... |
def nine_lines():
three_lines()
three_lines()
three_lines()
def three_lines():
new_line()
new_line()
new_line()
def new_line():
print('*') | The main task of the code is to simulate clearing the screen by sequentially calling helper functions that print lines: nine_lines() twice, three_lines() twice, and new_line() once, totaling 25 lines to overwrite or space out previous content. | def clear_screen():
nine_lines()
nine_lines()
three_lines()
three_lines()
new_line() |
def parseUsername(input):
"""Convert a string or partial list into a tuple representing a username.
Accepts firstname.lastname, firstname, ("firstname"), etc.
Returns ("firstname", "lastname")
"""
if type(input) == tuple or type(input) == list:
if len(input) == 1:
return ... | This function retrieves Second Life RegAPI capabilities by authenticating with a username and password. It sends a POST request to the Second Life server, parses the response, and stores the result in `self.capabilities`. A warning is shown if the developer doesn't explicitly confirm they understand the security risks ... | def getCapabilities(self, username, password, IKnowWhatIAmDoing = False):
"""This is a utility function to get the RegAPI capabilities.
It should only be used by the developer implementing this.
If you are writing a GUI, set IKnowWhatIAmDoing to True to suppress
the warning m... |
def getCapability(self, cap):
"""Helper function - Get the capability by name, otherwise throw an
error if we don't have it.
"""
if cap not in self.capabilities:
raise RegAPIError("No capability '{}'!".format(cap))
return self.capabilities[cap]
def doRequest(*args... | The main task of the code is to retrieve a list of usernames (last names) from an API, cache the result if enabled, convert string-based IDs to integers, and return the data in a dictionary format {id: "name"}. It checks for caching, sends a request with headers, decodes the response, handles potential errors, and ensu... | def getLastNames(self):
"""Returns a list of available usernames in {id: "name", ...} format"""
cap = self.getCapability("get_last_names")
result = None
if self.cache:
result = self.cache.get("get_last_names")
if not result:
req = urllib.request.R... |
def getCapability(self, cap):
"""Helper function - Get the capability by name, otherwise throw an
error if we don't have it.
"""
if cap not in self.capabilities:
raise RegAPIError("No capability '{}'!".format(cap))
return self.capabilities[cap]
def getError(self, ... | The main task of the code is to retrieve a list of experiences accessible by the capability, format them as {UUID: "name"} pairs, and return them while utilizing caching to avoid redundant requests. It fetches data via an HTTP request if not cached, decodes the response using LLSD, converts string keys to UUIDs, and st... | def getExperiences(self):
"""Returns a list of experiences the capability has access to in
{id: "name"} format
"""
cap = self.getCapability("get_experiences")
result = None
if self.cache:
result = self.cache.get("get_experiences")
if not r... |
def getCapability(self, cap):
"""Helper function - Get the capability by name, otherwise throw an
error if we don't have it.
"""
if cap not in self.capabilities:
raise RegAPIError("No capability '{}'!".format(cap))
return self.capabilities[cap]
def doRequest(*args... | The code retrieves a list of available starting avatars from a server, using caching to avoid redundant requests. It formats the result as a dictionary with UUID keys and avatar names, handling errors if necessary. If the cached data exists, it returns that; otherwise, it sends a request, decodes the response, converts... | def getAvatars(self):
"""Returns a list of available starting avatars in {id: "name"} format
"""
cap = self.getCapability("get_avatars")
result = None
if self.cache:
result = self.cache.get("get_avatars")
if not result:
req = urllib.reques... |
def getCapability(self, cap):
"""Helper function - Get the capability by name, otherwise throw an
error if we don't have it.
"""
if cap not in self.capabilities:
raise RegAPIError("No capability '{}'!".format(cap))
return self.capabilities[cap]
def doRequest(*args... | The main task of the code is to check if a given username is available by sending a POST request to an API endpoint. It uses the 'check_name' capability, encodes the request with LLSD format, and processes the response. If the result indicates unavailability, it raises an error; otherwise, it returns a boolean indicati... | def checkName(self, username, lastNameId = None):
"""Check if a username is available. Automatically assumes resident is
the lastname if not specified.
Raises RegAPIError if not available, returns True if available.
Might return False if not available!
"""
cap... |
def getCapability(self, cap):
"""Helper function - Get the capability by name, otherwise throw an
error if we don't have it.
"""
if cap not in self.capabilities:
raise RegAPIError("No capability '{}'!".format(cap))
return self.capabilities[cap]
def doRequest(*args... | The main task of the code is to create a user with a specified username and optional parameters like estate, location, marketing preferences, and redirect URLs. It constructs a data payload with default values, encodes it in LLSD format, sends a POST request via a capability endpoint, and returns the decoded API respon... | def createUser(self, username, lastNameId = None,
estate = None, region = None, location = None,
lookAt = None, marketing = None, successUrl = None,
errorUrl = None, maturity = None):
"""Creates a user with the provided username. Automatically assumes
... |
def getCapability(self, cap):
"""Helper function - Get the capability by name, otherwise throw an
error if we don't have it.
"""
if cap not in self.capabilities:
raise RegAPIError("No capability '{}'!".format(cap))
return self.capabilities[cap]
def doRequest(*args... | This function regenerates a user's nonce by sending a POST request with an agent ID to a specific capability endpoint. It encodes data in LLSD format, processes the response, and returns the result or raises an error if the response is a list. | def regenerateUserNonce(self, agentId):
"""Regenerate a registration URL. Useful if you have a internal database
and a user re-requests to create their authorized account.
AgentID must be a UUID.
"""
cap = self.getCapability("regenerate_user_nonce")
result = None
... |
def getCapability(self, cap):
"""Helper function - Get the capability by name, otherwise throw an
error if we don't have it.
"""
if cap not in self.capabilities:
raise RegAPIError("No capability '{}'!".format(cap))
return self.capabilities[cap]
def doRequest(*args... | This function sets an agent's starting avatar by sending a POST request with UUIDs for agentId and avatarId, using a time-limited capability. It encodes data in LLSD format, handles errors, and returns the result, but only works pre-login and within 1 hour of account creation. | def setUserAvatar(self, agentId, avatarId):
"""Set the starting avatar for agentId to avatarId. See getAvatars()
Both agentId and avatarId must be a UUID.
**This cannot be used after the resident logs in!**
**This ability expires after 1 hour of the account creation!**
... |
def getCapability(self, cap):
"""Helper function - Get the capability by name, otherwise throw an
error if we don't have it.
"""
if cap not in self.capabilities:
raise RegAPIError("No capability '{}'!".format(cap))
return self.capabilities[cap]
def doRequest(*args... | This function automatically makes a user accept a specified experience by sending a POST request with agent and experience UUIDs to a capability endpoint. It encodes data in LLSD format, handles errors, and enforces time-sensitive restrictions: it can only be used within 1 hour of account creation and before the reside... | def setUserExperience(self, agentId, experienceId):
"""Automatically make the user accept a experience.
agentId and experienceId must both be a UUID.
**This cannot be used after the resident logs in!**
**This ability expires after 1 hour of the account creation!**
"""... |
def getCapability(self, cap):
"""Helper function - Get the capability by name, otherwise throw an
error if we don't have it.
"""
if cap not in self.capabilities:
raise RegAPIError("No capability '{}'!".format(cap))
return self.capabilities[cap]
def parseUsername(i... | This function adds a user to a managed group by sending a POST request with the user's parsed name and group name, using a capability token. It handles authentication, request formatting, error checking, and returns the API response, raising exceptions for list-type errors. | def addToGroup(self, username, groupName):
"""Add a user to a group that you manage.
username can be a string or tuple.
**This CAN be used after the resident logs in!**
**This ability expires after 1 hour of the account creation!**
"""
cap = self.getCapability... |
def get_filelist(root_dir):
Filelist = []
for home, dirs, files in os.walk(root_dir):
for f in files:
filename = join(home, f)
if is_video_ext(filename) and os.path.isfile(filename):
Filelist.append(filename)
# Filelist.append( filename)
return... | The main task of the code is to process videos by extracting and cropping human body frames using segmentation masks, resizing them to 128x128, and generating SMPL 3D human model parameters (pose, shape, camera extrinsics/intrinsics) for each frame. The results are saved as cropped images and JSON files containing tran... | def main(source_dir, dest_dir):
# Hard-core params
H, W = 240, 320
pad = 4
out_res = 128
half_pad = pad / 2
t = 0
intrinsic = np.array([ [600, 0, 160],
[ 0, 600, 120],
[ 0, 0, 1] ], dtype=np.float32)
#input_videos = [str(f) fo... |
def __get_html(url):
"""
Getting text source page from url
:param url (string): Link of homepage of core vulnerability
:return source (string): HTML of web page
"""
source = requests.get(url).text
return source
def __get_end_page(html):
"""
Home Page: https://developer.joomla.org/sec... | The main task of the code is to crawl vulnerability data from Joomla's security center webpage using pagination, extract vulnerability details into a list, and write the collected data to a file at ../resources/joomla/core.jdb. The function iterates through pages, fetches HTML content, identifies end page limits, and s... | def update_core():
"""
This is the main of code, which will be called and returned
the data to file: ../resources/joomla/core.jdb
"""
list_database = []
end_page = 0
counter = 0
success_msg('Crawling on ' + link_msg('https://developer.joomla.org/security-centre.html\n\n'))
while... |
def update_dotted_and_hit_sets(
*,
fired_block: tuple,
computer_turn: bool,
diagonal_only: bool = True,
) -> None:
"""
Puts dots in center of diagonal or all around a block that was hit (either by human or
by computer). Adds all diagonal blocks or all-around chosen block to a separate set
... | The main task of the code is to determine if a fired block is a hit or miss by checking if it belongs to any ship in the opponent's list. If it hits, it updates game state markers (dots/Xs), removes destroyed ships, and returns True. If it misses, it marks the block as missed, updates tracking for computer turns, and r... | def check_hit_or_miss(
*,
fired_block: tuple,
opponents_ships_list: list[list],
computer_turn: bool,
opponents_ships_list_original_copy: list,
opponents_ships_set: set,
computer: AutoShips,
) -> bool:
"""
Checks whether the block that was shot at either by computer or by human is a h... |
def midjourney_community_feed(driver: WebDriver):
driver.get("https://www.midjourney.com/app/feed/")
def midjourney_search_prompts(search_term: str, driver: WebDriver):
search_input = driver.find_element(By.CSS_SELECTOR, 'input[name="search"]')
search_input.send_keys(search_term)
time.sleep(1)
# Fi... | The code crawls Midjourney content by using a browser driver to access community feeds, search prompts, and extract images. It stores the collected images in session state for further processing, with delays to ensure proper page loading and data retrieval. | def crawl_midjourney(tab_crawling):
session_state: SessionState = st.session_state["session_state"]
driver = session_state.browser.driver
time.sleep(1)
midjourney_community_feed(driver)
time.sleep(2)
midjourney_search_prompts(session_state.crawling_request.search_term, driver)
time.sleep(4)
... |
def build_tree(train):
root = get_split(train)
split(root)
return root
def print_tree(node, depth=0):
if isinstance(node, dict):
print('level:%d %s[X%d < %.3f]' % (depth, depth*' ', (node['index']+1), node['value']))
print_tree(node['left'], depth+1)
print_tree(node['right'], depth+1)
else:
... | The code constructs a decision tree from training data, predicts classes for test samples, and predicts a new data point. It prints the tree structure, test rows, and the new prediction, then returns the list of test predictions. | def decision_tree(train, test):
tree = build_tree(train)
print_tree(tree)
predictions = list()
for row in test:
prediction = predict(tree, row)
predictions.append(prediction)
print('The row: ',row)
newRow=[2.0, 12.86, 1.33, 22.97, 23.0, 40.0, 2.64, 5.78, 0.26, 1.50, 3.01, 0.0... |
def cross_validation_split(dataset, n_folds):
dataset_split = list()
dataset_copy = list(dataset)
fold_size = int(len(dataset) / n_folds)
for i in range(n_folds):
fold = list()
while len(fold) < fold_size:
index = randrange(len(dataset_copy))
fold.append(dataset_c... | The code evaluates a decision tree algorithm using k-fold cross-validation. It splits the dataset into folds, iterates through each fold as a test set while combining the rest as training data, trains the decision tree, predicts outcomes, compares predicted values to actual values, calculates accuracy for each fold, an... | def evaluate_algorithm(dataset, n_folds):
folds = cross_validation_split(dataset, n_folds)
scores = list()
for fold in folds:
train_set = list(folds)
train_set.remove(fold)
train_set = sum(train_set, [])
test_set = list(fold)
predicted = decision_tree(train_set, test_... |
def __get_numerical_columns(df: pd.DataFrame, exclude: Optional[Iterable[str]]) -> List[str]:
return [
column
for column in df.columns
if __is_numeric_type(df[column].dtype) and (exclude is None or column not in exclude)
]
def __get_date_columns(df: pd.DataFrame, exclude: Optional[Iterab... | This function generates risk diagrams for continuous variables in a DataFrame by binning them based on thresholds and date ranges. It uses a transformer to discretize data, filters relevant columns, and delegates plotting to a categorical risk visualization function, enabling analysis of incident distributions over tim... | def plot_risk_continuous(df: pd.DataFrame, target: str, columns_to_show: List[str] = None, date_column: str = None,
bad: int = 1, data_bin_n: int = 4, bin_by_month: bool = False, n_threshold: int = 50,
y_threshold: int = 10, p_threshold: float = 0.35, sign: bool = False... |
def point_setup(n:int, seed:int=0):
"""returns n points distributed on the unit sphere"""
np.random.seed(seed)
points = np.random.randn(3, n)
points /= np.linalg.norm(points, axis=0)
points = points.transpose()
return np.array(points)
def geom_opt(points, F_calc, iterations = 1000, factor = 1e-4... | The code optimizes molecular configurations by iterating through random initial setups, applying gradient descent to refine structures, transforming coordinates to center of mass, and using basin hopping for global optimization. It aims to find the lowest energy configuration by evaluating multiple starting points, ref... | def optimise(self,
riter:int=10000, # the number of random initial configurations to consider
giter:int=1000, # the number of gradient descent iterations to consider
gfactor:int=1e-4,# the factor for the gradient descent
biter:int=100 # the number ... |
def cal_monday(self, day_num):
r"""Shift the day number if week should start on Monday
Shift the day number if we're doing cal_monday,
or cal_weekend is false, since that also means
we're starting on day 1
Parameters
----------
day_num : int
Returns
... | This function processes 'calw', 'calm', or 'cal5w' commands to generate calendar event data by calculating start/end dates for weeks/months, retrieving events within that range, and passing them to GraphEvents for visualization. It handles date parsing, adjusts for Monday-based weeks/months, and manages edge cases like... | def CalQuery(self, cmd, startText='', count=1):
r"""Process calw and calm commands by calling GraphEvents
Parameters
----------
cmd : string (calw or calm)
startText : string (parsed to get start date)
count : number of weeks or months
"""
if not startTex... |
def search_for_events(self, start, end, pattern, field='summary',
ev_type=ALL_EVENTS):
r"""Retrieve events matching (text and/or date based) search
Parameters
----------
start : starting date (defaults to None)
end : ending date (defaults to None)
... | This code deletes calendar events matching specified criteria (search text, date range, field) after user confirmation. It handles recurring events with warnings, allows batch deletion or individual prompts, and ensures read-only calendars throw errors. The function iterates through found events, confirms deletion per ... | def delete(self, search_text='', start=None, end=None,
field='summary'):
r"""Delete matching events from calendar after prompt
Parameters
----------
search_text : string
start : datetime
end : datetime
field : string (field within event to be searc... |
def search_for_events(self, start, end, pattern, field='summary',
ev_type=ALL_EVENTS):
r"""Retrieve events matching (text and/or date based) search
Parameters
----------
start : starting date (defaults to None)
end : ending date (defaults to None)
... | The code edits calendar events based on search criteria (text, date range, field), handling both single and multiple edits. It checks for read-only status, processes recurring/non-recurring events, and prompts user confirmation for bulk edits. A warning is issued when modifying recurring events, which affects all insta... | def edit(self, search_text='', start=None, end=None,
field='summary'):
r"""Edit matching events
Parameters
----------
search_text : string
start : datetime
end : datetime
field : string (field within event to be searched)
"""
if self.... |
def calculate_recall_success_sequences(manager, T_recall, T_cue, n, sequences):
successes = []
total_sequences = len(sequences)
for n_recall in range(total_sequences):
sequence_to_recall = sequences[n_recall]
I_cue = sequence_to_recall[0]
success = calculate_recall_success(manager, ... | The main task of the code is to calculate time-related metrics for sequence recall, including total time, mean, and standard deviation of timing intervals, along with recall success. It checks if the first sequence is a subsequence of generated timings, computes statistics for valid cases, and returns these values alon... | def calculate_recall_time_quantities(manager, T_recall, T_cue, n, sequences):
# If the manager does not have the patterns yet, get them from the sequences
if not manager.stored_patterns_indexes: # This test for empty list
aux = [element for sequence in sequences for element in sequence]
manage... |
def read_file(file):
all_entries = {0: {'CVE': "", 'Date': "",'Description': [], 'Description-Tokenized' : [],
'Month-String':"",'Month-Int': 0,"Year":"","Year-Int":0,"Cluster": 0,
"Time Start": 0, "Time End": 0}}
untokenized_text = list()
start_index = 0
year... | The code processes a text file by building a doc2vec model to generate document vectors, computes cosine similarity between vectors, constructs a network graph from the similarity matrix, and returns an igraph object representing the network structure, using entries from the input file for node labeling. | def main(file):
file_info = read_file(file)
entries = file_info[0]
text = file_info[1]
# build a doc2vec model
read_corpus(text,tokens_only=False)
model = build_doc2vec(text)
tokenized = tokenize(text)
vectors = compute_vectors(tokenized,model)
cos_matrix = create_cos_matri... |
def play_sfx(file_name):
pygame.mixer.Sound.play(file_name)
def boundary(self):
if (self.rect.right > WIDTH - 50):
self.rect.x = WIDTH - 170
if (self.rect.left < 50):
self.rect.x = 50
def movement(self):
keys = pygame.key.get_pressed()
if (keys[pygame.K_LEFT] ... | The code's main task is to update the ship's state: if hidden for over 1500ms, it reappears at the screen's bottom center with a heal sound, then enforces boundaries and processes movement. | def update(self):
if self.ship_hidden and pygame.time.get_ticks() - self.ship_hide_timer > 1500:
play_sfx(heal)
self.ship_hidden = False
self.rect.centerx = WIDTH/2
self.rect.y = HEIGHT - 150
self.boundary()
self.movement() |
def default(val, d):
return val if exists(val) else d
def kernel_and_same_pad(*kernel_size):
paddings = tuple(map(lambda k: k // 2, kernel_size))
return dict(kernel_size=kernel_size, padding=paddings)
def cast_tuple(val, length=None):
if isinstance(val, list):
val = tuple(val)
output = val ... | This code defines a U-Net-based neural network architecture with customizable depth, attention mechanisms, and block types (ResNet/ConvNext). It initializes encoder (downsampling), decoder (upsampling), and middle blocks, incorporating skip connections, nested UNet structures, and feature consolidation. The model proce... | def __init__(
self,
dim,
init_dim=None,
out_dim=None,
frame_kernel_size=1,
dim_mults=(1, 2, 4, 8),
num_blocks_per_stage=(2, 2, 2, 2),
num_self_attn_per_stage=(0, 0, 0, 1),
nested_unet_depths=(0, 0, 0, 0),
nested_unet_dim=32,
channel... |
def find_matches(inp_img1,inp_img2):
sift = cv2.xfeatures2d.SIFT_create()
##points and descriptors for both images
insPts1, despImg1 = sift.detectAndCompute(inp_img1, None)
insPts2, despImg2 = sift.detectAndCompute(inp_img2, None)
bfmatcher = cv2.BFMatcher(crossCheck=True)
mts = sorted(bfmatcher.match(despImg... | The code performs RANSAC to estimate homography for image stitching between two rain images. It reads images, finds matches, filters inliers, draws matched points, and saves the result. It then stitches the images using the homography matrix, saving the output. If stitching fails, it handles errors. | def rainerRansac(inlierThresh, iterations):
image1, image2 = cv2.imread('given_images/Rainier1.png'), cv2.imread('given_images/Rainier2.png')
mts, insPts1, insPts2 = find_matches(image1, image2)
inliers_mts, hom, hom_inverse = RANSAC (mts , iterations, inlierThresh, insPts1, insPts2)
if inliers_mts is None:
print... |
def rainerRansac(inlierThresh, iterations):
image1, image2 = cv2.imread('given_images/Rainier1.png'), cv2.imread('given_images/Rainier2.png')
mts, insPts1, insPts2 = find_matches(image1, image2)
inliers_mts, hom, hom_inverse = RANSAC (mts , iterations, inlierThresh, insPts1, insPts2)
if inliers_mts is None:
print... | The code generates a panoramic image by stitching multiple input images using feature matching and RANSAC for robust homography estimation. It processes pairs of images, filters inliers, applies transformations, and combines them sequentially into a final panorama saved as 'panoroma.png', displaying the result with adj... | def start():
inlierThresh = 5
iterations = 1000
a2start()
print("\n****STEP3 and STEP4****")
rainerRansac(inlierThresh, iterations)
##Rainer Images
inp_img = ['given_images/Rainier1.png', 'given_images/Rainier2.png', 'given_images/Rainier3.png', 'given_images/Rainier4.png', 'given_images/Rainier5.png'... |
def is_row_full(self, row: int) -> bool:
for x in range(self.width):
if not self.grid[row][x]:
return False
return True
def remove_row(self, row: int):
while row >= 0:
for x in range(self.width):
self.grid[row][x] = None
if ... | This function identifies and removes full rows from the bottom up. It tracks consecutive full rows (lines_combo) and triggers the apply_lines_cleared method when a non-full row is encountered, resetting the counter. This is typical in games like Tetris for row-clear mechanics and scoring. | def break_full_rows(self):
y = self.height - 1
# go up the rows!
lines_combo = 0
while y >= 0:
if self.is_row_full(y):
self.remove_row(y)
lines_combo += 1
else:
y -= 1
if lines_combo > 0:
... |
def skip_game_tick(self):
self.last_game_tick_ms = ms_now()
def does_current_tetromin_collide(self) -> bool:
tetro, tx, ty = self.unpack_current_tetromin()
tetro_grid = tetro.current_grid()
for y in range(tetro.height()):
for x in range(tetro.width()):
gx = t... | The function moves the current tetromino down, checks for collisions, and handles collision logic by either dropping the tetromino into the grid, triggering the next piece, or reversing the move. It also plays movement and collision sounds conditionally. | def tetromin_down(self, process_logic_on_collision=True, ignore_move_sound=False):
self.skip_game_tick()
self.current_tetromin['y'] += 1
if not ignore_move_sound:
sound_move.play()
if collides := self.does_current_tetromin_collide():
sound_harddrop.play()
... |
def updateIndex(self):
self.__index=[]
self.__type={}
oid = (mibs.oid['ifIndex'],)
SnmpObj = self.__snmpIf.getNext( *oid)
index=list(SnmpObj.values())
oid = (mibs.oid['ifType'],)
SnmpObj = self.__snmpIf.getNext( *oid)
for i in ind... | The main task of the code is to update multiple attributes of an object by calling a series of methods, including index, channel ID, frequency, signal-to-noise ratio, power, operational status, and codeword statistics, ensuring the object's state reflects the latest data. | def update(self):
self.updateIndex()
self.updateChId()
self.updateChFreq()
self.updateDownSnr()
self.updateDownPower()
self.updateOperStatus()
self.updateCorrCodewords()
self.updateUncorrCodewords()
self.updateUnerrCodewo... |
def update(self):
self.updateIndex()
self.updateChId()
self.updateChFreq()
self.updateDownSnr()
self.updateDownPower()
self.updateOperStatus()
self.updateCorrCodewords()
self.updateUncorrCodewords()
self.updateUnerrCodewo... | This code initializes a class to manage Docsis interface data via SNMP, storing metrics like SNR, codewords, channel IDs, and operational status in dictionaries. It retrieves and updates these values using methods like `update()`, `__updateMac()`, and `updatePartialSrv()`, enabling access to network interface informati... | def __init__(self,snmpIf):
self.__snmpIf=snmpIf #Passing snmpif to access Docsis Interface
self.__macIfIndex=None
self.__index=[] #DocsisIf OID Index
self.__type={} #DocsusIf type: UP/DOWN
self.__downSnr={} #SNR values for all DownDocsIf
sel... |
def validate(size, cliques):
"""
Validate the integrity of the input as a kenken board
* For each of the cliques:
* Remove duplicate members of the clique at hand
* Check whether the specified operator is acceptable or not
* Check if any of the members of the clique are out of boun... | This code initializes a Constraint Satisfaction Problem (CSP) by setting up variables, domains, and neighbor relationships from given cliques. It validates input parameters, constructs problem structure, and stores metadata for constraints and display formatting. The CSP is initialized with custom constraints, and attr... | def __init__(self, size, cliques):
validate(size, cliques)
variables = [members for members, _, _ in cliques]
domains = gdomains(size, cliques)
neighbors = gneighbors(cliques)
csp.CSP.__init__(self, variables, domains, neighbors, self.constraint)
self.size = size
... |
def get_possible_words(self):
if len(self.effective_word_list) <= 0:
self.effective_word_list = self.word_list
all_excluded_words = list(set([attempt[0] for attempt in self.tries] + self.excluded_words))
first_level_filter = [word for word in self.effective_word_list if self.is_in_wo... | The function generates and returns a sorted list of suggested words by evaluating high-probability letters, prioritizing combinations that match the unknown letter count, and falling back to a sorted list of all possible words if no narrowing is possible. | def get_suggested_words(self):
all_possible_words = self.get_possible_words()
if len(all_possible_words) <= 0:
return []
unknown_letter_count = self.word_length - len(self.included_letters)
suggested_letters_with_prob = self.get_suggested_letters_by_freq(all_possible_words)
... |
def load_image(file_name):
img = cv2.imread(file_name, cv2.IMREAD_GRAYSCALE)
if img.shape[1] > 2000:
scale = 2000 / img.shape[0]
img = cv2.resize(img, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR)
elif img.shape[0] > 2000:
scale = 2000 / img.shape[1]
img = cv2.... | The main task of the code is to perform OCR on an image using two methods—DFT and SVM—while comparing their accuracy against a reference text. It preprocesses the image based on command-line flags, loads necessary models/data, extracts text via both OCR techniques, and evaluates results using Levenshtein distance if a ... | def main():
framed = '--no-frame' not in sys.argv
if not framed:
del sys.argv[sys.argv.index('--no-frame')]
img = load_image(sys.argv[1])
img = preprocess(img, framed)
alphabet = load_dft_data()
classifier = load_svm_data()
text_dft = ocr(img, img_to_text_dft, alphabet=alphabet)
... |
def printBoard(board):
ind = 0
for letter in board.lb:
print("%c " % letter.char, end="")
if ind % 4 == 3:
# on right side, print new line
print("")
ind += 1
print("")
def findValidWords(board, mode):
for letter in board.lb:
letter.markVisited()
... | The code collects and processes a list of English words, limiting their maximum length, then identifies valid words from a 4x4 letter board by checking word prefixes and generating possible combinations. It sorts and outputs valid words in descending order, using a custom comparison function. | def collect_info():
# initial setup
global MAX_LENGTH
print("\nNote: This code was designed for the 4x4 (default) board size.")
maxLen = input(
"\nDefault max word length is 10. Note this allocates about\n"
+ "16MB of space for word sets. If you wish to change it, enter\n"
+ "the... |
def printModeInfo():
print(("-" * 60 + "\n") * 2 + "There are two available display modes:\n")
# list mode
print("List Mode is one large list, where each word has its own row:\n")
print(
" X | Word \t| Starting Position on Board\n"
+ "----------------------------------------------"... | The main task of the code is to process a word list, accept a 4x4 board input, and find all valid words that can be formed using the board's letters. It allows users to customize the maximum word length (default 10) and choose between list or diagram output modes. The code reads words from a file, stores them in sets f... | def main():
# initial setup
global MAX_LENGTH
print("\nNote: This code was designed for the 4x4 (default) board size.")
maxLen = input(
"\nDefault max word length is 10. Note this allocates about\n"
+ "16MB of space for word sets. If you wish to change it, enter\n"
+ "the desired... |
def anti_traps_start(self):
if self.center_pos[0] in self.available_positions:
self.figure_maker(self.center_pos)
else:
self.figure_maker(self.available_corners)
def easy(self):
if self.available_positions:
self.figure_maker(self.available_positions)
def hard(... | The 'medium' method selects between different strategies based on game state and randomness: it uses 'anti_traps_start' or 'easy' for initial moves, and 'hard' or 'easy' for later moves, with probabilities determined by random choices and the count of used positions. | def medium(self):
if self.available_positions:
random_choice = random.randint(0, 8)
# First moves
if len(self.used_positions) < 2:
if random_choice <= 5:
self.anti_traps_start()
else:
self.easy()
... |
def _read_sentences_by_id(self, img_id):
sentence_file = self.sentence_dir / '{}.txt'.format(img_id)
return get_sentence_data(sentence_file)
def get_verb_idx(self, sentence: str, with_frames:bool=False):
# spacy_verbs = self.get_spacy_verbs(sentence)
# print(spacy_verbs)
verbs ... | The code processes sentences associated with an image ID by identifying verbs and their corresponding semantic frames. It extracts frame elements, structures them into JSON format, and saves the output. The main task is to analyze sentences, detect frame triggers, and organize frame details like verbs and elements for ... | def export_sentence_frames(self, img_id:str):
sentences = self._read_sentences_by_id(img_id)
output = []
for s in sentences:
base_sentence, _ = self.frame_parser._identify_triggers(s['sentence'])
verb_idx, verbs = self.get_verb_idx(base_sentence, with_frames=True)
... |
def generalize_keys(self, key:str):
if 'location' in key:
key = 'location'
return key
def select_single_phrase(self, phrase:str, phrases:List):
phrase_list = self.extract_phrases(phrase, phrases)
if len(phrase_list) > 1:
selected = self.detect_phrase(phrase, phras... | The main task of the code is to process and transform frames from input data by extracting and modifying elements based on associated phrases. It filters frames with single elements, generalizes keys, selects relevant phrases, and structures results into a list of processed entries containing sentences and transformed ... | def get_process_frames(self):
processed_entries = []
for s_idx, s in enumerate(self.frames):
current = self.sentences[s_idx]
phrases = current['phrases']
modifiled_frames = []
for item in s['frames']:
mod = {
'frame': it... |
def get_bed_snap(self,
timestep=None, idx=None,
include_only=None,
absolute_coords=True,
array_form=False) -> dict:
"""
Method to get the state of the bed at the specified timestep.
"""
if include_only i... | The main task of the code is to process and aggregate data from multiple timesteps into a single output structure. It iterates through each timestep, adds entries to the output array using `__add_entry_t`, tracks keys that couldn't be added, measures execution time, and returns the final aggregated output along with di... | def read_timesteps_single(self):
out_single = self.get_bed_snap(array_form=True)
keys_not_added_single = []
timesteps = self.get_timesteps()
print("Start Single")
start_single = perf_counter()
for t, v in timesteps.items():
out_single, keys_not_added_single =... |
def __check_square(self) -> None:
if self.row != self.column:
raise NotSquareMatrixError(
f"Square matrix must have equal number of rows and columns. (row = {self.row}, column = {self.column})")
def copy_values(self) -> list[list[Union[int, Fraction]]]:
"""Return a copy of 2D... | This method calculates the determinant of a square matrix using cofactor expansion along the first row. It checks if the matrix is square, handles the 1x1 case directly, and recursively computes the determinant by summing the products of elements in the first row with their corresponding cofactors. | def determinant(self) -> Union[int, Fraction]:
"""A method to find the determinant of a square matrix by cofactor method.
Returns:
Determinant of the matrix
"""
self.__check_square()
if self.row == 1:
return self.values[0][0]
else:
det... |
def rref(self) -> str:
"""
ROW OPERATION: Reduced Row Echelon Form
Algorithm for rref:
1) get matrix in REF form (using self.ref() method)
2) Determine all the leading ones in Ref
3) determine the rightmost column containing a leading one (pivot)
4) erase all no... | The `ro_string` method processes an input string to execute elementary row operations on a matrix. It identifies commands like row swaps, scalar multiplication, row addition, REF, or RREF, normalizes the string, and applies the corresponding operation. Fractions are supported for scalars. The matrix is modified in-plac... | def ro_string(self, input_string: str) -> str:
"""
ROW OPERATION: Elementary Row Operation via string command:
This method accepts a string and processes it to one of the elementary row operations.
There are five possible operations that can be invoked by this method:
1) Rm,n (... |
def __check_square(self) -> None:
if self.row != self.column:
raise NotSquareMatrixError(
f"Square matrix must have equal number of rows and columns. (row = {self.row}, column = {self.column})")
def determinant(self) -> Union[int, Fraction]:
"""A method to find the determinan... | The code computes the inverse of a square matrix by calculating its determinant, adjugate matrix, and scaling the adjugate by the reciprocal of the determinant. If the determinant is zero, it raises an InverseSingularError to handle non-invertible (singular) matrices. | def inverse(self) -> None:
self.__check_square()
try:
det = self.determinant()
self.adjugate_matrix()
self.multiply_scalar(1 / det)
except ZeroDivisionError:
raise InverseSingularError("Matrix is a singular matrix. (Det == 0)") |
def synthesis(A: dict[int, int], B: dict[int, int]) -> list[dict]:
A_element, A_charge = process_molecule(A)
B_element, B_charge = process_molecule(B)
# 1 should be + and the other is -
if (A_charge < 0 and B_charge < 0) or (A_charge > 0 and B_charge > 0):
return "Invalid reagents"
positiv... | The code defines a function `run_reaction` that dispatches chemical reaction processing based on the input `reaction_type`. It routes calls to specialized functions (`synthesis`, `redox`, `metathesis`, `combustion`) for specific reaction types or returns an error for "UNKNOWN". The function accepts two dictionaries, `A... | def run_reaction(reaction_type: str, A: dict[int, int], B: dict[int, int]) -> Union[list[dict], str]:
if reaction_type == "UNKNOWN":
return "Unknown reaction type"
elif reaction_type == "SYNTHESIS":
return synthesis(A, B)
elif reaction_type == "REDOX":
return redox(A, B)
elif ... |
def node_of_depth_first_index(self, x):
return self.node_of_np_node(self.depth_first_np_nodes[x])
def node_of_np_node(self, node):
for i in self.nodes:
if np.array_equal(self.np_rep_of_nodes[i], node):
return i
def create_next_node_table(self):
play_table = np.full((s... | This code initializes a game tree structure, converting it into numpy arrays for efficient processing. It stores nodes in both breadth-first (BF) and depth-first (DF) orders, identifies decision nodes, and maps node relationships. It constructs detailed metadata for each node (actions, children, terminal status) and cr... | def __init__(self, root, max_number_of_bets):
self.root = root
self.max_number_of_bets = max_number_of_bets
# numpy.ndarray: List containing nodes of Tree in BF order
self.np_rep_of_nodes = np.array(
numpy_representation_of_nodes.create_breadth_first_tree(self.root, self.max... |
def _topsort(functions):
lookup = {f.name: f for f in functions}
# strip duplicates
return list(dict.fromkeys(_topsort_helper(functions, lookup)))
def parse_external_interfaces(external_interfaces, global_ctx):
for _interfacename in global_ctx._contracts:
_interface_defs = global_ctx._contracts[... | The function generates intermediate representation (IR) for a module's functions, handling dependencies by topologically sorting functions. It creates function signatures, separates runtime and initialization functions, generates IR for runtime functions, and constructs deploy IR with initialization logic. The output i... | def generate_ir_for_module(global_ctx: GlobalContext) -> Tuple[IRnode, IRnode, FunctionSignatures]:
# order functions so that each function comes after all of its callees
function_defs = _topsort(global_ctx._function_defs)
# FunctionSignatures for all interfaces defined in this module
all_sigs: Dict[st... |
def get_device_create_doc(self, carrier, detail, now):
doc = {
'accountId': carrier['accountId'],
'platform': 'jasper',
'carrierId': carrier['id'],
'carrierName': carrier['name'],
'configUpdated': now,
'created': now,
'createdBy... | The main task of the code is to process device details from a message by checking if devices exist via ICCID. If not found, it creates new devices, assigns IDs, and logs audit/usage entries. For existing devices, it prints their ICCID. The function updates device records based on carrier data, handling both creation an... | def update_devices_from_message(self, carrier, now, details):
for detail in details:
device = self.device_repo.get_device_by_iccid(carrier_id=carrier['id'], iccid=detail['iccid'])
if not device:
print('NOT INCLUDED')
device = self.get_devic... |
def get_carrier_device_queue(self, carrier_id):
try:
queue_name = self.get_carrier_device_queue_name(carrier_id)
service_bus_client = self.ServiceBusClient.from_connection_string(self.config.service_bus_connection_string)
queue_client = service_bus_client.get_queue(queue_name... | The main task of the code is to process a carrier's message queue by fetching and handling messages from a queue client. It retrieves the current time, initializes the queue client, sets API credentials, and iteratively fetches messages in batches. Each message is processed via `process_queue_message`, while errors are... | def process_carrier_queue(self, carrier):
try:
now = datetime.now(timezone.utc)
# logger.info(f"jasper worker process_carrier_queue - name: {carrier['name']} id: {carrier['id']} now: {now}")
queue_client = self.get_carrier_device_queue(carrier['id'])
if not queue... |
def move(self):
# if human is alive and hasnt found goal
if not self.dead and not self.reached_goal:
# increment next step counter
self.next_step_counter += 1
# check if brain has any directions left
if len(self.brain.directions) > self.brain.step:
... | This code updates a human agent's state by moving and rendering it on the screen. It checks if the human has fallen off the island (triggering death) or found the bitcoin (marking goal achievement). If the bitcoin is found, it records the end time, resets image counters, and updates visual state. | def update(self, win, width, island_mask, bitcoin):
# move human
self.move()
# show human
self.show(win)
# if human is alive
if not self.dead:
# check if human has gone off island
if not self.is_on_island(island_mask):
# set fell_of... |
def init_factorization(self, seed):
np.random.seed(seed)
return np.random.rand(self.n,self.k), np.random.rand(self.k,self.m)
def _rounding(X, k = 0.5, l = 1.e+20):
X = _prox(X, k, l)
return np.round(np.clip(X, 0, 1))
def _print_loss(A, U, V):
print(f'recall : {_recall(A, U, V)}, similarity :... | This __init__ method initializes a matrix factorization model by copying input matrices, setting regularization parameters, and initializing factor matrices U and V with random seeds. It configures optimization settings like iterations, tolerance, and batch size, applies rounding to initial factors, and computes the in... | def __init__ ( self,
org_A,
A,
ncomponents,
l1reg,
l2reg,
c, # = t -> c^t
maxiter,
tolerance,
random_seed = 19,
... |
def _factorize_palm(elbmf):
U = elbmf.U
V = elbmf.V
l2reg_init = elbmf.l2reg
l1reg = elbmf.l1reg
c = elbmf.c
A = elbmf.A
tol = elbmf.tolerance
ell0 = sys.float_info.max
ell = 0
for iter in range(elbmf.maxiter):
l2reg = l2reg_init * pow(c, iter)
U = _reducemf_impl(... | The code's main task is to factorize matrices U and V using either _factorize_palm, _factorize_ipalm (with beta parameter), or _batched_factorize_ipalm depending on batchsize and beta, round the results, and print the loss. | def factorize(self):
if(self.batchsize >= len(self.A)):
if(self.beta == 0):
self.U, self.V = _factorize_palm(self)
else:
self.U, self.V = _factorize_ipalm(self, self.beta)
else:
self.U, self.V = _batched_factorize_ipalm(self)
... |
def full():
for i in range(1,10):
if grid[i]==' ':
return False
return True
def winner(le,bo):
return ((bo[7] == le and bo[8] == le and bo[9] == le) or (bo[4] == le and bo[5] == le and bo[6] == le) or (bo[1] == le and bo[2] == le and bo[3] == le) or (bo[7] == le and bo[4] == le and bo[1]... | The code implements a tic-tac-toe game where the computer plays against a human player. The computer selects the best move iteratively, updates the grid, checks for victory or tie conditions, and announces the outcome. The loop continues until a win or tie occurs, with the computer's moves and player's turns alternatin... | def game():
while(not full() and not winner('X',grid) and not winner('O',grid)):
move=findbestmove()
grid[move]=d[0]
print("computer move")
printgrid()
if winner('O',grid):
print("you lost")
break
if full():
print("Tie")
... |
def validateSettings(self):
try:
# Validate Input Directories
if self.tableModel.getRowCount() == 0:
JOptionPane.showMessageDialog(self.frame, "No input directories have been added.", "Settings Error", JOptionPane.ERROR_MESSAGE)
return False
f... | This code handles GUI action events by stopping table editing, then executing commands like "Create Montage" (validation + confirmation), "Add" (directory addition), or "Remove" (directory deletion) based on the event's action command. | def actionPerformed(self, event):
if self.table.isEditing():
self.table.getCellEditor().stopCellEditing()
command = event.getActionCommand()
if command == "Create Montage":
if self.validateSettings():
self.showConfirmationDialog()
return
... |
def __start_ping_thread(self):
self.event = threading.Event()
self.end_ping_thread = False
self.ping_thread = threading.Thread(target=self.__ping_thread_target)
self.ping_thread.setDaemon(True)
self.ping_thread.start()
def __stop_ping_thread(self):
self.end_ping_thread = True
self.event.set()
self.ping_... | The main task of the code is to repeatedly initiate a ping thread, run it indefinitely, stop the thread, and resubscribe to a service or resource in an infinite loop. This cycle ensures continuous monitoring, maintenance, or reconnection to a system, likely for networked applications or real-time data processing. | def thread_target():
while True:
self.__start_ping_thread()
self.run_forever()
self.__stop_ping_thread()
self.__resubscribe() |
def _create_subhand(self, bet=0.0, card=None): # bet = 0.0 for now
hand = dict({'cards': ([card] if card else []), 'done': False, 'bet': bet, 'paid': False})
self.subhands['hands'].insert(self.current_hand_number + 1, hand)
def _initialize_subhand(self, hand_number):
cards_to_draw = 2 - len(sel... | The main task of the code is to initialize the dealer's main hand in a card game. It creates a subhand with an initial bet, initializes the current hand number, and draws the first card for the dealer's hand. This sets up the dealer's starting state before gameplay begins. | def _initialize_main_hand(self):
self._create_subhand(bet=self.initial_bet)
self._initialize_subhand(self.current_hand_number)
self.dealer_hand = [self._draw()] |
def _get_action_set(self):
ans = []
if self.finished:
return ans
if self.dealer_hand[0][0] == 'A' and len(self.action_history) == 0:
ans.append(INSURANCE_YES)
ans.append(INSURANCE_NO)
return ans
if self._is_natural_bj():
# shou... | This code processes a player's action in a card game (likely Blackjack), updating game state, handling bets, and determining outcomes. It validates actions, adjusts winnings for insurance/double, manages hand progression, and marks hands as paid/done. The function returns True if the action is valid and processed, else... | def act(self, action, additional_bet_amount=0.0):
if not (len(action) == 1 and action in self._get_action_set()):
return False
if action == INSURANCE_NO:
self._check_and_handle_dealer_bj()
elif action == INSURANCE_YES:
# check if payment for additional_bet_am... |
def _initialize_main_hand(self):
self._create_subhand(bet=self.initial_bet)
self._initialize_subhand(self.current_hand_number)
self.dealer_hand = [self._draw()]
def _check_and_handle_dealer_bj(self):
if self._check_dealer_bj():
self.finished = True
self.dealer_han... | This code handles the finalization of a Blackjack game state by checking for initial setup, resolving dealer actions, processing natural blackjacks, and calculating payouts when the game is finished. It updates game outcomes, marks hands as resolved, and ensures proper dealer hand resolution and payout logic based on p... | def save(self, *args, **kwargs):
if not self.subhands: # first time setting up hand
self.seed = str(int(str(envvar('SEED_PREFIX')), 16) + int(str(self.transaction_hash), 16))
self.cards = shuffle(DEFAULT_DECK, int(self.seed))
self.subhands = dict({'hands': []})
s... |
def isEmpty( stack ):
return len(stack) == 0
def pop( stack ):
# If stack is empty
# then error
if(isEmpty( stack )):
print("Stack Underflow ")
exit(1)
return stack.pop()
def insertAtBottom(stack, item):
if isEmpty(stack):
push(stack, item)
else:
temp = po... | The code recursively reverses the order of elements in a stack by repeatedly popping the top element, recursively processing the remaining stack, and inserting the popped element at the bottom, effectively inverting the original order. | def reverse(stack):
if not isEmpty(stack):
temp = pop(stack)
reverse(stack)
insertAtBottom(stack, temp) |
def contrast_train(self, batch, keep_node=None, mask_edge=None):
if keep_node is None and mask_edge is None:
aug = permute_edges(deepcopy(batch).cpu()).to(self.device)
z_aug, _ = self.get_features(aug.batch, aug.x, aug.edge_index, aug.edge_attr, None, None)
x_aug = self.get_p... | The code performs a conditional forward pass: if progress is below a warm-up ratio, it executes contrastive training; otherwise, it generates node/edge masks, computes positive and negative scores via specialized methods, and returns their weighted difference (pos_score - 0.1*neg_score) for contrastive learning optimiz... | def forward(self, batch, progress):
if progress < self.warm_ratio:
return self.contrast_train(batch)
else:
keep_node_list, mask_edge_list = self.get_contrastive_cam(batch, self.inner_iter)
indicater = keep_node_list[-1]
mask_edge = mask_edge_list[-1]
... |
def get_total_available(self):
"""Gets the total amount of GPUs available after min free threshold."""
if (datetime.datetime.now() - self.last_polled).total_seconds() > 60:
self.poll_gpu_status()
total_available = 0
total_available_fp16 = 0
for host, config in self.ho... | The main task of the code is to distribute and manage jobs on available GPUs by prioritizing tasks, adjusting device IDs, adding host-specific commands, and spawning GPUWorker threads. It continuously monitors the job queue, polls GPU status, and ensures efficient resource allocation while handling idle periods and wor... | def run_jobs(self, cmds=[], host2cmd_adds={}):
gpus_available = self.get_total_available()
while self.queue.qsize() > 0:
workers = []
print('Total jobs left: {0}.'.format(self.queue.qsize()))
print('Calculating priority list...')
priority_list = self.get_... |
def player(board):
"""
Returns player who has the next turn on a board.
"""
numX = 0
numO = 0
global starter
for i in range(boardlen):
for j in range(boardlen):
if board[i][j] == X:
numX += 1
elif board[i][j] == O:
numO += 1
... | This function determines the optimal action for the current player using a minimax algorithm by recursively evaluating all possible moves, selecting the action that maximizes the player's utility (for X) or minimizes it (for O), and returns the best score for the current board state. | def utilityhelp(board):
"""
Returns the optimal action for the current player on the board.
"""
user = player(board)
v = -math.inf if user == X else math.inf
actionset = actions(board)
for (i,j) in actionset:
boardtemp = [row[:] for row in board]
boardtemp[i][j] = user
... |
def player(board):
"""
Returns player who has the next turn on a board.
"""
numX = 0
numO = 0
global starter
for i in range(boardlen):
for j in range(boardlen):
if board[i][j] == X:
numX += 1
elif board[i][j] == O:
numO += 1
... | The code implements the minimax algorithm to determine the optimal move for the current player on a tic-tac-toe board. It evaluates all possible actions, simulates each move by creating a board copy, and calculates the resulting utility (or a helper utility for non-terminal states). The algorithm selects the action max... | def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
user = player(board)
v = -math.inf if user == X else math.inf
actionset = actions(board)
if terminal(board):
return None
ansset = (-1,-1)
for (i,j) in actionset:
boardtemp = [r... |
def get_healthy_number(self):
return self.healthy_number
def set_healthy_letter(self, status):
self.healthy_letter = status
def get_alphabet_dni(self):
return self.dni[-1]
def check_valid_letter(self):
return (
self.get_healthy_number()
and self.get_alphabet_dni()... | The code checks if a letter is valid based on specific conditions: it must be uppercase, not a digit, and pass a validation check. If the preceding number is healthy, it sets and returns the validity status of the letter; otherwise, it returns False. | def check_letter(self):
if self.get_healthy_number():
self.set_healthy_letter(
self.get_alphabet_dni().isupper()
and not self.get_alphabet_dni().isdigit()
and self.check_valid_letter()
)
return self.get_healthy_letter()
... |
def _calc_all_weights(self):
# gmz calcs:
self.num_cmls = self.df_for_dist.shape[0]
# compute the number of virtual gauges for each cml
self.max_num_of_gauges = self.df_for_dist['num_of_gauges'].max()
self.use_gauges = np.zeros((self.num_cmls, self.max_num_of_gauges),
... | The code calculates rain rates at virtual gauges using CML data via iterative refinement, reusing precomputed weights if valid. It initializes gauge values, adjusts for ROI, and applies IDW interpolation to generate a rain map. The process iterates until convergence, updating gauge estimates and interpolating results o... | def __call__(self, df, quantization, interpolate=True,
ROI_for_interp=None):
''' Calculates the rain rate at every virtual gauge of every cml
and uses the results to create a rain map with IDW interpolation.
df is a pandas DataFrame that should include the following columns:
... |
def posWeights(alg, seqw=1, lbda=0, N_aa=20,
freq0=np.array([.073, .025, .050, .061, .042, .072, .023, .053,
.064, .089, .023, .043, .052, .040, .052, .073,
.056, .063, .013, .033]),
tolerance=1e-12):
'''
Compute single-... | The function `seqProj` computes three sequence projections using eigenvectors from a similarity matrix, applying SVD and ICA. It generates projections with no weights, sequence weights, and combined sequence-position weights. The output includes SVD results (`Useq`) and ICA-rotated versions (`Uica`), enabling dimension... | def seqProj(msa_num, seqw, kseq=15, kica=6):
'''
Compute three different projections of the sequences based on eigenvectors
of the sequence similarity matrix.
**Arguments**
- `msa_num` = sequence alignment (previously converted to numerical
representation using lett2num_)
- `s... |
def freq(alg, seqw=1, Naa=20, lbda=0, freq0=np.ones(20) / 21):
'''
Compute amino acid frequencies for a given alignment.
**Arguments**
:alg: a MxL sequence alignment (converted using lett2num_)
.. _lett2num: scaTools.html#scaTools.lett2num
**Keyword Arguments**
:seqw: a vector of se... | The function `scaMat` computes the Structural Covariance Analysis (SCA) matrix from a multiple sequence alignment (MSA). It calculates a positional correlation matrix (`Cp`) by projecting the MSA onto a reduced space using either Frobenius or spectral norm, derives a projected alignment (`tX`), and constructs a project... | def scaMat(alg, seqw=1, norm='frob', lbda=0, freq0=np.ones(20) / 21,):
'''
Computes the SCA matrix.
**Arguments**
:alg: A MxL multiple sequence alignment, converted to numeric
representation with lett2num_
**Keyword Arguments**
:seqw: A vector of sequence weights (defaul... |
def alg2bin(alg, N_aa=20):
'''
Translate an alignment of size M x L where the amino acids are represented
by numbers between 0 and N_aa (obtained using lett2num) to a sparse binary
array of size M x (N_aa x L).
**Example**::
Abin = alg2bin(alg, N_aa=20)
'''
[N_seq, N_pos] = alg.shap... | The function projects an alignment (msa_ann) onto the ICA components derived from another alignment's sequence space (msa_num, seqw). It computes sparse binary representations, applies SVD for dimensionality reduction, aligns components via sign normalization, and uses ICA rotation. The result is two projections (Ui1, ... | def projUica(msa_ann, msa_num, seqw, kica=6):
'''
Compute the projection of an alignment (msa_ann) on the kpos ICA components
of the sequence space of another (msa_num, seqw).This is useful to compare
the sequence space of one alignment to another.
**Example**::
Uica_ann, Uica = projUpica(ms... |
def seqWeights(alg, max_seqid=.8, gaps=1):
'''
Compute sequence weights for an alignment (format: list of sequences) where
the weight of a sequence is the inverse of the number of sequences in its
neighborhood, defined as the sequences with sequence similarity below
max_seqid. The sum of the weights... | This function selects a default reference sequence from an alignment by identifying the sequence whose mean pairwise identity to others is closest to the overall mean pairwise identity of the alignment. It reduces large alignments via random sampling, computes sequence similarities, calculates per-sequence mean identit... | def chooseRefSeq(alg):
'''
This function chooses a default reference sequence if none is given by
taking the sequence which has the mean pairwise sequence identity closest
to that of the entire alignment.
**Example**::
i_ref = chooseRefSeq(msa_num)
'''
if len(alg) > 1000:
se... |
def scaMat(alg, seqw=1, norm='frob', lbda=0, freq0=np.ones(20) / 21,):
'''
Computes the SCA matrix.
**Arguments**
:alg: A MxL multiple sequence alignment, converted to numeric
representation with lett2num_
**Keyword Arguments**
:seqw: A vector of sequence weights (defaul... | The function `projUpica` projects an alignment (`msa_ann`) onto the ICA components derived from the SCA matrix of another alignment (`msa_num, seqw`), enabling comparison of sequence spaces via positional correlations. It computes SCA matrices, extracts eigenvalues/vectors, applies ICA rotation, projects data, and norm... | def projUpica(msa_ann, msa_num, seqw, kpos):
'''
Compute the projection of an alignment (msa_ann) on the kpos ICA components
of the SCA matrix of another (msa_num, seqw). This is useful to compare the
sequence space (as projected by the positional correlations) of one
alignment to another.
**Ex... |
def freq(alg, seqw=1, Naa=20, lbda=0, freq0=np.ones(20) / 21):
'''
Compute amino acid frequencies for a given alignment.
**Arguments**
:alg: a MxL sequence alignment (converted using lett2num_)
.. _lett2num: scaTools.html#scaTools.lett2num
**Keyword Arguments**
:seqw: a vector of se... | The function randomizes a sequence alignment while preserving amino acid frequencies at each position, generating multiple trials. It computes the spectrum of the SCA matrix for each randomized alignment, returning eigenvectors (Vrand), eigenvalues (Lrand), and averaged SCA matrices (Crand). The process involves weight... | def randomize(msa_num, Ntrials, seqw=1, norm='frob', lbda=0, Naa=20, kmax=6,
tolerance=1e-15):
'''
Randomize the alignment while preserving the frequencies of amino acids at
each position and compute the resulting spectrum of the SCA matrix.
**Arguments**
:msa_num: a MxL sequence al... |
def check_keydown_events(event,game_settings,screen,ship,bullets):
'''respond to keypresses'''
# move the ship right and left
if event.key==pygame.K_RIGHT:
ship.moving_right=True
elif event.key==pygame.K_LEFT:
ship.moving_left=True
elif event.key==pygame.K_q:
sys.exit()
#... | This function handles keyboard and mouse events in a game. It processes quitting, key presses (calling `check_keydown_events`), key releases (calling `check_keyup_events`), and mouse clicks (triggering `check_play_button` with coordinates). It delegates actions to other functions to manage ship movement, bullets, game ... | def check_events(game_settings,screen,stats,sb,play_button,ship,aliens,bullets):
'''Follow keyboard & mouse events'''
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
elif event.type==pygame.KEYDOWN:
check_keydown_events(event,game_settings,screen,s... |
def check_fleet_edges(game_settings,aliens):
'''respond if alien reaches edge'''
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(game_settings,aliens)
break
def ship_hit(game_settings,screen,stats,sb,ship,aliens,bullets):
'''respond to ship being... | The function `update_aliens` updates alien positions, checks if they reach screen edges, detects collisions between the ship and aliens, and triggers responses for alien-bottom collisions or ship hits. It ensures aliens move, monitors threats, and initiates game state changes like ship destruction or alien defeat. | def update_aliens(game_settings,screen,stats,sb,ship,aliens,bullets):
'''checking to see if edge reached and Updating the aliens position on the screen'''
check_fleet_edges(game_settings,aliens)
aliens.update()
#look for alien-ship collision
if pygame.sprite.spritecollideany(ship,aliens):
sh... |
def get_status(self):
# idle
if self.acc.x == 0:
self.Idle = True
else:
self.Idle = False
# direction
if not self.iframe:
if self.acc.x >= 0.3 or self.vel.x >= 1:
self.FaceLeft = False
if self.acc.x <= -0.3 or self.v... | This code updates a game object's physics and collision handling by calculating acceleration, velocity, and position changes, applying friction, checking wall collisions, adjusting hitboxes, handling sliding, teleportation, power-ups, and saving the state. | def update(self):
self.get_status()
self.get_keys()
self.draw()
self.get_hit()
#
self.acc.x += self.vel.x * Player_friction
#
self.vel.x += self.acc.x
if abs(self.vel.x) < 0.1:
self.vel.x = 0
self.x += self.vel.x + 0.5 * self.ac... |
def get_zillow_data():
"""Seeks to read the cached zillow.csv first """
filename = "zillow.csv"
if os.path.isfile(filename):
return pd.read_csv(filename)
else:
return get_new_zillow_data()
def handle_nulls(df):
# We keep 99.41% of the data after dropping nulls
# round(df.dro... | The main task of the code is to clean and prepare Zillow housing data by handling nulls, optimizing data types, addressing outliers, creating new features like cost_per_sqft and sqft_room_ratio, dummy encoding the 'fips' column, renaming columns for clarity, and returning a structured DataFrame ready for analysis. | def wrangle_zillow():
"""
Acquires Zillow data
Handles nulls
optimizes or fixes data types
handles outliers w/ manual logic
returns a clean dataframe
"""
df = get_zillow_data()
df = handle_nulls(df)
df = optimize_types(df)
df = handle_outliers(df)
#new column total bi... |
def run_destination_sample( # KEEP
state: workflow.State,
spec_segment_name,
tours,
persons_merged,
model_settings,
network_los,
destination_size_terms,
estimator,
chunk_size,
trace_label,
known_time_periods=None,
):
# FIXME - MEMORY HACK - only include columns actually ... | The function `run_tour_destination` processes tour destination choices for different segments by sampling, calculating logsums, and simulating choices. It filters tour records by segment, computes destination size terms, runs destination sampling and logsum calculations, and aggregates results into choice and sample da... | def run_tour_destination(
state: workflow.State,
tours: pd.DataFrame,
persons_merged: pd.DataFrame,
want_logsums,
want_sample_table,
model_settings,
network_los,
estimator,
chunk_size,
trace_hh_id,
trace_label,
in_period_col=None,
out_period_col=None,
duration_col... |
def covid_stats():
'''Calls data from Public Health Service, uses the uk_covid19 module to do this.
Makes a loud statement report right before finishing.'''
area_filter = [
'areaType=nation',
'areaName=England'
]
cases_and_deaths = {
"date": "date",
"areaName": "areaN... | The main task of the code is to check if scheduled alarms match the current time, trigger alerts, and provide user-requested information (e.g., news or weather). It appends new alarms, compares them with the current time, executes corresponding actions like fetching COVID stats, announcing news titles, or handling weat... | def alarm_checker():
'''Checkes the scheduled alarms if it is time or not,
after that complies the user's requests
(weather or news information) '''
now = datetime.datetime.now()
current_time = now.strftime("%Y-%m-%d %H:%M:00")
# Enter the time(Hours and minute)
setted_alarms.append(reque... |
def initializeNN(self, NNX, NNY):
self.NNX = NNX
self.NNY = NNY
self.initalizeWeight(NNX)
for i in range(self.iter):
self.forward(self.NNX)
self.cost = 1 / self.v_n.shape[0] * np.sum(np.square(self.v_n - self.NNY))
if np.isnan(self.cost):
... | The function performs k-fold cross-validation on a neural network. It shuffles input/output data, splits them into k subsets, iterates through each subset as a test set while training on the remaining data, evaluates model performance using R-squared score, and returns the average score across all folds. | def trainNN(self,NNX,NNY, k=15):
np.random.shuffle(NNX)
np.random.shuffle(NNY)
X = np.array_split(NNX,k)
Y = np.array_split(NNY,k)
currentScoreList = []
for i in range(k):
if i == 0:
trainX = np.concatenate(X[i+1:])
trainY = n... |
def norm_wgts(wgts):
wgts_norm = wgts/np.linalg.norm(wgts, ord=2) # (wgts/np.sum(wgts, axis=-1, keepdims=True)).tolist()
return wgts_norm
def get_wgts_cat(wgts, ncats):
ncats_neg = min(int((ncats-1)/2), len([w for w in wgts if w<0]))
ncats_pos = ncats - ncats_neg
min_wgts = np.min(wgts, axis=-1, ke... | This function generates color gradients based on weighted token categories, applying them to tokens. It normalizes weights, categorizes them, creates a gradient from start to finish hex colors (or split at a middle color), then maps each token to a color from the gradient based on its weight category. | def color(toks, wgts, start_hex="#ffffff", finish_hex="#037ef3", middle_hex=None, n=20): # # ff4c4c
wgts = norm_wgts(wgts)
wgts = get_wgts_cat(wgts, ncats=n)
if not middle_hex:
color_grad = linear_gradient(start_hex=start_hex, finish_hex=finish_hex, n=n)['hex']
else:
n_pos = int(n/2)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.