dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def print_log_title(title):
rprint("[blue b]" + ">> " * 5 + title + "<< " * 5)
def display_job_run(job_name, job_run_at, tasks, job_graph, method="flat"):
job_run_at = timestamp_to_datetime(job_run_at)
tree = Tree(f"`{job_name}` at {job_run_at}")
root_task_names = [n for n, d in job_graph.in_degree() i... | This code retrieves and displays logs for a specified job, showing the latest runs in a structured format. It queries a storage system for task records, processes them into a DataFrame, filters the most recent entries, and visualizes the job's execution history using a specified style (e.g., tree). | def log_job(self, job_name, latest_n=3, style="tree"):
pattern = ":".join([PREFIX, job_name]) + ":[1-9]*" # skip meta
task_keys = self._store.keys(pattern=pattern)
job_meta = self._store.get(":".join([PREFIX, job_name, "META"]))
if not job_meta:
rprint(f"[red b]\[Pydag]There... |
def determine_null_cells( self,
table_counts ):
print()
columns_range = range( table_counts.get( 'columns_count' ) )
rows_range = range( self.rows_count )
text = 'Null'
# list for storing count of cells about to be NULL in every column
... | The main task of the code is to prepare and generate synthetic database data by calculating column counts, identifying null/empty cells, creating an XML-based name pool, and producing random data entries using these parameters. It structures data for database insertion, though table creation is currently commented out. | def main( self ):
columns_counts = {
'columns_count' : len( self.columns ),
'string_columns_count': len( self.xml_tags_to_database_columns )
}
null_cells = self.determine_null_cells( columns_counts )
empty_cells = self.__determine_empty_string_cells( column... |
def days_since_2000_jan0(y, m, d):
"Return the number of days since 2000 Jan 0."
return (367 * (y) - ((7 * ((y) + (((m) + 9) / 12))) / 4) + ((275 * (m)) / 9) + (d) - 730530)
def revolution(x):
"Reduce angle in degrees to between 0 and 360."
return (x - 360.0 * math.floor(x * INV360))
def GMST0(d):
"... | The function calculates sunrise and sunset times for a given date and location, using astronomical computations. It computes the Sun's position relative to the observer's coordinates, adjusts for altitude and upper limb visibility, and determines the diurnal arc. The result is a time interval [sunrise, sunset] in UT ho... | def sunriset(year, month, day, lon, lat, altit, upper_limb):
"Return the start and end times of the sun for the given date and location."
# Compute d of 12h local mean solar time
d = days_since_2000_jan0(year, month, day) + 0.5 - (lon / 360.0)
# Compute local sidereal time of this moment
sidtime = ... |
def sunRADec(d):
"Return the right ascension and declination of the Sun."
# Compute Sun's ecliptical coordinates
res = sunpos(d)
lon = res[0]
r = res[1]
# Compute ecliptic rectangular coordinates (z=0)
x = r * cosd(lon)
y = r * sind(lon)
# Compute obliquity of ecliptic (inclination... | The code calculates the solar zenith angle at a given date, time, and location by determining the Sun's declination, solar hour angle, and using trigonometric functions to compute the angle between the Sun and the zenith point. It incorporates sunrise/sunset times, latitude/longitude, and time shifts to derive the zeni... | def zenith(year, month, day, hour, minute, lon, lat, timeshiftHr, jDay):
"Return the zenith angle of the Sun for the given date and location."
rdat = []
rdat = sunRADec(jDay)
dec = rdat[1]
# Compute sine and cosine of Sun's declination
sin_sdecl = sind(dec)
cos_sdecl = cosd(dec)
# sin ... |
def get_latency_fwd_per_layer_attn(
self,
batch_size: int,
seq_len: int,
is_inference: bool = True,
activation_recomputation:
ActivationRecomputation = ActivationRecomputation.NONE,
) -> float:
"""Get the latency for the forward pass of the attention module in... | The function calculates the total latency for a transformer layer's forward pass, summing attention, MLP, layernorm, and tensor-parallel communication components, while handling DeepSpeed ZeRO constraints and overlapping communication with computation. It returns the total latency and a detailed breakdown of each compo... | def get_latency_fwd_per_layer(
self,
batch_size: int,
seq_len: int,
is_inference: bool = True,
activation_recomputation:
ActivationRecomputation = ActivationRecomputation.NONE,
layernorm_dtype_bytes: int = BYTES_FP32,
ds_zero: DSZeRO = DSZeRO.NONE,
) -... |
def get_num_params_total(self) -> int:
"""Get the total number of parameters in the model, including all the
transformer layers and the embedding layer.
Returns:
int: the total number of parameters in the model
"""
return (
self.model_config.num_layers * ... | The code initializes an LLMAnalysis object to configure and analyze large language model performance. It sets up model, GPU, and parallelism parameters, calculates memory and FLOPS efficiency metrics based on provided or default values, validates ranges, and computes total model parameters including MLP, embeddings, an... | def __init__(
self,
model_config: ModelConfig,
gpu_config: GPUConfig,
dtype_config: DtypeConfig = DtypeConfig(),
parallelism_config: ParallelismConfig = ParallelismConfig(),
achieved_tflops: float = None,
achieved_memory_bandwidth_GBs: float = None,
flops_... |
def get_latency_fwd_per_layer(
self,
batch_size: int,
seq_len: int,
is_inference: bool = True,
activation_recomputation:
ActivationRecomputation = ActivationRecomputation.NONE,
layernorm_dtype_bytes: int = BYTES_FP32,
ds_zero: DSZeRO = DSZeRO.NONE,
) -... | This function calculates the forward pass latency of a transformer model given batch size, sequence length, and configuration parameters. It computes total latency by summing per-layer (attention, MLP, layernorm, communication) latencies across all layers, input embedding, and output embedding/loss components. Returns ... | def get_latency_fwd(
self,
batch_size: int,
seq_len: int,
is_inference: bool = True,
activation_recomputation:
ActivationRecomputation = ActivationRecomputation.NONE,
layernorm_dtype_bytes: int = BYTES_FP32,
breakdown_prefix: str = "",
ds_zero: DSZ... |
def perform_scan():
try:
subnet = InputUtils.get_text_input('Enter subnet:',r'\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}\/\d{1,3}') # get valid subnet user input
print('Scanning...')
nmap.scan_command(subnet, arg='-sV -O') # perform nmap OS and service scan
print('Scanning Complete')
... | The main task of the code is to interact with the Metasploit Framework (MSF) by connecting to its database, scanning targets or reusing existing data, managing hosts/vulnerabilities, and exploiting systems via Meterpreter sessions or botnet-style control. It provides options to perform scans, import results into MSF, u... | def main():
print(AsciiArt.get_art())
try:
# connect to the metasploit database
client = MsfRpcClient('uDIBkUec')
print('Initialised MSF RPC client')
client.db.connect('msf', 'msf', password='pm3telki8mupy3a5dcyjz59miqbdnuek')
# user choice to scan or use existing host in... |
def MoveBasePower(move, attacker, defender):
basepower = move.base_power
if move.id.startswith("waterspout"):
return basepower * attacker.current_hp_fraction
if move.id in ["heavyslam", "heatcrash"]:
if defender.is_dynamaxed:
return 0
weight_ratio = (defender.weight ... | The function calculates the base damage of a move in a battle using the formula ((((2*Level/5)+2) * Power * (A/D)) / 50) + 2, where Level is the attacker's level, Power is the move's base power, A is the attacker's effective attack stat, and D is the defender's effective defense stat. It returns the computed damage val... | def CalcBaseDamage(move, attacker, defender, battle):
Level = attacker.level
Power = MoveBasePower(move, attacker, defender)
A = GetEffectiveAttackStat(move, attacker, defender, battle)
D = GetEffectiveDefenceStat(move, defender, battle)
Damage = ((((2*Level/5)+2) * Power * (A/D)) / 50) + 2
re... |
def IsFaster(pokemon1, pokemon2, battle):
# Returns True if pokemon1 is faster than pokemon2
# False otherwise
if GetPokemonStat(pokemon1, "spe", battle) > GetPokemonStat(pokemon2, "spe", battle):
return True
else:
return False
def HasGuaranteedKO(attacker, defender, battle, guessed... | The code determines the optimal move in a Pokémon battle by prioritizing guaranteed knockouts, evaluating speed advantages, considering status moves, and selecting the highest-damage attack. It also checks for switches if necessary, using helper functions to assess battle conditions and maximize strategic effectiveness... | def choose_move(self, battle):
dynamax = battle.can_dynamax
#print(f"\n{battle.turn}")
#Best Move is to take the free knockout
if(True):
if battle.available_moves:
if IsFaster(battle.active_pokemon, battle.opponent_active_pokemon, battle):
... |
def ShouldSwap(battle):
# Checks to see if any swap would reselt in an eval change of 10+
enemy = battle.opponent_active_pokemon
BaseEval = EvalMatchup(battle.active_pokemon, enemy)
# -5 For every 3 net Negative Stat Changes
statChangesCount = 0
# boosts is a dict with key-str Stat, Value int R... | The code determines the best move in a battle by prioritizing switches if beneficial, selecting the highest-damage move if available, and using Dynamax/Terastallize when possible. If no moves are available, it switches. The core task is to strategically choose actions (switch or attack) to maximize damage and matchup a... | def choose_move(self, battle):
dynamax = battle.can_dynamax
#Check if want to Swap
if(battle.available_switches):
if ShouldSwap(battle):
#Swap
BestSwap = max(battle.available_switches, key=lambda self: EvalMatchup(self, battle.opponent_active_... |
def TakeDamage(pokemon, damage):
damage = math.floor(damage)
# Calculate new HP value
currentHP = pokemon.current_hp
#print(f"currentHP: {currentHP}")
#print(f"damage: {damage}")
newHP = pokemon.current_hp - damage
#print(f"newHP: {newHP}")
if newHP > pokemon.max_hp:
newHP = pok... | The function Simulates a Pokémon battle between an Ally and an Enemy, determining the outcome as a percentage of health remaining. It considers move damage, status effects (like poison), turn order, and swapping costs. The result indicates the Ally's health percentage relative to the Enemy's, with +100 meaning a clean ... | def SimBattle(Ally, Enemy, battle, randdata, swapincost = 0):
# Returns a +/- percent health of pokemon
# +100 means we KO Pokemon without taking any damage
# -100 means we get KO'ed without dealing any damage
# Assumes Full HP
Ally = copy.copy(Ally)
Ally.boosts = copy.copy(Ally.boosts)
E... |
def CalcBaseDamage(move, attacker, defender, battle):
Level = attacker.level
Power = MoveBasePower(move, attacker, defender)
A = GetEffectiveAttackStat(move, attacker, defender, battle)
D = GetEffectiveDefenceStat(move, defender, battle)
Damage = ((((2*Level/5)+2) * Power * (A/D)) / 50) + 2
re... | The function calculates the damage of a move in a battle, using either a specific or general method. If the move is status, it returns 0. For specific calculations, it computes base damage, applies multipliers, adjusts for expected hits (e.g., Skill Link ability), and handles special cases like Seismic Toss. If using t... | def CalcDamage(move, attacker, defender, battle, UseSpecificCalc = False):
if(move.category == MoveCategory.STATUS):
return 0
if UseSpecificCalc:
# Use specific calc for RAND BATS
Damage = CalcBaseDamage(move, attacker, defender, battle)
Damage *= Calc... |
def get_intrinsic_replay_dataset(model, new_classes, dataset_full, dataset_trained, factor=1):
dataset_new_classes = filter_by_class(dataset_full, new_classes)
samplesize = math.ceil(average_dict_values(
count_samples_per_class(dataset_new_classes))*factor)
dataset_intrinsic_replay = create_synthet... | The function dynamically expands a neural network's capacity by adding nodes to handle outliers in new data. It iterates through decoder levels, identifies high-loss samples (outliers), and adds nodes while training with both new data and replayed old data. Parameters are optimized separately for new and existing nodes... | def neurogenesis(model, data_new, data_old, threshoulds, max_nodes, max_outliers, pretrained_digits, classes, lr=1e-4, criterion=nn.MSELoss(), epochs_per_it=1,):
ir_training_data = get_intrinsic_replay_dataset(
model, pretrained_digits, full_train_dataset, train_dataset)
size_start = [l.size() for l in ... |
def newEtherTrade(self, amount, order, custom_nonce=None):
self.verifyOrderTradable(order)
amount = self.verifyCapacity(amount, order)
self.log(f"newEtherTrade, amount = {amount}")
ex_contract = self.provider.toChecksumAddress(order["contract"])
exchange = self.provider.eth.con... | This function processes a trade order by determining its type (sell/buy) and token standard (ERC20/ERC223), then delegates to the appropriate trade creation method. It queries the order details, checks the token type, and initiates either an Ether trade, ERC20 trade, or ERC223 trade based on the order's specifications,... | def newTrade(self, amount, orderTx, custom_nonce=None):
order = self.query.awaitOrderTx(orderTx)
order_type = order["type"].lower()
if order_type == "sell":
return self.newEtherTrade(amount, order, custom_nonce)
elif order_type == "buy":
token_address = self.provi... |
def verifyOrderType(self, order_type):
types = ["buy", "sell"]
if order_type not in types:
raise Exception(f'Unknown order type {order_type}')
def determineTokenType(self, address):
address = self.provider.toChecksumAddress(address)
is223 = self.isERC223(address)
is20... | This function creates a new buy/sell order for a token on a decentralized exchange, validating the order type, token standard (ERC20/ERC223), and address format. It routes to specific order-creation methods based on the type, ensuring compatibility with the token's protocol. Custom nonces are supported, and exceptions ... | def newOrder(self, token_address, order_type, amount, price, custom_nonce=None):
token_address = self.provider.toChecksumAddress(token_address)
self.verifyOrderType(order_type.lower())
token_type = self.determineTokenType(token_address)
order_contract = self.exchange_contract_address
... |
def compute_keyword_embeddings(categories):
start_time = time.time()
print("Computing keyword embeddings...")
model = initialize_bert_model()
keyword_embeddings = {}
for category, subcategories in categories.items():
for subcategory, keywords in subcategories.items():
for keywor... | The function processes feedback data by categorizing comments using semantic similarity with predefined categories, computing sentiment scores, and generating summaries. It handles dynamic category updates, batch processing of embeddings, and assigns categories based on similarity thresholds, returning structured data ... | def process_feedback_data(feedback_data, comment_column, categories, similarity_threshold):
global previous_categories
if previous_categories != categories: # Use the categories parameter here
# Compute keyword embeddings
keyword_embeddings = compute_keyword_embeddings(categorie... |
def compute_keyword_embeddings(categories):
start_time = time.time()
print("Computing keyword embeddings...")
#model = initialize_bert_model()
keyword_embeddings = {}
for category, subcategories in categories.items():
for subcategory, keywords in subcategories.items():
for keywo... | The main task of the code is to process feedback data by categorizing comments using semantic similarity with predefined categories, summarizing text, analyzing sentiment, and structuring results into a DataFrame. It handles embeddings computation, batch processing, similarity matching, and outputs categorized data wit... | def process_feedback_data(feedback_data, comment_column, date_column, categories, similarity_threshold):
global previous_categories
# Retrieve the cached keyword embeddings
keyword_embeddings = compute_keyword_embeddings(categories)
# Check if we already computed embedd... |
def compute_keyword_embeddings(categories):
start_time = time.time()
print("Computing keyword embeddings...")
model = initialize_bert_model()
keyword_embeddings = {}
for category, subcategories in categories.items():
for subcategory, keywords in subcategories.items():
for keywor... | The main task of the code is to process feedback data by categorizing comments using semantic similarity with predefined categories, computing sentiment scores, and summarizing text. It preprocesses comments, calculates embeddings in batches, assigns categories based on similarity thresholds, and constructs a structure... | def process_feedback_data(feedback_data, comment_column, categories, similarity_threshold):
global previous_categories
if previous_categories != categories: # Use the categories parameter here
# Compute keyword embeddings
keyword_embeddings = compute_keyword_embeddings(categorie... |
def compute_keyword_embeddings(categories):
start_time = time.time()
print("Computing keyword embeddings...")
model = initialize_bert_model()
keyword_embeddings = {}
for category, subcategories in categories.items():
for subcategory, keywords in subcategories.items():
for keywor... | The main task of the code is to process feedback data by categorizing comments using semantic similarity with predefined categories, summarizing comments, analyzing sentiment, and structuring results into a DataFrame with extended metadata like categories, subcategories, keyphrases, and similarity scores, while handlin... | def process_feedback_data(feedback_data, comment_column, categories, similarity_threshold):
global previous_categories
if previous_categories != categories: # Use the categories parameter here
# Compute keyword embeddings
keyword_embeddings = compute_keyword_embeddings(categorie... |
def preprocess_text(text):
start_time = time.time()
print("Preprocessing text...")
# Convert to string if input is a float
if isinstance(text, float):
text = str(text)
end_time = time.time()
print(f"Preprocessing text completed. Time taken: {end_time - start_time} seconds.")
# Remove... | The main task of the code is to summarize a list of comments using a text summarization pipeline, handling large texts by chunking and batching to stay within token limits. It preprocesses comments, skips summarizing short texts, and processes remaining batches efficiently, returning a list of summaries while tracking ... | def summarize_text(comments, max_tokens_per_sentence=512, max_length=75, min_length=30, max_tokens=1024, min_word_count=70):
start_time = time.time()
print("Preprocessing comments and summarizing if necessary...")
# Preprocess the comments
preprocessed_comments = [preprocess_text(comment) for comment in... |
def compute_keyword_embeddings(keywords):
start_time = time.time()
print("Computing keyword embeddings...")
model = initialize_bert_model()
keyword_embeddings = {}
for keyword in keywords:
keyword_embeddings[keyword] = model.encode([keyword])[0]
end_time = time.time()
print(f"Keyword... | The code processes feedback data by categorizing comments using semantic similarity with predefined keywords, calculating sentiment scores, and generating a structured DataFrame with extended columns. It preprocesses comments, computes embeddings in batches, assigns categories based on similarity thresholds, and organi... | def process_feedback_data(feedback_data, comment_column, date_column, categories, similarity_threshold):
# Compute keyword embeddings
keyword_embeddings = compute_keyword_embeddings([keyword for keywords in categories.values() for keyword in keywords])
# Initialize lists for categor... |
def compute_keyword_embeddings(keywords):
start_time = time.time()
print("Computing keyword embeddings...")
model = initialize_bert_model()
keyword_embeddings = {}
for keyword in keywords:
keyword_embeddings[keyword] = model.encode([keyword])[0]
end_time = time.time()
print(f"Keyword... | The main task of the code is to categorize feedback comments into predefined categories using semantic similarity, compute sentiment scores, summarize long comments, and generate a structured DataFrame with processed data including categories, sub-categories, sentiment scores, and dates. It batches embeddings for effic... | def process_feedback_data(feedback_data, comment_column, date_column, categories, similarity_threshold):
# Compute keyword embeddings
keyword_embeddings = compute_keyword_embeddings([keyword for keywords in categories.values() for keyword in keywords])
# Initialize lists for categor... |
def add_stats(stats, a):
if a not in stats:
stats[a] = 1
else:
stats[a] += 1
def handle_patron_not_found(self, fail):
failed_loan = fail[1]
loan_created = None
try:
q_path = (
f'/item-storage/items?query=(barcode=="{failed_loan["item_barcode"]}... | The code processes failed loan records by categorizing failure reasons, updating statistics, and generating a migration report. It iterates through failed loans, applies specific handlers for issues like missing patrons or inactive users, logs unhandled cases, and outputs summaries of counts for duplicates, successes, ... | def work(self):
print("Starting....")
# Iterate over every loan
i = 0
for failed_loan in self.failed_items.values():
# for failed_loan in failed_loans:
# print(failed_loan)
# print(failed_loan[0][2])
fail_reason = failed_loan[0][2]
... |
def screen_on():
os.system('echo 0 | sudo tee /sys/class/backlight/rpi_backlight/bl_power')
def calculate_distance(speed_mph,time_ms):
mpms = speed_mph / 3600000 # 1 hour = 3600000 milliseconds
distance = mpms * time_ms
return distance
def replace_text(text_widget, new_text):
text_widget.delete('1.... | The code receives and processes CAN bus messages from a vehicle's OBD-II system, updating parameters like RPM, Bar, MAP, TPS, and transmission data. It differentiates between Linux (real CAN message handling) and non-Linux (simulated data generation). Detected messages update a shared data dictionary, trigger screen al... | def receive_can_messages(values,bus,LastMessageTime,out_q):
global count
while True:
if os_type == "Linux":
canMsg = bus.recv(0.01)
if canMsg is not None:
canMsg = cast(can.Message,canMsg)
if (LastMessageTime - datetime.now()).total_seconds() ... |
def load_bbox(self):
data_dir = self.data_dir
bbox_path = os.path.join(data_dir, 'CUB_200_2011/bounding_boxes.txt')
df_bounding_boxes = pd.read_csv(bbox_path,
delim_whitespace=True,
header=None).astype(int)
#... | This code initializes a dataset class for image-text tasks, loading images, captions, and metadata. It uses GloVe embeddings for text, handles bounding boxes for bird datasets, and prepares data splits (train/test). The class also loads a knowledge base and sets up transformations for image normalization and resizing, ... | def __init__(self, data_dir, split='train',
base_size=64,
transform=None, target_transform=None):
self.transform = transform
self.norm = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
... |
def getmindist(self, max_ang, min_ang):
min_index = self.angletoindex(min_ang * math.pi / 180)
max_index = self.angletoindex(max_ang * math.pi / 180)
return min(self.laserdata[min_index:max_index]) / (max_index - min_index)
def getrightsum(self):
rightsum = 0
count = 0
for i in range(self.anglet... | This code implements a wall-following and obstacle-avoidance strategy for a robot using laser data. It checks front, left, and right sensor ranges to decide turning direction or forward movement, adjusting linear and angular velocities based on proximity to walls. If no direct obstacle is detected, it switches to a saf... | def move(self):
if self.laserdata is not None:
if (self.getmindist(90, -90) == self.getmindist(30, -30)):
#minimum is in front, pick either R or L wall follow
if (self.getrightsum() > self.getleftsum()):
self.turn_right()
self.wall_right()
elif (self.getleftsum() > ... |
def _load_checkpoint(self):
"""
Returns the checkpoint dict found in path.
TODO: map location could be switched to possible GPUs theoretically
"""
# Generate a variable that stores the checkpoint path
checkpoint_path = os.path.join(self.path, "checkpoint.tar")
... | The main task of the code is to execute jobs encoded in JSON format by iterating through a job queue, setting up logging, creating directories, initializing models, and performing training/evaluation based on job specifications. It handles checkpointing, logging, and error handling, while resuming or clearing logs as s... | def run(self):
"""
This method can be called in order to run a job (encoded in json format)
"""
# Iterate through all jobs
for index, job in enumerate(self.job_queue):
try:
# Set data logging to initial
self.epoch_log_initial = True
... |
def dog_detector(img_path):
prediction = ResNet50_predict_labels(img_path)
return ((prediction <= 268) & (prediction >= 151))
def inceptionv3_predict_dogbreed(img_path, model):
'''
Returns the dog breed that is predicted by an CNN network model.
Parameters:
img_path (str... | The function `detect_human_dog` classifies an image as containing a human or a dog using detectors, then employs a pre-trained CNN model to predict the breed (or resemble breed for humans). It returns the detected category and breed, or an error if neither is identified. The model, intended for dog breeds, is reused fo... | def detect_human_dog(img_path, model):
'''
Returns if the identified animal is a person or a dog and what is each breed (or what breeds it resembles if a person)
If it is not returns an error.
Parameters:
img_path (str): image file path
model (keras.model... |
def dog_detector(img_path):
prediction = ResNet50_predict_labels(img_path)
return ((prediction <= 268) & (prediction >= 151))
def inceptionv3_predict_dogbreed(img_path, model):
# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("../data/dog_images/train/*/"))]
# extract bottle... | The code detects if an image contains a dog or human using specific detectors. If a dog is detected, it predicts the breed using a model and returns the result. If a human is detected, it similarly predicts a "breed-like" descriptor. If neither is found, it returns an error message. | def detect_human_dog(img_path, model):
img = cv2.imread(img_path)
if dog_detector(img_path):
breed = inceptionv3_predict_dogbreed(img_path, model)
return 'Dog detected: This dog looks like a {}'.format(breed)
elif face_detector2(img_path):
breed = inceptionv3_predict_... |
def get_1d_max_index_softmax_prob(self, data_1d, idx=[], get_num=1):
'''input dim value'''
data_1d = np.array(data_1d).copy()
d_l=np.size(data_1d)
d_t = data_1d.reshape(d_l,)
if len(idx) == 0:
d_t_idx = np.linspace(0,d_l-1, d_l, dtype=np.int)
else:
... | The main task of the code is to generate the next state in a reinforcement learning environment by selecting and applying an action based on the current global state. It randomly chooses parameters like layer, cluster level, dimension, type, size, and offset, while incorporating heuristics to balance exploration/exploi... | def next_state(self, decay_turn, is_init=False):
global mcts_init_done_flag
#act_t_type = np.random.randint( 0, varInst.act_type_len, [varInst.act_type_exist, ], np.int).tolist()
#act_t_dim = np.random.randint( 0, varInst.act_dim_len, [varInst.act_dim_exist, ... |
def createNewMarkupNode(self):
# Create empty markup fiducial node
if self.segmentMarkupNode is None:
displayNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLMarkupsDisplayNode")
displayNode.SetTextScale(0)
self.segmentMarkupNode = slicer.mrmlScene.AddNewNodeByClass(... | The code disables the effect cursor in slice views, creates a new markup fiducial node if none exists, configures the fiducial placement toggle with the node, disables placing mode, and updates the GUI based on MRML data. | def activate(self):
self.scriptedEffect.showEffectCursorInSliceView = False
# Create empty markup fiducial node
if not self.segmentMarkupNode:
self.createNewMarkupNode()
self.fiducialPlacementToggle.setCurrentNode(self.segmentMarkupNode)
self.setAndObserveSeg... |
def validate_request(data):
for key in data.keys():
is_valid = is_valid_text(data[key])
if not is_valid:
response_message = "%s should not be empty" % key
return create_response(400, response_message)
return is_valid_email(data['email'])
def create_response(status_code,... | The code's main task is to register a new broker by validating input data, checking if their email domain is whitelisted, matching them to an agency based on address proximity, and saving the broker to the database. It ensures domain compliance, resolves agency conflicts via geolocation, and returns the broker's detail... | def signup(data):
is_invalid = validate_request(data)
if is_invalid:
return is_invalid
broker = Broker(**data)
domain = broker.email.split('@', 1)[1]
try:
query = db.session.query(AgencyDomainWhiteList).filter(AgencyDomainWhiteList.domain == domain)
whitelist_domain = que... |
def enforce_node_consistency(self):
"""
Update `self.domains` such that each variable is node-consistent.
(Remove any values that are inconsistent with a variable's unary
constraints; in this case, the length of the word.)
"""
for var in self.domains:
for wor... | The code solves a Constraint Satisfaction Problem (CSP) by enforcing node consistency (validating individual variable domains), applying the AC3 algorithm to ensure arc consistency (validating pairwise variable constraints), and then using backtracking search to find a valid assignment of values to variables that satis... | def solve(self):
"""
Enforce node and arc consistency, and then solve the CSP.
"""
self.enforce_node_consistency()
self.ac3()
return self.backtrack(dict()) |
def part1(pairs):
result = [int(compare(*pair)) for pair in pairs]
return sum(i+1 for i, val in enumerate(result) if val)
def parse_input(path: str):
with open(path) as f:
content = f.read()
text_pairs = [pair.split('\n') for pair in content.split('\n\n')]
pairs = [[eval(item) f... | The code's main task is to execute and compare solutions for two parts (Part 1 and Part 2) of a programming problem using test and actual input files. It reads input from `test.txt` and `input.txt`, processes them with `part1()` and `part2()` functions, and prints results for both test cases and the actual input. The g... | def solve():
test_path = '13/test.txt'
input_path = '13/input.txt'
print("Part 1:")
print(f"test: {part1(parse_input(test_path))}")
print(f"result: {part1(parse_input(input_path))}")
print("Part 2:")
print(f"test: {part2(parse_input(test_path))}")
print(f"result: {part2(parse_input(... |
def _dijkstra(self, graph, source, destination, pos, ax):
self.distances[source] = 0
priority_queue = [(0, source)]
while priority_queue:
dist, current_node = heapq.heappop(priority_queue)
if current_node == destination:
break
if current_nod... | This code executes Dijkstra's algorithm to find the shortest path from a source to destination node in a graph. If a path exists, it visualizes the graph with the shortest path nodes highlighted in green, updates node colors, redraws edges, and displays the result with a title. If no path is found, it prints an error m... | def execute(self, graph,pos,ax, source, destination):
self._dijkstra(graph, source, destination,pos, ax)
if destination not in self.distances:
print(f"No path found from {source} to {destination}")
else:
self._build_shortest_path(source, destination)
print(f... |
def increment(self, ):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def expr(self):
return self.bin_op(self.term, (LEX_NEXT, LEX_PAUSE)) | This function parses expressions by handling unary operations, keywords, and parentheses. It processes tokens like LEX_NEXT, LEX_PAUSE, LEX_KEYNOTE, and LEX_LPAREN, recursively parsing factors or expressions, and returns corresponding AST nodes (UnaryOpNode, SFrequencyNode) or syntax errors if invalid tokens/structure ... | def factor(self):
res = ParseResult()
tok = self.current_tok
if tok.type in (LEX_NEXT, LEX_PAUSE):
res.register(self.increment())
factor = res.register(self.factor())
if res.error: return res
return res.success(UnaryOpNode(tok, factor))
elif tok.type is LEX_KEYNOTE:
res.register(self.increment(... |
def posix_ensure_abs(path):
if not path.is_absolute():
return '/' / path
return path
def out(message):
print(message, flush=True)
def get_remote_to_delete(local_dir, remote_dir):
path_list = []
output = cmd("mega-ls -Rl {}".format(remote_dir), ignore_errors=True)
current_dir = None
... | This function synchronizes local and remote directories by deleting remote files not present locally and uploading new/modified local files. It handles exclusion patterns, skips deletions/uploads in dry-run mode, and uses Mega CLI commands for operations. | def sync(local_dir, remote_dir, excludes=None, dryrun=False):
local_dir = Path(local_dir).resolve(strict=True)
remote_dir = posix_ensure_abs(PurePosixPath(remote_dir))
out("Syncing from {} to {}".format(local_dir, remote_dir))
# Find all actual local files/directories excluded by exclude globs
excl... |
def get_train_set(self):
get_train_set_frame = ttk.Labelframe(self.root, text="Get Train Set")
get_train_set_frame.grid(column=0, row=0,padx=8)
file_path = tk.StringVar(value="")
ttk.Label(get_train_set_frame, text="Train File Path").grid(column=0, row=0)
ttk.Entry(get_train_set... | The code initializes a GUI application by setting up a frame, loading a training dataset, testing and validating a model, customizing the dataset, creating model-related UI components, and enabling input fields for user interaction. It orchestrates model setup, data processing, and interface configuration in a structur... | def __init__(self):
self.root = ttk.Frame()
# Get Train Set
self.get_train_set()
# Model testing and validation
self.model_testing_and_validating()
# Customize Train Set
self.customize_train_set()
# Model Frame
... |
def login(self):
self.logger.info('Connecting to homepage')
self.driver.get(KijijiReposter.HOMEPAGE)
if self.cookie is None:
self.logger.info('Reading cookie file')
with open(self.cookie_filename, 'r') as f:
self.cookie = f.read().strip()
... | The code's main task is to manage ad operations by logging in, optionally deleting all ads from a directory if `delete_all` is True, posting all ads if `is_post` is True, and performing cleanup afterward. | def repost(self, rootdir, delete_all=False, is_post=False):
self.login()
if delete_all:
self.delete_all_ads(rootdir)
if is_post:
self.post_all_ads(rootdir)
self.cleanup() |
def render(self, mode="human"):
self._update_screen()
self._check_events()
def _get_obs(self) -> dict[str, np.ndarray]:
"""
Gets the observation of the environment.
The observation is a dictionary that contains the following keys:
- player_velocity: The velocity of t... | The code processes an action in a game environment for machine learning. It updates the player's state, awards +1 reward for passing a pipe, applies -500 penalty for collisions, and returns observation, reward, termination status, and metadata. The function handles game state transitions and reinforcement learning feed... | def step(self, action):
self.render()
# If the game is being run on machine learning mode
if self.is_ml:
# Take the action
self.current_scene.player.take_action(self._action_to_move[action])
# If the player has passed a pipe, give a reward of 1
if... |
def _download(self):
# See https://github.com/pytorch/vision/issues/4156
torch.hub._validate_not_a_forked_repo = lambda a, b, c: True
if self._check_integrity():
print('Files already downloaded and verified')
return
print('Downloading dataset')
download_... | This code initializes a dataset by handling download, verifying data integrity, cropping images if specified, and splitting data into training/test sets. It sets up transformations, manages file paths, and ensures required directories exist for image processing and storage. | def __init__(self, root='~/data/cub2011', train=True, crop=True,
transform=None, target_transform=None, download=False, resize_size=None):
super().__init__(root, transform=transform, target_transform=target_transform)
self.loader = default_loader
self.train = train
self... |
def query_long_term_memory(self, query, k=2) -> list:
"""Query the long-term memory for similar documents. Returns a list of Document objects."""
try:
memories = self.long_term_memory_index.similarity_search(query, k=k)
sorted_memories = sorted(memories, key=lambda x: x.metadata... | The code queries a language model to generate a response to a given prompt, incorporating long-term memory retrieval, parameter tuning (temperature, penalties), model-specific configurations (Gemini vs. others), NSFW content filtering, and updates short-term memory with the interaction. It returns the generated respons... | def query(self, prompt, temperature=.3, top_p=None,
frequency_penalty=0, presence_penalty=0, max_tokens=200) -> str:
"""Query the model for a response to a prompt. The prompt is a string of text that the AI will respond to.
The temperature is the degree of randomness of the model's out... |
def map_pixel_to_pcd(self, valid_pix_mask):
''' establish pixel to point cloud mapping, with -1 filling for invalid pixels
:param valid_pix_mask:
:return:
'''
image_size = valid_pix_mask.shape
pix_2_pcd_map = torch.cumsum(valid_pix_mask.view(-1), dim=0).view(image_size).l... | This function registers a depth frame by converting it into a point cloud, mapping pixels to 3D points, and optionally aligning landmarks between source and target frames. It then visualizes the target point cloud and the result of a registration process (warped_pcd) using the solve method, which likely aligns the poin... | def register_a_depth_frame(self, tgt_depth_path, landmarks=None):
"""
:param tgt_depth_path:
:return:
"""
"""load target frame"""
tgt_depth = io.imread( tgt_depth_path )/1000.
depth_mask = torch.from_numpy(tgt_depth > 0)
tgt_pcd = depth_2_pc(tgt_depth, se... |
def findMoveMinMax(gs, validMoves, depth, whiteToMove, alpha, beta, capture=False):
global nextMove, counter, movesEvaluated
# Check if terminal move
if (depth >= DEPTH and not capture) or (depth >= MAX_DEPTH):
return scoreBoard(gs)
if gs.draw:
return DRAW
if whiteToMove:
ma... | The function `findBestMove` determines the optimal chess move using a minimax algorithm with alpha-beta pruning. It evaluates valid moves, calculates their scores recursively, and selects the best move based on the evaluation. If no move is found, it defaults to a random choice. The process tracks time, move evaluation... | def findBestMove(gs, validMoves, turn, returnQueue):
global nextMove, counter, favLine, capture, bestEval, movesEvaluated
counter = 0
nextMove = None
#sstart = timer()
#gs.getValidMoves()
#endd = timer()
#print(endd-sstart)
movesEvaluated = 0
start = timer()
#bestEval = findMoveN... |
def findMoveNegaMax2(gs, validMoves, depth, turnMultiplier, root, alpha, beta):
global initialMoves, counter, bestEval, movesEvaluated
# Move Ordering - Implement later
maxScore = -CHECKMATE - 1
counter += 1
if (depth == 0):
return turnMultiplier * scoreBoard(gs)
else:
attack = ... | This function performs a two-step search algorithm for move evaluation in a game. It first conducts an initial search using NegaMax to identify candidate moves, then performs a deeper final search with alpha-beta pruning to evaluate the best move. The result is stored in a queue, with time and evaluation metrics printe... | def twoStepSearch(gs, validMoves, lines, initialDepth, finalDepth, returnQueue):
global initialMoves, counter, initFound, movesEvaluated, nextMove
counter = 0
initialMoves = []
nextMove = None
movesEvaluated = 0
turn = 1 if gs.whiteToMove else -1
start = timer()
print("Initial Search:")
... |
def AlphaBeta(gs, depth, alpha, beta, mate): # val = AlphaBeta(gs, 8, -INFINITY, INFINITY, MATE);
global counter
legal = 0
if depth == 0:
return scoreBoardNega(gs)
validMoves = gs.getValidMoves()
for move in validMoves:
counter += 1
gs.initMove(move, True)
val = -Alp... | This function performs a quiescence search in a game state, evaluating only positions where captures are possible. It uses alpha-beta pruning to optimize the search, updating alpha/beta bounds and tracking the best move in `pline`. It recursively explores capture moves, applying and undoing each move, and returns the b... | def Quies(gs, alpha, beta, mate, pline): #val = AlphaBeta(gs, 5, -INFINITY, INFINITY);
global counter
line = LINE()
if gs.check:
return AlphaBeta(gs, 1, alpha, beta, mate - 1)
val = scoreBoardNega(gs)
if val >= beta:
return beta
if val > alpha:
alpha = val
captureMove... |
def getAllPossibleMoves(self):
moves = []
for r in range(len(self.board)):
for c in range(len(self.board[r])):
turn = self.board[r][c][0]
if (turn == "w" and self.whiteToMove) or (turn == "b" and not self.whiteToMove):
piece = self.board[r]... | The main task of the code is to generate valid chess moves by filtering out moves that leave the king in check, handling castling, and determining checkmate/stalemate conditions. It iterates through all possible moves, simulates each, checks for opponent's threat, removes invalid moves, and updates game state flags if ... | def getValidMoves(self):
self.trying = True
moves = self.getAllPossibleMoves()
opp = "b" if self.whiteToMove else "w"
for i in range(len(moves) - 1, -1, -1):
self.initMove(moves[i])
if self.inCheck(opp):
moves.remove(moves[i])
self.undo... |
def getCapturesOnly(self):
moves = []
for r in range(len(self.board)):
for c in range(len(self.board[r])):
turn = self.board[r][c][0]
if (turn == "w" and self.whiteToMove) or (turn == "b" and not self.whiteToMove):
piece = self.board[r][c][... | This function identifies valid capture moves by removing those that don't put the opponent in check. It checks for checkmate or stalemate if no valid captures remain, updating game state flags accordingly. | def getValidCaptures(self):
self.trying = True
moves = self.getCapturesOnly()
opp = "b" if self.whiteToMove else "w"
if moves == None:
return moves
for i in range(len(moves) - 1, -1, -1):
self.initMove(moves[i])
if self.inCheck(opp):
... |
def is_5_of_a_kind(cards):
if USE_JOKER:
jokers = cards.count('J')
if jokers == 5:
return True
card = cards[0]
count = 1
while card == 'J' and count < len(cards):
card = cards[count]
count += 1
return 5 == jokers + cards.count(card)... | This function compares two poker hands (set1 and set2) by checking their types (e.g., 5-of-a-kind, full house) and card values. It returns 0 if equal, 1 if the first hand is stronger, or -1 if the second is stronger, using a hierarchy of hand rankings and a helper function for tie-breaking comparisons between same-type... | def cmp_sets(c1, c2):
set1 = c1[0]
set2 = c2[0]
if set1 == set2:
return 0
if is_5_of_a_kind(set1) and is_5_of_a_kind(set2):
return cmp_cards(set1, set2)
if is_5_of_a_kind(set1):
return 1
if is_5_of_a_kind(set2):
return -1
if is_4_of_a_kind(set1) and is_4_of_a_... |
def clean_ratings():
"""
Ingests ramen-ratings.csv,
Renames a United States value to USA,
Drops low-count ramen styles Box, Can, and Bar (8 rows),
Drops countries with less than 5 cumulative observations (29 rows),
Drops Unrated, nulls and duplicates (16 rows),
Repl... | The main task of the code is to prepare data for machine learning modeling by cleaning, engineering features (e.g., creating 5-star review brackets for country and flavor, spicy status), selecting relevant columns, splitting data into training, validation, and test sets, and isolating the target variable 'five_stars' f... | def prep_model():
""" Cleans, engineers, and splits data for modeling, returns splits """
# clean data
df = clean_ratings()
# create country low-, medium- and high-proportion 5-star-review brackets
df = create_country_features(df)
# create flavor low-, medium- and high-proportion 5-star-review b... |
def calculate_d_alpha_h(p, d_alpha_h, alpha_smaller_0, alpha_greater_0, alpha_0, h_q_t):
d_alpha_h[alpha_smaller_0] = (
h_q_t[alpha_smaller_0 + 1] - h_q_t[alpha_smaller_0]
) / p.dalpha
d_alpha_h[alpha_greater_0] = (
h_q_t[alpha_greater_0] - h_q_t[alpha_greater_0 - 1]
) / p.dalpha
d_a... | The code computes the dynamic function `h` over time, alpha, and q values using nested loops and boundary conditions. It initializes arrays, iterates backward through time steps, and calculates `h` using helper functions for derivatives and optimal postings. Terminal conditions set `h`'s final state, while `mo_plus` an... | def generate_h(p):
print("Starting h calculation")
Upsilon = p.Delta + p.epsilon
dt = p.dt
print(dt)
q_a = np.arange(-p.q_max, p.q_max + 1, 1)
alpha = np.arange(-p.A, p.A + 1, p.dalpha)
alpha_smaller_0 = np.where(alpha < 0)[0]
alpha_greater_0 = np.where(alpha > 0)[0]
alpha_0 = np.w... |
def forward(self, X):
# Performs a forward pass through the neural network
# Given an input X, it calculates the activations of each layer and returns them as a list
# activations[0] is the input layer and activations[-1] is the output layer
activations = [X]
for i in range(len(s... | The code trains a neural network using batch gradient descent over multiple epochs. It processes data in batches, computes activations via forward propagation, updates weights using backpropagation, and calculates loss every 10 epochs to monitor performance. The learning rate controls weight updates, while batch size d... | def train(self, X, y, epochs, batch_size, learning_rate):
self.learning_rate = learning_rate # set the learning rate
for epoch in range(epochs): # loop through the number of epochs
for i in range(0, len(X), batch_size): # loop through the training data in batches
X_batch =... |
def in_qdq(self, input):
"""Quantize-dequantize both the input and the input's gradient."""
qin = qdq_and_update(input, FAKE_E4M3, self.input_scale, self.input_amax_history)
def grad(in_grad):
in_grad_ret = qdq_and_update(in_grad, FAKE_E5M2, self.input_grad_scale,
... | This code performs a linear transformation on input tensors using matrix multiplication, handling sparse and ragged tensors efficiently. It ensures dtype consistency, processes RaggedTensors by flattening or converting them, applies optional bias and activation functions, and restores original tensor structures before ... | def call(self, inputs):
if inputs.dtype.base_dtype != self._compute_dtype_object.base_dtype:
inputs = tf.cast(inputs, dtype=self._compute_dtype_object)
is_ragged = isinstance(inputs, tf.RaggedTensor)
if is_ragged:
# In case we encounter a RaggedTensor with a fixed last d... |
def stemm(q):
splitq = q.split(" ")
newq = ""
for qterm in splitq:
newq += ss.stem(qterm) + " "
#returns original query
return q.lower()
def query(q, searchtype, start=0):
#how many results per page
size = 10
#stemming query terms
#newq = q#stemm(q)
#print('Query ' ... | The main task of the code is to search documents from a specified domain using a stemmed query, retrieve up to a given number of results, and return them in JSON format with URLs. It utilizes Elasticsearch to filter by domain, perform a multi-field match query on "title" and "fulltext," and format the response. | def mfd(q, domainurl, size=4):
print('more from here ' + str(domainurl))
#stemming query terms
newq = stemm(q)
s = Search(using=es, index=indexName_doc).filter('term', domain=domainurl).query("multi_match", query = newq, fields = ["title", "fulltext"])[1:int(size)]
response = s.execute()
#p... |
def recommend_edge(self, idx, how = 'random_fof', **kwargs):
if how == 'random_fof':
return(self._recommend_random_fof(idx))
if how == 'adamic_adar':
return(self._recommend_adamic_adar(idx))
if how == 'embedding':
return(self._recommend_embedding(idx, **kwargs... | The code applies an intervention by recommending and selectively adding/removing edges to treatment nodes in a network. It samples nodes based on size/fraction, recommends edges using specified methods, and conditionally accepts them. Parameters control sampling, recommendation strategy, acceptance probability, and edg... | def intervention(self, **kwargs):
# intervention is applied only to treatment nodes
self.rec_how = kwargs.get('rec_how', 'random_fof')
self.rec_sample_size = kwargs.get('rec_sample_size', None)
self.rec_sample_fraction = kwargs.get('rec_sample_fraction', None)
self.acc_how = k... |
def initialize_metrics(self, **kwargs):
self.is_ab_test = kwargs.get('is_ab_test', False)
self.treatment_probability = kwargs.get('treatment_probability', 1)
self.metric_names = ['time', 'added_nodes', 'nodes', 'edges', 'avg_degree', 'degree_variance', 'bi_frac', 'global_clustering', 'avg_age',... | The main task of the code is to run multiple experiments with different random seeds, collect performance metrics, and optionally save results to a JSON file or plot averaged metrics. It initializes experiment parameters, executes each trial, records individual or aggregated results, and generates visualizations if ena... | def run_experiments(self, grp_info: 'list[dict]', **kwargs):
self.experiments = []
record_each_run = kwargs.get('record_each_run', True)
plot = kwargs.get('plot', False)
if plot or (not record_each_run):
self.grp_num = len(grp_info)
self.total_step = kwargs.get('... |
def step_natural_growth(self, node: Node, ng_how, p2_mediated):
self.network.add_node(node)
# phase 1
node_list = copy.deepcopy(list(self.network.G.nodes))
random.shuffle(node_list)
if not (self.Ns is None):
node_list = node_list[:self.Ns]
for i in node_list:
... | This code simulates a network step by adding new nodes proportional to group sizes, applying natural growth, treatment (based on probability/color), and interventions. It updates the network state, increments time, and optionally removes nodes, returning the updated node index. | def step(self, nodes_step, idx, intervention, treatment, **kwargs):
# assume new node comes in proportional to groups' initial sizes
arrival_probs = self.network.init_sizes/np.sum(self.network.init_sizes)
new_nodes_grp = np.random.choice(len(self.grp_lst), size=nodes_step, p=arrival_probs)
... |
def tensorsFromPair(pair):
'''
Convert pair to a tensor
'''
input_tensor = tensorFromSequence(source, pair[0])
target_tensor = tensorFromSequence(target, pair[1])
return (input_tensor, target_tensor)
def train(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, c... | The code trains a sequence-to-sequence model using encoder and decoder networks over multiple iterations. It initializes optimizers, computes loss via NLLLoss, iterates through shuffled input-target pairs, accumulates and averages losses per epoch, prints training progress with time tracking, and stores losses for plot... | def trainIters(encoder, decoder, n_iters, pairs, learning_rate=0.01):
'''
Train model. Print losses and time trianing took for each epoch. Plot losses every epoch.
'''
start = time.time() #for tracking training time
plot_losses = []
print_loss_total = 0
plot_loss_total = 0
encoder_o... |
def __error(self, selector):
if not selector:
logger.error(f"can not find metadata from the selector: {selector}")
return True
else:
return False
def _get_title(self, metadata_selector):
titles_xpath = 'div[@class="nbk-w-full nbk-flex nbk-flex-wrap nbk-justi... | The code extracts metadata from a webpage using XPath selectors. It retrieves title, price, size, and link data from a specific HTML element, handles errors if the element isn't found, compiles the data into a dictionary, adds a timestamp, and returns the structured metadata. | def get_all_metadata(self, selector) -> dict:
metadata_selector = selector.xpath(
'div[@class="nbk-px-2 nbk-pt-2 md:nbk-px-3 md:nbk-pt-3"]'
)
if len(metadata_selector) > 0:
metadata_selector = metadata_selector[0]
else:
self.__error(metadata_selector)... |
def __error(self, selector):
if not selector:
logger.error(f"can not find metadata from the selector: {selector}")
return True
else:
return False
def _get_title(self, metadata_selector):
xpaths = {
# "title": 'div[@class="FactsSection-1460e"]/div... | The function `get_all_metadata` extracts metadata from an HTML element using XPath. It selects the first `<a>` tag, then gathers title, price/size, and link data via helper methods. A timestamp is added, and the combined metadata is returned as a dictionary. | def get_all_metadata(self, selector) -> dict:
metadata_selector = selector.xpath('a')
if len(metadata_selector) > 0:
metadata_selector = metadata_selector[0]
else:
self.__error(metadata_selector)
metadata = {}
metadata.update(self._get_title(metadata_sel... |
def __error(self, selector):
if not selector:
logger.error(f"can not find metadata from the selector: {selector}")
return True
else:
return False
def _get_title(self, metadata_selector):
xpaths = {
"title": 'div[2]/div[1]/div[1]/h2/text()',
... | The main task of the code is to extract metadata from HTML elements using XPath. It selects the first 'a' tag from the input selector, then compiles a dictionary containing title, price/size, link data via helper methods, and adds a timestamp. The result is a consolidated metadata dictionary for further processing or s... | def get_all_metadata(self, selector) -> dict:
metadata_selector = selector.xpath('a')
if len(metadata_selector) > 0:
metadata_selector = metadata_selector[0]
else:
self.__error(metadata_selector)
metadata = {}
metadata.update(self._get_title(metadata_sel... |
def HOPF(dt, mu, w0, alpha, beta, D, Forces_x, Forces_y, r0, phi0):
N = len(Forces_x)
X = np.zeros(N, dtype=float)
Y = np.zeros(N, dtype=float)
X[0] = r0*np.cos(phi0)
Y[0] = r0*np.sin(phi0)
for i in range(1, N):
X[i], Y[i] = Hopf_RK2(mu, w0, alpha, beta, X[i-1], Y[i-1], Forces_x[i-1], Fo... | The function computes the quality factor (Q) and threshold bandwidth (tBW) from the frequency spectrum of a Hopf bifurcation model. It initializes parameters, generates time-series data via the HOPF function, computes the FFT of segmented data, averages frequency magnitudes, and applies find_Q and find_Threshold_Bandwi... | def find_Q_and_tBW(dt, mu, W0, alpha, beta, D, num_seg=10, threshold_for_BW=0.1):
if mu > 0:
r0, w0 = (mu/alpha)**0.5, W0 + beta*mu/alpha
else:
r0, w0, = 0, W0
N = 100002
N_cut = 10000
x, y = HOPF(dt, mu, w0, alpha, beta, D, np.zeros(N*num_seg + N_cut), np.zeros(N*num_seg + N_cut), r... |
def contains(self, key):
index = self.hash(key);
return self.contains_helper(index, 0, key);
def hash(self, key):
ret = 0;
string = str(key)
for i in range(len(string)):
temp = ord(string[i]);
ret += temp*i + temp;
if ret > self.length-1: return r... | This code retrieves a value from a hash table by checking if the key exists, computing its hash index, finding the correct index (handling collisions), and returning the corresponding value from the array. | def get(self, key):
if not self.contains(key): return None;
index = self.hash(key);
return self.arr[self.find_index(index, key)].value; |
def isConnected(self):
try:
socket.create_connection(("1.1.1.1", 53))
# QMessageBox.critical(self,"Connection Error","No Internet Connection. Please after reconnecting.")
return True
except OSError:
pass
return False
def reload(self):
if(se... | The main task of the code is to validate and publish a quiz by checking input constraints (e.g., nickname, duration, time limits), handling errors, prompting user confirmation for default duration, verifying internet connectivity, and invoking a database call to publish the quiz with specified parameters. It also notif... | def publishQuiz(self):
quizNickName = self.sessionNickName.text().strip()
err = ""
if(quizNickName==""):
err+="Nick Name must not be blank.\n"
duration = self.duration.value()
if(self.isTimeConstrained.isChecked()):
if(self.sessionStart.dateTime()... |
def data_loader():
data_train_ = pd.read_excel('data_train.xlsx')
data_train_.drop('Unnamed: 0', axis=1, inplace=True)
data_dev_ = pd.read_excel('data.xlsx')
data_dev_.drop('Unnamed: 0', axis=1, inplace=True)
data_train = []
data_dev = []
for idx, item in data_train_.iterrows():
da... | The main task is to load training and validation data, prepare a model with an optimizer and scheduler, train the model using the data, and generate predictions. The code initializes data loaders, sets up the model for training, executes the training process, and finally runs predictions on the training data. | def main():
print('done')
(
train_data_loader,
dev_data_loader,
num_train_optimization_steps
) = data_loader()
model, optimizer, scheduler = prep_for_training(num_train_optimization_steps)
train(
model,
train_data_loader,
dev_data_loader,
opt... |
def create_parser():
parser = CompatibleArgumentParser(
description=__summary__)
parser.add_argument('-v', '--version',
action='version',
version='%(prog)s ' + __version__)
parser.add_argument('--from',
action='store', type=str,... | The main task of the code is to parse command-line arguments, generate an output string based on the arguments, save it to a specified file if needed, print the output, and display warnings (if any) to standard error. It orchestrates input processing, file handling, and result presentation in a single execution flow. | def main(): # pragma: no cover
parser = create_parser()
args = parser.parse_args()
output_string = create_output_string(args)
output_file = args.output_file
save_if_needs(output_file, output_string)
print(output_string)
warn_string = create_warn_string(args)
if warn_string:
p... |
def detect_feature_and_keypoints(self, image):
# detect and extract features from the image
descriptors = cv2.SIFT_create()
(keypoints, features) = descriptors.detectAndCompute(image, None)
keypoints = np.float32([i.pt for i in keypoints])
return keypoints, features
def match_key... | The code stitches two images using SIFT feature detection and matching. It identifies keypoints and descriptors, matches them with a Lowe's ratio test and threshold, computes homography for alignment, and warps images to create a seamless panorama. If enabled, it visualizes matches. Returns the stitched image or a tupl... | def image_stitch(
self, images, lowe_ratio=0.75, max_Threshold=4.0, match_status=False
):
# detect the features and keypoints from SIFT
(imageB, imageA) = images
(key_points_A, features_of_A) = self.detect_feature_and_keypoints(imageA)
(key_points_B, features_of_B) = self.det... |
def getNeighbors(r, c):
neighbors = []
if (r > 1):
neighbors.append((r - 1, c))
if (c > 1):
neighbors.append((r - 1, c - 1))
if (c < len(grid[0]) - 2):
neighbors.append((r - 1, c + 1))
if (c > 1):
neighbors.append((r, c - 1))
if (c < len(grid[0]) -... | This function processes a grid to reveal non-mine cells and their neighbors in a Minesweeper-like game. It iterates through cells, skips visited or mine cells, checks neighboring cells for mines, and triggers neighbor reveals when the adjacent mine count matches the current cell's value, aiding automated gameplay. | def basicMineClick():
for r in range(1, len(grid) - 1):
for c in range(1, len(grid[0]) - 1):
if (grid[r][c] == -1 or grid[r][c] == -2 or visitedNodes[r][c]): continue
neighbors = getNeighbors(r, c)
mineFound = count(-2, neighbors)
neighborBlank = count(-1, nei... |
def rotateExcluded(pattern, rows, cols):
ans = []
for p in pattern:
ans.append(rotatePoint(p, rows, cols))
return ans
def rotatePattern(pattern):
ans = [[0 for i in range(len(pattern))] for j in range(len(pattern[0]))]
for i in range(len(pattern[0])):
for j in range(len(pattern)... | The code generates all 8 possible rotations and reflections of the input pattern, along with corresponding transformed click, flag, and mine-exclusion patterns. It then processes each transformed version using the processPattern function to handle symmetrical variations in a Minesweeper-like scenario. | def solvePattern(pattern, clickPattern, flagPattern, minesExcluded):
rowLen = len(pattern)
colLen = len(pattern[0])
patterns = []
mineExcludedList = []
clickPatterns = []
flagPatterns = []
mineExcludedList.append(minesExcluded)
clickPatterns.append(clickPattern)
flagPatterns.append(f... |
def getMonths(day1):
""" Finds the relevant table codes to pull data given a date
Parameters:
day1 (pandas datetime): a time that is representative of the data you would like to grab
Returns:
str: the table code for the month of the given data
str: the table code for the mo... | The code generates accurate expected bias ("OFFSET") for each meter combination in the input DataFrame by validating historical data across multiple time windows. It prioritizes data from 2 days before the median V1 measurement, then iteratively shifts backward by 1 day up to 13 days if initial validation fails. If no ... | def getOffsets(cell_data):
"""Creates a validated offset from the best availible data.
Parameters:
cell_data (pandas DataFrame): The Cell Data for which offsets are being created. Must include Columns = ['LINE_NO', 'V1_MEASURE_DATE', 'V2_MEASURE_DATE', 'V1_MACHINE', 'V2_MACHINE', 'METER']
'LINE_NO'... |
def train_task(self, idx, task_dict=None):
context_images, context_labels, target_images, target_labels = \
self.imagenet_subset.get_batch(phase='train', idx=idx)
context_images = torch.from_numpy(context_images).permute(0,3,1,2).cuda(0).float()
context_labels = torch.argmax(... | This code trains a model using cluster refinement parameters, validates periodically, and saves checkpoints. It handles training, validation, and testing modes, adjusting refinement steps for train/test phases. During training, it accumulates losses/accuracies, optimizes parameters, and logs progress. In 'train_test' m... | def run(self):
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
validation_accuracy = 0
with tf.compat.v1.Session(config=config) as session:
if self.args.mode == 'train' or self.args.mode == 'train_test':
self.model.set_cluster_refine... |
def squareCaptured(self, r, c):
self.whiteToMove = not self.whiteToMove
oppMoves = self.getAllPossibleMoves()
self.whiteToMove = not self.whiteToMove
for move in oppMoves:
if move.end_row == r and move.end_col == c:
return True
return False
def getKing... | This code generates legal castling moves for a chess king based on current player's turn and castling rights. It checks if the king's square is not captured, then adds kingside or queenside castling moves to the 'moves' list if the respective castling rights (wks/wqs for white, bks/bqs for black) are enabled. | def getCastleMoves(self, r, c, moves):
if self.squareCaptured(r,c):
return
if (self.whiteToMove and self.currentCastlingRights.wks) or (not self.whiteToMove and self.currentCastlingRights.bks):
self.getKingsideCastleMoves(r, c, moves)
if (self.whiteToMove and self.curren... |
def getAllPossibleMoves(self):
moves = []
for r in range(len(self.board)):
for c in range(len(self.board[r])):
turn = self.board[r][c][0]
if (turn == 'w' and self.whiteToMove) or (turn == 'b' and not self.whiteToMove):
piece = self.board[r]... | This function generates valid chess moves by checking all possible moves, validating them against check conditions, handling castling rights, en passant, and determining checkmate/stalemate. It iterates through potential moves, simulates each, and removes invalid ones, then restores game state before returning the list... | def getValidMoves(self):
for log in self.castleRightsLog:
print([log.wks, log.bks, log.wqs, log.bqs])
tempEnpassantPossible = self.enpassantPossible
tempCastleRights = CastleRights(self.currentCastlingRights.wks, self.currentCastlingRights.bks,
... |
def knn(v, v_neighbor_l, k=1):
similarity_l = []
for ele in v_neighbor_l:
cos_similarity = cosine_similarity(v,ele)
similarity_l.append(cos_similarity)
sorted_idxs = np.argsort(similarity_l)
k_idx = sorted_idxs[-k:]
return k_idx
def find_k_nearest_neighbor_universe(s... | The code computes the accuracy of two nearest neighbor methods ("universe" or "flipped") by comparing their predicted points (after adding 50.00) with true labels derived from k-nearest neighbors. It counts matches using a `check` function, calculates accuracy as the ratio of correct matches, and prints the result as a... | def compute_accuracy(self,method,k = 3,id_query = -1,point_query = None):
#implement time in python
if id_query != -1:
point_query = self.points[id_query]
k_l = knn(point_query,self.points,k)
label_l = [self.points[ele] + 50.00 for ele in k_l]
if metho... |
def create_my_scene(self):
tableHeight = 0.05
tableSize = 0.5
table1_position = [-0.1,0,0]
self.add_table(width=0.25,height=0.6,position=table1_position,name="table1")
leg_size = 0.025
self.add_leg([ -0.2,-0.3 +leg_size/2 ,-tableHeight+table1_position[2]],0.25,"leg5")
... | The code initializes a robot control system using MoveIt and ROS, setting up a robot commander, planning scene, and move groups for an arm and gripper. It configures ROS services for tasks like path planning, resetting, and waypoint management, while loading predefined waypoints from parameters. The class also initiali... | def __init__(self):
super(RobotPX, self).__init__()
moveit_commander.roscpp_initialize(sys.argv)
# rospy.init_node('RobotPX',anonymous=True,log_level=rospy.DEBUG)
rospy.init_node('RobotPX',anonymous=True)
robot_name = "px100"
self.robot_name = robot_name
self.dof ... |
def attach_box(self):
grasping_group = 'interbotix_gripper'
touch_links = self.robot.get_link_names(group=grasping_group)
self.scene.attach_box(self.eef_link, "graspObject", touch_links=touch_links)
return self.wait_for_state_update(objName="graspObject",box_is_attached=True, box_is_know... | The main task of the code is to execute a series of predefined waypoints for a robotic arm, planning and executing each movement while adjusting the gripper state (open/close) based on waypoint specifications. It runs in a loop until reset, handling path planning errors and resetting the system after completing all way... | def srvf_follow(self,SetBoolRequest):
if(SetBoolRequest.data):
self.loopa = True
while(self.loopa):
for point in self.waypoints:
# execute whole planning
rospy.logdebug(point)
self.group.set_pose_target(point.pose)
p... |
def unhide(self):
if self.sent_ctrl_mode == "in_unhide":
self.sent_ctrl_mode = "in_hide"
if not self.is_hidden:
return
print(self.prompt + self.current_str.replace("\t", " ") + "\b"*(len(self.current_str[self.current_cursor:].replace("\t", " "))), end="", flush=True)
self.is_hidden = False
def use... | This code implements a custom input handler with features like password masking (hide/unhide), command history, and special key processing. It processes user input character-by-character, updates the display dynamically, and stores entered commands in a history file. The function returns the input string upon pressing ... | def input(self, prompt = ""):
self.prompt = prompt
if self.sent_ctrl_mode == "in_unhide":
self.unhide()
elif not self.is_hidden:
print(self.prompt + self.current_str.replace("\t", " ") + "\b"*(len(self.current_str[self.current_cursor:].replace("\t", " "))), end="", flush=True)
if self.history_f... |
def check_cmd(self, cmd):
if not isinstance(cmd, str):
return cmd, "write"
temp_cmd = cmd.strip(" ").strip("\t")
cmd_type = ""
if len(temp_cmd) >= 2:
if temp_cmd[0] == ":":
cmd = temp_cmd[1:].replace("\\!", "!").replace("\\:", ":")
cmd_type = "internal"
elif temp_cmd[0] == "!":
cmd = temp_... | The code executes commands based on their type: system commands using os.system, internal commands via internal_exec, and other commands by writing them with an end character if they are strings, or directly writing them otherwise. | def exec(self, cmd):
cmd, cmd_type = self.check_cmd(cmd)
if cmd_type == "system":
os.system(cmd)
elif cmd_type == "internal":
self.internal_exec(cmd)
else:
if isinstance(cmd, str):
self.write(cmd + self.end)
else:
self.write(cmd) |
def fetch_id(self, table_name: str, where: dict = {}, id_column: str = "id", operator: str = "AND") -> int:
return self.fetch_value_where(table_name, where, id_column, operator)
def insert(self, table_name: str, data: dict = {}) -> int:
if data:
columns = ", ".join(data.keys())
v... | This function performs a conditional delete, insert, or update operation on a database table. It checks if records exist using `where_columns` and `criteria_columns`. If no existing record is found, it inserts new data. If a record exists, it deletes it if no criteria are provided, otherwise updates it. The function re... | def delupsert(
self, table_name: str, data: dict, where_columns: tuple, criteria_columns: tuple = [], criteria: tuple = []
) -> int:
if not criteria:
criteria = [data[column] for column in criteria_columns]
where = {column: data[column] for column in where_columns}
id = s... |
def fetch_id(self, table_name: str, where: dict = {}, id_column: str = "id", operator: str = "AND") -> int:
return self.fetch_value_where(table_name, where, id_column, operator)
def insert(self, table_name: str, data: dict = {}) -> int:
if data:
columns = ", ".join(data.keys())
v... | This function performs an upsert operation: if an 'id' is provided or can be derived from 'where_columns', it updates the existing record in the specified table; otherwise, it inserts a new record. It returns the record's ID after either insertion or update, ensuring data consistency by leveraging existing keys or gene... | def upsert(self, table_name: str, data: dict, where_columns: tuple = (), id: int = None) -> int:
if id is None and where_columns:
where = {column: data[column] for column in where_columns}
id = self.fetch_id(table_name, where)
if id is None:
id = self.insert(table_na... |
def welcome():
'''
Purpose: To generate a random name from the list and print out
a welcome message
Parameters: None
Returns: None
'''
# Chooses a random integer between 0 and 9
num = randint(0, 9)
# Sets the name variable equal to the name which corresponds to the above selected i... | The main task of the code is to execute a sequence of functions—welcome(), order_type(), catalog(), and order_merch()—to orchestrate a process, likely for order management or user interaction in a system. It acts as a controller to sequentially trigger these functions without parameters or return values. | def main():
'''
Purpose: To run all functions
Parameters: None
Returns: None
'''
welcome()
order_type()
catalog()
order_merch() |
def feed_forward(self):
#Calculating hidden neurons
for j in range(self.hidden_dim):
self.z1[j] = np.dot(self.weights1[j], self.input)
self.hidden[j] = self.sigmoid(self.z1[j])
#Calculating output neurons
for i in range(self.output_dim):
self.... | The main task of the code is to train a neural network model using stochastic gradient descent. It iterates over training data for a specified number of epochs, performing forward propagation to compute predictions, calculating cost and accuracy for each training example, executing backpropagation to update weights, an... | def fit_data(self, x_train, y_train, epochs):
cost = [[]]
accuracy = [[]]
for epoch in range(1, epochs + 1):
cost.append([])
accuracy.append([])
print('\n==============Epoch ', epoch, "=============")
for number in range(len(x_train)):#Fo... |
def parse_args():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--task_name", choices=['mnist', 'fashion-mnist', 'svhn', 'gtsrb'], required=True)
parser.add_argument("--width", type=int, required=True)
parser.add_argument("--num_layers", ty... | The main task of the code is to train a multi-layer perceptron (MLP) model for continual learning on a sequence of tasks. It initializes model parameters, sets up device configuration, loads datasets, and trains the model while logging accuracy, forgetting, and learning performance. The results are recorded in a file f... | def main():
args = parse_args()
torch.manual_seed(args.seed)
device = set_device()
datasets = get_continual_learning_tasks(args.task_name)
model = get_mlp_model(args.task_name, args.num_layers, args.width)
model.to(device)
logging.basicConfig(filename=f'{args.task_name}_{args.num_layers}l_{a... |
def is_horizontal_line(self, line_segment):
"""
function that returns true if the line segment has a
length greater than 10 and an angle of 0 or 180 degrees
"""
dist = self.distance_between_two_points(line_segment)
angle = self.angle_of_line_segment(line_segment)
... | The code's main task is to evaluate if an action (second line segment) forms a target shape (horizontal, vertical, slash, etc.) when combined with the first line segment. It updates the environment state, checks shape validity at specific steps, and returns a reward (1/-1) and termination flag based on success/failure,... | def step(self, action):
self.state[1:5] = self.state[5:9]
self.state[5:9] = action
self.current_step += 1
self.line_segments = np.reshape(self.state[1:], (2, 2, 2))
if self.current_step == 1:
if self.target_class == 0:
if self.is_horizontal_line(self... |
def analyzeCigUse(self, response='Current', by_gender=False):
###
### Analyze cigarette use by education level. Can also return by education and gender if by_gender = True
### Returns pandas dataframe. Writes df to csv.
###
### Parameters:
###
... | The main task of the code is to generate and organize Pandas DataFrames and Matplotlib plots for tobacco use, cessation, and smokeless tobacco analysis across response categories (Current, Ever, Frequent) and gender. It iterates through parameters, calls analysis/plotting methods, and compiles results into structured d... | def analyze(self):
### Returns a dictionary with the Pandas DFs and Matplitlib Plots
### Appends each df and plot to two dictionaries -> 'dataframes' & 'plots' for further use in Python if required.
response_values = ['Current', 'Ever', 'Frequent']
gender_values = [True,False]
ce... |
def start_blinking(self):
if not self.is_blinking:
self.is_blinking = True
self.blink()
def stop_blinking(self):
self.is_blinking = False
self.update_timer_label()
def timer_tick(self):
if self.is_timer_running and not self.is_paused:
if self.is_rest_t... | This method toggles the pause state of a timer. If the timer is running, it alternates between paused and active states. When paused, it initiates blinking and cancels the existing timer; when unpaused, it stops blinking and resumes the timer by calling `timer_tick()`. The function manages visual feedback (blinking) an... | def toggle_pause(self, event):
if self.is_timer_running:
self.is_paused = not self.is_paused
if self.is_paused:
self.start_blinking()
if self.timer_id:
self.master.after_cancel(self.timer_id) # Cancel any existing timer_tick
... |
def visualize_tour(tour, style="bo-"):
if len(tour) < 1000:
plt.figure(figsize=(15,10))
start = tour[0:1]
visualize_segment(tour + start, style)
visualize_segment(start, "rD")
def name(algorithm):
return algorithm.__name__.replace("_tsp","")
def distance_tour(tour):
return sum(distance_p... | The code evaluates a Traveling Salesman Problem (TSP) algorithm by executing it on a list of cities, measuring its runtime, verifying the solution's validity (all cities included), visualizing the tour, and reporting the tour length and execution time. It serves as a benchmarking framework for comparing TSP algorithms'... | def tsp(algorithm, cities):
t0 = time.perf_counter()
tour = algorithm(cities)
t1 = time.perf_counter()
assert Counter(tour) == Counter(cities)
visualize_tour(tour)
print("{}: {} cities => tour length: {:.0f} in {:.3f} seconds".format(name(algorithm), len(tour), distance_tour(tour), t1-t0)) |
def zero_log(self,
x: torch.Tensor,
dim: Union[int, Tuple[int]] = -1) -> torch.Tensor:
dist = self.dist0(x, dim=dim, keepdim=True)
nomin = 1.0 / self.curvature * self.inner0(x, keepdim=True) * self.sqrt_c
d = x.size(dim) - 1
nomin = torch.cat((nomin + x.... | This function performs parallel transport of a tensor `x` along a manifold to a target point `to`, adjusting `x` by subtracting a component aligned with the logmap of `to`. It calculates the inner product of the logmap and `x`, scales it by the squared distance between `to` and the origin, then subtracts this scaled te... | def parallel_transport0(self,
x: torch.Tensor,
to: torch.Tensor,
dim: int = -1) -> torch.Tensor:
logmap = self.zero_log(to, dim=dim)
nomin = self.inner_product(logmap, x, keepdim=True)
denominator = self.dist0(to... |
def parallel_transport0(self,
x: torch.Tensor,
to: torch.Tensor,
dim: int = -1) -> torch.Tensor:
logmap = self.zero_log(to, dim=dim)
nomin = self.inner_product(logmap, x, keepdim=True)
denominator = self.dist0(to... | This function performs parallel transport of a tensor `x` along a manifold, adjusting it based on the logarithmic map between points `from_` and `to_`. It computes a correction term using inner products and distances, then subtracts it from `x` to align the vector with the tangent space at `to_`, ensuring geometric con... | def parallel_transport(self,
x: torch.Tensor,
dim: Union[int, Tuple[int]] = -1,
from_: Optional[torch.Tensor] = None,
to_: Optional[torch.Tensor] = None) -> torch.Tensor:
if from_ is None:
ret... |
def preprocess_line(target):
target = target.replace('@params', '@param')
target = target.replace('@returns', '@return')
return target
def process_returns(returns):
if returns is None:
return None
regex = re.compile(
'@return\s*(?P<type>{.+})\s*-\s*(?P<desc>.+)',
)
arg_nam... | The function processes a documentation block by extracting parameters, return values, and description content. It parses lines starting with '@param' and '@return', appending subsequent lines to the last parameter or return value. Remaining lines form the description. Finally, it formats parameters, returns, and descri... | def transform_extract(extract):
content, params, returns = [], [], None
for line in extract.content:
line = preprocess_line(line.strip())
if line.startswith('@param'):
params.append(line)
continue
if line.startswith('@return'):
returns = line
... |
def strToFloat(x):
if re.search("M$", x) != None:
return float(re.sub('M','',x))*1000000
elif re.search("K$", x) != None:
return float(re.sub('K','',x))*1000
def roc(arr, window_size):
roc_array = []
i = 0
while i < len(arr) - window_size + 1:
# Store elements from i to i+wi... | The main task of the code is to fetch historical stock price data for AirAsia from a website, extract specific financial metrics, and append the data to a CSV file if the date is not already present. It includes date conversion, web scraping, data validation, and feature engineering (e.g., calculating logarithmic volum... | def checkSharePrice(x):
# turn string date to date format
today = datetime.strptime(str(x), "%m/%d/%Y")
# send request to the website
link = "https://www.investing.com/equities/airasia-bhd-historical-data"
req = Request(link, headers={'User-Agent':'Mozilla/5.0'})
webpage = urlopen(req).rea... |
def truncated_normal(mean=0.5, sd=1.0, low=0, upp=1):
return truncnorm((low - mean) / sd, (upp - mean) / sd, loc=mean, scale=sd).rvs()
def set_IS(self):
if self.args.is_const_IS:
self.I = self.args.const_I
self.S = self.args.const_S
else:
self.I = truncated_normal... | This code initializes an object with parameters for a simulation or optimization process, setting up innovation selection from a pool, tracking historical innovation and outcome data, and preparing to update states iteratively. It configures a truncated normal distribution, initializes counters, and calls methods to se... | def __init__(self, args, inno_pool: list) -> None:
self.args = args
self.K = truncated_normal()
self.inno_pool = inno_pool
self.inno = np.random.choice(self.inno_pool)
self.inno_his = list() # with memory of the past M iterations
self.n_ti = 0
self.set_IS... |
def _get_migrate_repo_path(branch):
abs_path = os.path.abspath(
os.path.join(
os.path.dirname(sql.__file__),
'legacy_migrations',
f'{branch}_repo',
)
)
if not os.path.isdir(abs_path):
raise exception.MigrationNotProvided(sql.__name__, abs_path)
... | The function validates the upgrade order of migration repositories to ensure they follow a specific sequence: expand's version must be greater than or equal to migrate's, and migrate's version must be greater than or equal to contract's. It checks if the target version for the current branch aligns with the required or... | def _validate_upgrade_order(branch, target_repo_version=None):
"""Validate the state of the migration repositories.
This is run before allowing the db_sync command to execute. Ensure the
upgrade step and version specified by the operator remains consistent with
the upgrade process. I.e. expand's versio... |
def expand_schema():
"""Expand the database schema ahead of data migration.
This is run manually by the keystone-manage command before the first
keystone node is migrated to the latest release.
"""
_validate_upgrade_order(EXPAND_BRANCH)
_db_sync(branch=EXPAND_BRANCH)
def migrate_data():
"""... | This function performs an offline database synchronization by expanding the schema, migrating data, and contracting the schema to update the database to the latest version. It no longer supports specifying a target version, as version-specific migrations are deprecated. The process ensures full schema and data updates ... | def offline_sync_database_to_version(version=None):
"""Perform and off-line sync of the database.
Migrate the database up to the latest version, doing the equivalent of
the cycle of --expand, --migrate and --contract, for when an offline
upgrade is being performed.
If a version is specified then o... |
def text_preprocess():
# creating a new clean text column for each text
df["text_clean"] = df["text"].apply(
lambda x: prep.utils_preprocess_text(x, flg_stemm=False, flg_lemm=True, lst_stopwords=lst_stopwords))
df.head()
# extracting and storing hashtags from each tweet
df["tags"] = df["text... | The main task of the code is to analyze tweets by preprocessing text data, generating a word cloud of cleaned text, creating a bar chart for trending hashtags, and building a machine learning model. It processes text, visualizes key terms, and constructs a predictive model for tweet analysis. | def tweets_analytics():
text_preprocess()
word_cloud_of_cleaned_text(unicode_clean_text, ngram_range=(1, 1))
frequency_bar_chart_of_trending_hashtags(unicode_tags, ngram_range=(1, 1))
build_model() |
def get_log_history(
all: bool, commits: List[str], head_commit: str
) -> List[Dict[str, str]]:
"""Given all is True, returns a history information
of all existing branches . Otherwise, returns only
the history of the current active branch.
"""
history = []
if all:
for commit in... | The main task of the code is to print a branch history, optionally combining all branches' history or displaying it as a graph. It validates the reference file, retrieves commit data, constructs the history, adds branch pointers, prints the log, and generates a graph if requested. | def log(graph=False, all=False):
"""Prints a branch history. If 'all' options is used,
the history of all branches combined is printed.
If 'graph' is used, a graph of the history is shown
to the user.
"""
try:
helpers.validate_ref_file_exists()
except CommitRequiredError as err:
... |
def predict(self, Q_dict, state):
# Chosing which action we are going to take.
qvals = self.q(Q_dict, state)
actions = jnp.where(qvals == jnp.max(qvals))[0]
return jax.random.choice(key=self.key, a=actions)
def makeHashable(self, state):
if isinstance(state, (jnp.ndarray, np.ndar... | This code trains a Q-learning agent to learn optimal actions in an environment by iterating through episodes, updating Q-values using the Bellman equation, and checking for convergence when the agent can win from all starting states. It tracks cumulative rewards, win rates, and stops early if convergence is achieved, t... | def train(self, **kwargs):
# params passed throug the **kwargs are
# 1. discount: float64
# 2. exploration_rate: float64
# 3. learning_rate: float64
# 4. episodes: int
# 5. datetime: int
discount = kwargs.get("discount", 0.90)
exploration_rate = k... |
def load_random_from(self, paths):
"""
Chooses a random path from a list of image paths and reads the
corresponding image. Path must be in the format
?????-???-???-{_id}-???-???.png as the element id is retrieved
from the path.
:param paths: List of paths of images.
... | The main task of the code is to generate and place multiple randomized shapes into an output image. It iterates over `self.n_shapes`, randomly selects shapes, applies transformations (flipping, scaling, rotation), and attempts to place each modified shape in the image to create a composite output. | def add_shapes(self):
"""
Parametrizes as many shapes as indicated in self.n_shapes and tries
to place them into the output image.
"""
for shape_index in range(self.n_shapes):
# Choose a random shape and read it.
element_id, shape_img = self.load_random_fr... |
def __draw_randomized_limits(self):
"""
Draws a rectangle in the output image signaling the area occupied
by the real diagram (randomized at initialization).
"""
cv2.rectangle(self.output_img, (self.x0, self.y0),
(self.x0 + self.rwidth, self.y0 + self.rheigh... | The code's main task is to generate an output image containing an artificial diagram composed of available elements by adding shapes, connections, and optionally texts. If debug mode is enabled, it first draws randomized limits. The method returns the generated image as `self.output_img` | def generate(self):
"""
Generates the output image containing an artificial diagram composed
by a set of the available elements.
:return: Output image with the generated diagram.
"""
if self.debug:
self.__draw_randomized_limits()
self.add_shapes()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.