dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def getCards(state, category):
return numpy.where(state[category] == 1)
def length(cards):
return cards[0].size
def _updateAttackerAndDefender(self, newAttacker):
newDefender = self._nextPlayer(newAttacker)
self.attacker = newAttacker
self.defender = newDefender
def _pickUpCards(self):
... | The main task of the code is to handle the aftermath of a successful defense in a game. It burns all open and closed attacks and defenses, resets their states to zero, marks them as burned, updates the attacker and defender roles, increments the turn counter, and triggers card pickup. This ensures game state consistenc... | def _successfulDefence(self):
# Burn closed attacks and defences, but also burn any open attacks -
# the defender might just have used their last cards.
print(f'Successful defence by player {self.defender}!')
for category in [self.openAttacks, self.closedAttacks, self.defences]:
... |
def _playerState(self, player):
# Attacker and defender should be relative to this player.
attacker = (self.attacker - player) % self.numberOfPlayers
defender = (self.defender - player) % self.numberOfPlayers
attacker = numpy.full((4, 13), attacker, dtype=int)
defender = numpy.fu... | The function handles a player's concession in a game by validating the action, updating the game state to transfer cards from attack categories to the player's possession, burning leftover open attacks, and progressing the turn. It ensures consistency by checking state equality, applying rules via assertions, and updat... | def concede(self, player, playerState, attacksToConcede):
with self.lock:
latestPlayerState = self._playerState(player)
if not numpy.array_equal(playerState, latestPlayerState):
print(f'Player {player} conceding based on old information - reject this action.')
... |
def hasCards(self, state):
return numberOfCards(state, self.cards) > 0
def hasLost(self, state):
return numberOfCards(state, self.cards) + numberOfCards(state, self.burned) == 52
def getPossibleActions(self, state):
# Must only use the state to determine actions, nothing else.
openAttack... | The play method repeatedly selects and executes random valid actions from available options while the player has cards and hasn't lost, updating the game state after each action. The loop terminates when the player either runs out of cards or loses. If the player hasn't lost, it notifies the game that the player has co... | def play(self):
state = self.game.getState(self.name)
while self.hasCards(state) and not self.hasLost(state):
actions = self.getPossibleActions(state)
action = random.choice(actions)
action()
# time.sleep(random.uniform(3, 5))
state = self.game... |
def _playerState(self, player):
# Attacker and defender should be relative to this player.
attacker = (self.attacker - player) % self.numberOfPlayers
defender = (self.defender - player) % self.numberOfPlayers
attacker = numpy.full((4, 13), attacker, dtype=int)
defender = numpy.fu... | This function handles a player's defense action in a card game by validating the move, updating game state, and triggering consequences. It checks if the player's state is current, verifies card validity (suit/value/trump), updates card statuses (removing from open attacks, adding to defenses), and triggers a successfu... | def defend(self, player, playerState, defendingCard, attackingCard):
with self.lock:
latestPlayerState = self._playerState(player)
if not numpy.array_equal(playerState, latestPlayerState):
print(f'Player {player} defending based on old information - reject this action.')
... |
def _playerState(self, player):
# Attacker and defender should be relative to this player.
attacker = (self.attacker - player) % self.numberOfPlayers
defender = (self.defender - player) % self.numberOfPlayers
attacker = numpy.full((4, 13), attacker, dtype=int)
defender = numpy.fu... | This function handles a player's decision to decline an attack. It checks if the player's state is current, updates decline status, and triggers a successful defense if all active players decline and no attacks remain open. | def declineToAttack(self, player, playerState):
with self.lock:
latestPlayerState = self._playerState(player)
if not numpy.array_equal(playerState, latestPlayerState):
print(f'Player {player} declining based on old information - reject this action.')
retur... |
def validate_trie(attempts):
if(attempts >= MAX_ATTEMPTS):
raise Exception("Tries exceeded")
def tally(target, guess):
validate_length(guess)
return [tally_for_position(position, target, guess) for position in range(0, WORD_SIZE)]
def determine_message(attempts, tally_result):
if all(match == Matches.EXACT... | The main task of the code is to process a player's guess in a word game. It validates the guess's spelling, evaluates the guess against the target word to generate a tally result, determines the game's current status and message, and returns updated game state data including attempts, tally result, game status, and fee... | def play(attempts, target, guess, is_spelling_correct=lambda word: True):
validate_trie(attempts)
if not is_spelling_correct(guess):
raise Exception("Not a word")
tally_result = tally(target, guess)
message = determine_message(attempts, tally_result)
game_status = determine_game_status(attempts, ... |
def purge_old_requests(self) :
"""remove from data property all request data considered as expired"""
self.speak(f"purging old request among {len(self.data)} cached requests")
now = datetime.datetime.now()
for index in range(len(self.data)-1,-1,-1) :
time = self.data[index]['... | This method handles API requests by checking for freezes, cache hits, or overload status. If none, it sends a GET request, caches the response, logs details, and returns HTTP status codes or custom 9xx codes. It stores request data including URL, timestamp, status, and content in the 'data' property for tracking and re... | def requests(self, endpoint, filter="", pseudo=None, id=None) :
"""
return the response status code (int) or one of the following custom status code (int) :
- 901 > API manager has been freezed
- 902 > the asked request has been found in cache
- 903 > the API is overl... |
def get_model(args):
if args.name == 't5-small':
config = AutoConfig.from_pretrained('t5-small')
model = T5Model(config).to(args.device)
args.seq_length = config.n_positions # max sequence length
elif args.name == 'gpt2':
config = GPT.get_default_config()
config.model_type = 'gpt2'
config.v... | The code initializes a machine learning model with a specified seed, applies tensor parallelism (tp) to the model based on given arguments, and then trains the model using the provided configuration. The function is structured to handle model setup, parallelism, and training phases, with placeholder comments indicating... | def run(args):
torch.manual_seed(args.seed)
model, config = get_model(args)
# 1. tp
model = tp(model, args)
train(args, model, config)
# 2. pp
#model = pp(model, args)
pass |
def fetchResponse(url, choice):
response = requests.get(url)
print(response)
print(switch)
print(switch[h2])
if(response.ok):
jData = json.loads(response.content)
if(choice == "deviceInfo"):
deviceInformation(jData)
elif(choice == "Switchlinkinfo"):
Sw... | The function `loadbalance()` retrieves network topology and switch latency data, computes routing paths, fetches link costs, and adds flows to optimize traffic distribution in a software-defined network (SDN), aiming to balance network load and improve efficiency. | def loadbalance():
linkURL = "http://localhost:8080/wm/topology/links/json"
fetchResponse(linkURL, "Switchlinkinfo")
computeRoute()
url = ('http://localhost:8080/wm/core/switch/all/flow/json')
fetchResponse(url, "getswitchlatency")
getlinkLatency()
fetchLinkCost()
addFlow() |
def buildheap(self):
for i in range(self.n//2, -1, -1):
self.heapify(i)
def swap(self, l, r):
self.a[l], self.a[r] = self.a[r], self.a[l]
def heapify(self, i):
left_child = 2*i + 1
right_child = 2*i + 2
if ((left_child < self.n) and (self.a[left_child] > self... | The code implements the heap sort algorithm by first building a max heap and then repeatedly extracting the maximum element to sort the array in ascending order. | def sort(self):
self.buildheap()
for i in range(self.n -1 , 0, -1):
self.swap(0,i)
self.n -= 1
self.heapify(0) |
def train_loop(self, lam=None):
'''
Trains the model for one epoch (a single pass through the data).
:lam: L1 regularization constant for the Granger filter(s)
return: None
'''
self.model.train()
self.dataset.train_mode()
size, n_batches, batch_size = le... | This method trains a model for a specified number of epochs, applying L1 regularization (if provided) during training. It tracks training/validation errors, saves the model periodically, and prints progress/ timing details. The loop increments the epoch counter, executes the training loop, handles model saving, and rec... | def run_training(self, epochs, lam=None):
'''
Train the model for a specified number of epochs.
:lam: L1 regularization constant for the Granger filter(s)
return: None
'''
# lam tells us that the model has weights to be custom regularized with its regularize() function
... |
def hbl_GreetingIntent(intent_request):
session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {}
return close(
session_attributes,
'Fulfilled',
{
'contentType': 'PlainText',
'content': 'Hi there, Please ty... | This code routes incoming intent requests to specific handler functions based on the intent name. It checks the 'intent_name' from the request and executes the corresponding function (e.g., hbl_GreetingIntent, hbl_ThankYouIntent) if matched. If no match is found, it raises an exception indicating unsupported intent. Th... | def dispatch(intent_request):
intent_name = intent_request['currentIntent']['name']
# Dispath the intent
if intent_name == 'hbl_GreetingIntent':
return hbl_GreetingIntent(intent_request)
elif intent_name == 'hbl_ThankYouIntent':
return hbl_ThankyouIntent(intent_request)
... |
def RandomMotifs(Dna, k, t):
kmers = []
s = len(Dna[0])
for string in Dna:
m = random.randint(0, s - k)
kmer = string[m:m + k]
kmers.append(kmer)
return kmers
def ProfileWithPseudocounts(Motifs):
t = len(Motifs) + 4
k = len(Motifs[0])
profile = {}
profile = CountW... | The GibbsSampler function iteratively refines a set of motifs by randomly selecting a position, generating a new motif using a profile derived from the remaining motifs, and updating the best motifs if the new set has a lower score. It aims to find optimal motifs in DNA sequences through probabilistic sampling and pseu... | def GibbsSampler(Dna, k, t, N):
BestMotifs = [] # output variable
Motifs = RandomMotifs(Dna, k, t)
BestMotifs = Motifs
for j in range(N):
i = random.randint(0, t-1)
Motifs.pop(i)
Profile = ProfileWithPseudocounts(Motifs)
Motifs.insert(i, ProfileGeneratedString(Dna[i], Pro... |
def ProfileWithPseudocounts(Motifs):
t = len(Motifs) + 4
k = len(Motifs[0])
profile = {}
profile = CountWithPseudocounts(Motifs)
for key in profile:
for j in range(k):
profile[key][j] = profile[key][j] / t
return profile
def ProfileMostProbableKmer(text, k, profile):
kmer... | The main task of the code is to find the best set of k-length motifs across t DNA sequences using a greedy algorithm with pseudocounts. It initializes candidate motifs, iterates through possible positions in the first DNA string, builds motifs for subsequent sequences using a profile with pseudocounts, and updates the ... | def GreedyMotifSearchWithPseudocounts(Dna, k, t):
BestMotifs = []
for i in range(0, t):
BestMotifs.append(Dna[i][0:k])
n = len(Dna[0])
for i in range(n - k + 1):
Motifs = []
Motifs.append(Dna[0][i:i + k])
for j in range(1, t):
P = ProfileWithPseudocounts(Motif... |
def Profile(Motifs):
t = len(Motifs)
k = len(Motifs[0])
profile = {}
profile = Count(Motifs)
for key in profile:
for j in range(k):
profile[key][j] = profile[key][j] / t
return profile
def ProfileMostProbableKmer(text, k, profile):
kmer = text[0:k]
t = len(text)
m... | (GreedyMotifSearch identifies the best set of k-length motifs from t DNA strings by iteratively selecting the most probable k-mers based on a profile matrix. It initializes with the first k-mers, then for each possible starting position in the first DNA string, constructs candidate motifs using profile-based selection ... | def GreedyMotifSearch(Dna, k, t):
BestMotifs = []
for i in range(0, t):
BestMotifs.append(Dna[i][0:k])
n = len(Dna[0])
for i in range(n - k + 1):
Motifs = []
Motifs.append(Dna[0][i:i + k])
for j in range(1, t):
P = Profile(Motifs[0:j])
Motifs.appen... |
def RandomMotifs(Dna, k, t):
kmers = []
s = len(Dna[0])
for string in Dna:
m = random.randint(0, s - k)
kmer = string[m:m + k]
kmers.append(kmer)
return kmers
def ProfileWithPseudocounts(Motifs):
t = len(Motifs) + 4
k = len(Motifs[0])
profile = {}
profile = CountW... | The function `RandomizedMotifSearch` identifies the best set of motifs (subsequences of length `k`) from `t` DNA sequences by iteratively refining random initial motifs. It uses pseudocounts to build a probability profile, generates new motifs based on this profile, and updates the best motifs if the new set has a lowe... | def RandomizedMotifSearch(Dna, k, t):
M = RandomMotifs(Dna, k, t)
BestMotifs = M
while True:
Profile = ProfileWithPseudocounts(M)
M = Motifs(Profile, Dna)
if Score(M) < Score(BestMotifs):
BestMotifs = M
else:
return BestMotifs |
def ComputingFrequencies(Text, k):
FrequencyArray = []
for i in range(4 ** k):
FrequencyArray.append(0)
for i in range(len(Text) - k + 1):
Pattern = Text[i:i + k]
j = PatternToNumber(Pattern)
FrequencyArray[j] += 1
return FrequencyArray
def PatternToNumber(Pattern):
i... | The code identifies all k-mers that appear at least t times in any L-length substring of the genome. It uses a sliding window approach, updating frequency counts efficiently as the window moves. A Clump array tracks qualifying k-mers, which are later converted to patterns and returned. | def BetterClumpFinding(Genome, k, L, t):
FrequentPatterns = []
Clump = []
d = len(Genome)
for i in range(4**k):
Clump.append(0)
Text = Genome[0:L]
FrequencyArray = ComputingFrequencies(Text, k)
for index in range(4 ** k):
if FrequencyArray[index] >= t:
Clump[index... |
def player(board):
countO = 0
countX = 0
for y in [0, 1, 2]:
for x in board[y]:
if x == "O":
countO = countO + 1
elif x == "X":
countX = countX + 1
if countO >= countX:
return X
elif countX > countO:
return O
def actions... | The code implements the minimax algorithm to determine the optimal move for a player in a game like Tic-Tac-Toe. It alternates between maximizing (for the current player's turn) and minimizing (for the opponent's turn) scores by recursively evaluating all possible moves. The function iterates through available moves, s... | def minimax(board):
isMaxTurn = True if player(board) == X else False
bestMove = None
if isMaxTurn:
bestScore = -math.inf
for move in actions(board):
result(board, move)
score = minimax_helper(board)
board[move[0]][move[1]] = EMPTY
if (score > ... |
def collectData(st):
download = st.download()
upload = st.upload()
servernames = []
st.get_servers(servernames)
ping_results = st.results.ping
row_data = formatData(download, upload, ping_results)
writeToDatabase(row_data)
def formatData(download, upload, ping):
date_time = (str(datetime... | The main task of the code is to perform a speed test using the `speedtest` library, collect the data via `collectData(st)`, and handle exceptions by inserting a malformed record (-1 values) into a database using `writeToDatabase(bad_row)` if the speed test fails. | def main():
try:
st = speedtest.Speedtest()
collectData(st)
except:
bad_row = formatData(-1,-1,-1)
writeToDatabase(bad_row) |
def get_actions(self, t):
"""
Get all bandits' decision in parallel at time t
"""
que = queue.Queue(maxsize=len(self.bandits))
for i in range(len(self.bandits)):
thr = Thread(
target=lambda q, arg: q.put(
self.get_action(arg)
... | The code simulates a multi-armed bandit process over `n` time steps, generating actions, rewards, and environment-level rewards iteratively. After simulation, it prints the most frequent hiring outcome for each bandit using `Counter`, analyzing the distribution of hires across bandits. | def run(self):
for t in tqdm(range(self.n)):
self.get_actions(t)
self.generate_rewards(t)
self.compute_environment_level_reward(t)
# print("number of time using lobbyist", self.counts_lobbyists[0])
for b in self.bandits:
print(Counter(b.hires)[0]) |
def light(self):
brightness = []
for rotation in self.torusVertexRotation:
totalDifference = 0
for i in range(3):
difference = abs(rotation[i] - self.lightRotation[i])
if difference > m.pi: difference = 2*m.pi - difference
totalDiff... | The code continuously generates ASCII art projections of a rotating torus by measuring brightness, projecting it, rendering as ASCII, and rotating the torus in an infinite loop. | def loop(self):
while True:
brightness = self.light()
projection = self.project(brightness)
self.ascii(projection)
self.rotateTorus() |
def preprocess_img(self, image_buffer, frames, thread_id):
"""Preprocessing image_buffer using thread_id."""
# Note: Width and height of image is known only at runtime.
if self.train and self.distortions:
image = distort_image(image_buffer, frames=frames, time_window=self.time_window... | This function preprocesses input data by routing it to type-specific preprocessing methods (image, flow, or audio) based on the 'data_type' attribute, returning the processed data. It raises an error if the data type is unsupported. | def preprocess(self, data_buffer, frames, thread_id=0):
if self.data_type is 'rgb':
processed_data = self.preprocess_img(data_buffer, frames, thread_id)
elif self.data_type is 'flow':
processed_data = self.preprocess_flow(data_buffer, frames, thread_id)
elif self.data_typ... |
def try_names(frame_data, video_name):
anno = frame_data['annotations']
number_of_segment = len(list(anno))
file_list = []
if not anno:
filename = (video_name + '.tfrecords')
file_list.append(filename)
else:
for i_seg in range(number_of_segment):
filename = (video... | The main task of the code is to process a video by converting it into TFRecord files (both trimmed and untrimmed versions), checking if they already exist, and uploading them to HDFS if not. It also logs failed video processing attempts to a CSV file. The function handles video conversion, data extraction, file cleanup... | def processing_tfrecord_upload(_video_name, destination_path, database, jpg_path, fps, activity_index, existing_files_trimmed, existing_files_untrimmed):
with open('failed_videos.csv', 'a') as myfile:
csv_writer = csv.writer(myfile, quoting=csv.QUOTE_ALL)
frame_data = database[_video_name] # JSON d... |
def create_left_frame(self):
self.left_frame = tk.Frame(self, bg="pink")
self.left_frame.grid(row=0, column=0, sticky="nsew")
self.create_left_header()
self.create_left_content()
def create_right_frame(self):
self.right_frame = tk.Frame(self, bg="white", width=2*self.settings.width//3)
self.right_frame.grid... | The code initializes a GUI component by setting up attributes like application settings, database references, and layout configurations. It configures a grid layout for the parent container, creates left and right frames, and prepares the interface structure for a database-related application. | def __init__(self, parent, App):
self.app = App
self.settings = App.settings
self.current_Database = self.settings.Database[0]
self.last_current_Database_index = 0
self.update_mode = False
self.Databases_index = []
super().__init__(parent) # window.conteiner
self.grid(row=0, column=0, sticky="nsew")
... |
def load_results(dir):
import pandas
monitor_files = (
glob(osp.join(dir, "*monitor.json")) +
glob(osp.join(dir, "*monitor.csv"))) # get both csv and (old) json files
if not monitor_files:
raise LoadMonitorResultsError("no monitor files of the form *%s found in %s" % (Monitor.EXT, di... | The code plots multiple result curves from specified directories, visualizing 'reward' and 'timesteps' metrics against a given x-axis for a task. It filters data to limit timesteps, then generates subplots to display these metrics comparably across different result sets. | def plot_results(dirs, num_timesteps, xaxis, task_name):
tslist = []
for dir in dirs:
ts = load_results(dir)
ts = ts[ts.l.cumsum() <= num_timesteps]
tslist.append(ts)
yaxes = ['reward', 'timesteps']
fig = plt.figure(figsize=(8, 4))
for i in range(len(yaxes)):
plt.subp... |
def get_all_obs(self,robotId):
temp_obs_value = []
# Base position state
base_info = self.get_distance_and_ori_and_velocity_from_target(robotId)
# Joints state
joints_info = self.get_joints_values(robotId)
# Trajec state
trajec_info = self.get_t... | The main task of the code is to collect observations, rewards, and environment information for multiple robots. It iterates through each robot, gathers observations using `get_all_obs`, computes rewards with `get_reward_value`, and, in training mode, checks if targets are reached via `auto_reset`. Results are aggregate... | def get_obs(self,train=True):
temp_obs_value = []
temp_info = []
temp_reward_value = []
for robotId in self.robotId_list:
# GET OBSERVATION
temp_obs_value += [self.get_all_obs(robotId)]
# GET INFO
# Check weather the target is re... |
def load_dataset():
splits = load_json_files(config['disaster_splits_json'])
data_mean_stddev = load_json_files(config['disaster_mean_stddev'])
train_ls = []
val_ls = []
for item, val in splits.items():
train_ls += val['train']
val_ls += val['val']
xBD_train = DisasterDataset(... | The main task of the code is to train and evaluate a deep learning model (SiamNet) for image segmentation, focusing on damage and building classification. It loads datasets, sets up data loaders, initializes model parameters, and trains the model over multiple epochs. During training, it computes metrics like precision... | def main():
global viz, labels_set_dmg, labels_set_bld
global xBD_train, xBD_val
global train_loader, val_loader, test_loader
global weights_loss, mode
xBD_train, xBD_val = load_dataset()
train_loader = DataLoader(xBD_train, batch_size=config['batch_size'], shuffle=True)
val_loader = Data... |
def _walk_fields_decode_composite(schema: Schema, rv: dict, composite: Composite, vals: list, cursor: Cursor):
for t in composite.types:
if isinstance(t, Composite):
rv[t.name] = {}
_walk_fields_decode_composite(schema, rv[t.name], t, vals, cursor)
else:
if t.pre... | This function recursively decodes nested data structures into a dictionary by processing fields in a schema. It handles groups by iterating over their elements, recursively decoding each into a sub-dictionary, and processes composite types separately. The cursor tracks the current position in the input values list, adv... | def _walk_fields_decode(schema: Schema, rv: dict, fields: List[Union[Group, Field]], vals: List, cursor: Cursor):
for f in fields:
if isinstance(f, Group):
if len(vals) >= cursor.val + 1:
num_in_group = vals[cursor.val + 1]
else:
num_in_group = 0
... |
def scrollToBottom(self):
Y = 1000
last = 0
zeroCount = 0
while True:
self.driver.execute_script("window.scrollTo(0, " + str(Y) + ")")
Y = Y + 2000
self.content = self.driver.page_source
soup = BeautifulSoup(self.content, features="html.par... | This code scrapes and cleans long/short comments/outcomes from a webpage. It navigates to a given URL, scrolls to load content, parses HTML with BeautifulSoup, and extracts either outcomes-only or both outcomes/comments based on the 'outcomes_only' flag. It handles pagination by switching innings and re-scraping data a... | def scrape(self, address, outcomes_only=False): # scrape and clean the long and short comments
# reset the sequences for next page
self.outcomeEmissions = {}
self.outcomeSequence = []
print(address)
self.driver.get(address)
self.content = self.driver.page_source
... |
def createSequenceFiles(self):
save_path = 'scrapedSequences/'
address = os.getcwd()+'/scrapedSequences'
for filename in os.listdir(address):
with open(os.path.join(address, filename), 'w') as f:
f.write('')
def scrapeTeamList(self, address):
self.teams = [[],... | The main task of the code is to scrape cricket match data from multiple URLs, either full scorecards or ball-by-ball commentary, based on the `outcomes_only` flag, and write the extracted data to files. It iterates through a list of addresses, processes each one by calling specific scraping methods, accumulates total b... | def scrapeAll(self, outcomes_only=False):
i = 1
self.createSequenceFiles()
for address in self.addresses:
if address == '':
print('empty address')
break
print('scraping address ' + str(i) + ' of ' + str(len(self.addresses)))
if... |
def get_per_goal(data, func, data_sample_rate=1):
goal_set = get_goal_set(data)
goals_per_episode = get_goals_per_episode(data)
measure = func(data)
ret = {}
for goal in goal_set:
indices = (goals_per_episode == goal).all(axis=-1).nonzero()[0]
ret[goal] = (indices * data_sample_rate,... | The code generates and plots confidence intervals for four metrics—iteration first success and success rate—across different goals and switches. It processes input data, interpolates results, and visualizes them on provided axes with specific y-limits and titles, using color-coded representations for each goal. | def plot(ax_per_goal_iteration_first_success,
ax_per_goal_success_not_trivial,
ax_per_switch_iteration_first_success,
ax_per_switch_success_not_trivial,
data, data_sample_rate=1):
per_goal_iteration_first_success = get_per_goal(data, get_iteration_first_success, data_sample_rate=data... |
def collect_and_train(self, policy=True, critic=True):
self.collect_data()
while self.current_training_ratio < self.updates_per_sample:
self.train(policy=policy, critic=critic)
def evaluate(self):
"""Performs one episode of evaluation"""
goals = self.sample_goals(mode=self.ev... | This function trains the policy and critic networks using collected data, optionally evaluates the model, and logs summaries periodically based on the global training step count. It combines data collection, model training, evaluation (if enabled), and logging of metrics like exploration and training progress. | def collect_train_and_log(self, policy=True, critic=True, evaluation=False):
self.collect_and_train(policy=policy, critic=critic)
if evaluation:
self.evaluate()
if self.n_global_training % self.log_freq == 0:
self.log_summaries(exploration=True, evaluation=evaluation,
... |
def help():
print("Usage :-")
print('$python3 todo.py add \"todo item\" # Add a new todo ')
print('$python3 todo.py ls # Show remaining todos ')
print('$python3 todo.py del NUMBER # Delete a todo ')
print('$python3 todo.py done NUMBER # Complete a todo ')
print('$python3 todo.py help ... | The code defines a `run()` function that processes command-line arguments to execute tasks like adding, listing, deleting, marking tasks as done, generating reports, or showing help. It routes input commands to corresponding functions, acting as a CLI interface for task management. | def run():
if (len(sys.argv) == 1):
help()
elif sys.argv[1] == 'help':
help()
elif sys.argv[1] == 'add':
add(sys.argv[2])
elif sys.argv[1] == 'ls':
ls()
elif sys.argv[1] == 'del':
delete(sys.argv[2])
elif sys.argv[1] == 'done':
done(sys.argv[2])
elif sys.argv[1] == 'report':
report() |
def find_dist(t):
#find reference and token markers in children
for i in range(len(t)):
if '*ref' in str(t[i]):
ref_idx = i
if '*tok' in str(t[i]):
tok_idx = i
#get distance
if ref_idx == tok_idx:
return find_dist(t[ref_idx])
elif ref_idx < tok_idx:
... | This function generates features describing the relationship between tokens and their referents in parsed text. It calculates whether tokens and referents are in the same sentence, share the same speaker, their positional distance, and if cataphora occurs. The output is a matrix of these features for each key in the in... | def get_distance_features(tok_dict, ref_dict, parses):
feat_mat = []
for key in tok_dict.keys():
if not key in ref_dict:
feat_mat.append([])
continue
tok_marker = '*tok'+key+'*'
ref_marker = '*ref'+key+'*'
same_sent = False
same_speaker = True
... |
def get_indv_features(tok_dict, ref_dict):
examples = []
for key in tok_dict.keys():
if key in ref_dict:
examples.append((tok_dict[key], ref_dict[key]))
else:
examples.append((tok_dict[key], None))
feat_mat = []
for example in examples:
feat_mat.append(fe... | The main task of the code is to process labeled text files by extracting linguistic features from token and referent markers, combining individual and comparative features, and writing them with corresponding labels to output files. It reads input data, applies regex transformations, collects features using helper func... | def main():
for filename in os.listdir('labeled_ref'):
print("processing "+filename)
f = open('labeled_ref/'+filename)
outf = open('features/'+filename, 'w+')
#find parses with token and referent markers
tok_dict = {}
ref_dict = {}
parses = []
... |
def get_balance_of(token, account):
# return balanceOf for the given address
contract = web3.eth.contract(address=token, abi=ERC20_ABI)
return contract.functions.balanceOf(account).call()
def get_reserves(pair):
# return the current reserves
contract = web3.eth.contract(address=pair, abi=PAIR_ABI)... | The code's main task is to add liquidity to a token pair by calculating optimal token amounts based on wallet balances and existing reserves, applying slippage adjustments, approving token spending, and executing a liquidity addition transaction via a router contract, returning transaction hashes for tracking. | def add_liquidity(token0_address, token1_address, pair_address, amount0=None, amount1=None, deadline=120):
txns = []
# get balance of token0 and token1 in wallet
token0_balance = get_balance_of(token0_address, ACCOUNT)
token1_balance = get_balance_of(token1_address, ACCOUNT)
# debugging
print... |
def get_lp_token_address(pid):
# returns the lp token address for the given pool # ID
return staking_contract.functions.poolInfo(pid).call()[0]
def get_balance_of(token, account):
# return balanceOf for the given address
contract = web3.eth.contract(address=token, abi=ERC20_ABI)
return contract.fu... | The function stakes LP tokens in a specified pool by first approving the router to spend the tokens, then constructing and sending a transaction to deposit the LP tokens into the pool, returning the transaction hashes. | def stake_lp_tokens(pid, amount=None, private_key=None):
txns = []
# Get LP Token address and create Token instance
lp_token_address = get_lp_token_address(pid)
# APPROVE LP TOKENS FOR SPEND BY ROUTER
# get balance of LP tokens in wallet
lp_token_balance = get_balance_of(lp_token_address, AC... |
def get_balance_of(token, account):
# return balanceOf for the given address
contract = web3.eth.contract(address=token, abi=ERC20_ABI)
return contract.functions.balanceOf(account).call()
def _approve(token, max_approval=None, gas=150000, gas_price=None):
if not max_approval:
max_approval = MA... | The code removes liquidity from a decentralized finance (DeFi) liquidity pool by burning LP tokens and receiving the underlying tokens. It calculates minimum token amounts based on current reserves and slippage, approves the router to spend LP tokens, constructs a transaction with a deadline, and executes it. The funct... | def remove_liquidity(token0_address, token1_address, pair_address, liquidity=None, deadline=120):
txns = []
# get balance of LP tokens in wallet
lp_token_balance = get_balance_of(pair_address, ACCOUNT)
# if amount to remove not specified, use full LP token balance
if not liquidity or liquidity > ... |
def add_liquidity(token0_address, token1_address, pair_address, amount0=None, amount1=None, deadline=120):
txns = []
# get balance of token0 and token1 in wallet
token0_balance = get_balance_of(token0_address, ACCOUNT)
token1_balance = get_balance_of(token1_address, ACCOUNT)
# debugging
print... | The code executes a sequence of liquidity operations: adding liquidity to a pool, staking LP tokens, unstaking them, and removing liquidity, simulating a full lifecycle of liquidity provision and management. It tests interactions with a decentralized finance (DeFi) protocol by depositing, locking, unlocking, and withdr... | def run_test():
add_liquidity(cub_address, busd_address, cubbusd_address)
stake_lp_tokens(10)
unstake_lp_tokens(10)
remove_liquidity(cub_address, busd_address, cubbusd_address) |
def index_sample_data(event):
print(f'In index_sample_data {event}')
payload = json.loads(event['body'])
type = payload['type']
create_index()
for i in range(1, 5):
try:
file_name=f"{SAMPLE_DATA_DIR}/{type}_doc_{i}.txt"
f = open(file_name, "r")
data = ... | (The code defines an API handler for an Amazon Opensearch Serverless vector database, routing HTTP requests to specific functions based on their method and path. It maps endpoints like indexing documents, querying data, and deleting indexes to corresponding operations, returning responses or error messages while loggin... | def handler(event, context):
LOG.info("--- Amazon Opensearch Serverless vector db example with Llama2 / Falcon models ---")
api_map = {
'POST/rag/index-sample-data': lambda x: index_sample_data(x),
'POST/rag/index-documents': lambda x: index_documents(x),
'DELETE/rag/index-documents': ... |
def index_sample_data(event):
print(f'In index_sample_data {event}')
payload = json.loads(event['body'])
type = payload['type']
create_index()
for i in range(1, 5):
try:
file_name=f"{SAMPLE_DATA_DIR}/{type}_doc_{i}.txt"
f = open(file_name, "r")
data = ... | This code defines an AWS Lambda handler that routes incoming HTTP requests to specific functions based on API endpoints. It maps HTTP methods and paths to operations like indexing data, deleting indexes, or connecting trackers. The handler processes events, executes the corresponding function, and returns responses or ... | def handler(event, context):
LOG.info("--- Amazon Opensearch Serverless vector db example with Amazon Bedrock Models ---")
api_map = {
'POST/rag/index-sample-data': lambda x: index_sample_data(x),
'POST/rag/index-documents': lambda x: index_documents(x),
'DELETE/rag/index-documents': l... |
def forward(self, instance):
'''
Feed forward the Artificial Neural Network
'''
res = {
f'layer{i}': [0.0 for _ in range(self.topology[i])]
for i in range(1, len(self.topology))
}
# set the input layer to the instance
res['layer0'] = ... | This code trains an Artificial Neural Network by shuffling input data, performing forward passes to compute outputs, calculating loss, backpropagating errors, and updating weights iteratively. It accumulates loss across all examples, normalizes it by the dataset size, and returns the average loss per training step. The... | def training_step(self, train_data):
'''
Train the Artificial Neural Network
k is the number of folds
'''
if not train_data:
raise ValueError('No training data provided')
# get the data
data = train_data
# shuffle the data
random.shuffl... |
def forward(self, instance):
'''
Feed forward the Artificial Neural Network
'''
res = {
f'layer{i}': [0.0 for _ in range(self.topology[i])]
for i in range(1, len(self.topology))
}
# set the input layer to the instance
res['layer0'] = ... | This code trains an Artificial Neural Network (ANN) by iterating over the provided training data for a specified number of epochs. It shuffles the data, performs forward propagation to compute outputs, calculates loss, backpropagates errors, and updates weights using the step method. The average loss per epoch is track... | def train(self, train_data, epochs=10):
'''
Train the Artificial Neural Network
k is the number of folds
'''
if not train_data:
raise ValueError('No training data provided')
# get the data
data = train_data
# shuffle the data
random.shu... |
def get_all_trains(self) -> List[Train]:
"""
Get all the Trains in the graph
:return: List of Trains in the graph
"""
all_trains: List[Train] = []
for edge_tup in self.graph.edges:
track: Track = self.graph.edges[edge_tup]['object']
if track.train:... | (Advances the simulation by moving all trains forward and setting signals/junction switches, prioritizing lower-ID trains. Returns True if more updates are needed (trains remain en route), False if all trains have reached destinations. Updates trains, tracks switches/signals set by each train, avoiding conflicts with p... | def advance(self) -> bool:
"""
Advance the Simulation one step. Move all trains forward, then set Signals
& Junction switches for each Train (priority given to lower ID Trains).
:return: True if more updates are required,
False if all trains have reached their destination.
... |
def matrix_addition(self, start, end):
if not self.multithreading:
self.data = {}
self.object_main.ui.overallHeatmapOutput.setPixmap(QPixmap(""))
with open(self.source) as f:
x = f.readlines()[(start - 1): end]
for i, data_arr in enumerate(x):
... | This code converts a matrix to an image for display, handling both single-threaded and multithreaded execution. If multithreading is disabled, it directly processes the matrix and updates the display. If enabled, it sets up timers and connects UI sliders to adjust heatmap parameters dynamically, ensuring real-time upda... | def matrix_to_image(self, start=1, end=1):
if not self.multithreading:
output = self.matrix_addition(start, end)
self.object_main_display = self.object_main.ui.currentHeatmapOutput
self.matrix_to_image_display(output)
else:
self.timer.start()
s... |
def initializing_video_slider(self, source):
self.fps = cv2.VideoCapture(source).get(cv2.CAP_PROP_FPS)
total_frame = cv2.VideoCapture(source).get(cv2.CAP_PROP_FRAME_COUNT)
# set max value for videoSlider
self.ui.videoSlider.setValue(0)
self.ui.videoSlider.setMaximum(total_frame)... | This function initializes human detection by configuring UI icons, resetting data transfer parameters, and setting AI detection thresholds. It disables camera/run buttons if a video is loaded, initializes video sliders, starts multithreaded AI detection, and connects UI controls to pause/play/stop detection functions. | def human_detection(self):
self.ui.humanIcon.setIcon((QIcon("icons/human - white.svg")))
self.ui.warningIcon.setIcon(QIcon(""))
self.Saving.__init__(self)
if self.thread_1.isRunning():
self.thread_1.quit()
self.DataTransfer.__init__()
self.Heatmap.res... |
def get_file(self):
self.ui.outputImage.setPixmap(QPixmap(""))
self.fname = QFileDialog.getOpenFileName(self, 'Open file', 'c:/')
self.ui.openBtn.setStyleSheet("background-color: #16191d;")
def human_detection(self):
self.ui.humanIcon.setIcon((QIcon("icons/human - white.svg")))
s... | This code initializes a GUI application by setting up the user interface, configuring AI detection parameters (confidence, overlap thresholds), connecting buttons to functions (e.g., file opening, camera access, AI execution), managing UI states (login page restrictions), and initializing multithreaded AI detection and... | def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
loadJsonStyle(self, self.ui)
# Variables for the image/video source
self.fname = ('', '')
# Default AI parameters
#setting slider deafult values... |
def _next_canvas_non_ref(self):
for record in self.canvas:
if self._record_passes_filters(record, 'canvas'):
if record.id not in self._written_variants:
return record
self._canvas_finished = True
raise StopIteration
def _next_manta_cnv(self):
... | The code implements an iterator that alternates between two data sources (canvas and manta) to generate overlapping records. It fetches next records from each source, handles completion states, and selects the appropriate record for processing. When a record is used, it advances the corresponding iterator. The method r... | def __next__(self):
if self.current_canvas_record is None and not self._canvas_finished:
try:
self.current_canvas_record = self._next_canvas_non_ref()
except StopIteration:
pass
if self.current_manta_record is None and not self._manta_finished:
... |
def has_children(self, index):
return self.item_exists(self.left_child_index(index))
def find_child_index_for_bubble_down(self, index):
left_child_index = self.left_child_index(index)
right_child_index = self.right_child_index(index)
# if there are 2 children find smaller/bigger of them... | The main task of the code is to maintain the heap property by moving the element at the given index downward in the heap structure until it reaches a valid position. It repeatedly compares the element with its children, swaps it with the appropriate child if necessary, and updates the index to continue the process unti... | def bubble_down(self, index):
while True:
if self.has_children(index) is False:
break
child_index_to_swap = self.find_child_index_for_bubble_down(index)
result = self._comparator(
self._items[index], self._items[child_index_to_swap])
... |
def swap(self, index1, index2):
self._items[index1], self._items[index2] = self._items[index2], self._items[index1]
def size(self):
return len(self._items)
def bubble_down(self, index):
while True:
if self.has_children(index) is False:
break
child_index_t... | This method removes and returns the maximum element from a priority queue by swapping the root (maximum) with the last element, popping it, and restoring the heap structure via bubble-down operation. | def extract_top(self):
self.swap(0, self.size() - 1)
result = self._items.pop()
self.bubble_down(0)
return result |
def io(profile, outdir):
check_dir = os.path.isdir(outdir)
if not check_dir:
os.makedirs(outdir)
try:
base = os.path.basename(profile)
if re.search('\.base$', profile):
phase = outdir + '/' + os.path.splitext(base)[0] + '_periodicity.txt'
stat = outdir + '/' ... | The main task of the code is to perform a bioinformatics analysis pipeline: it measures execution time, processes input data (`i`, `o`) to extract phase and statistic information, parses ribosome profiling data into a dataframe, identifies open reading frames (ORFs), calculates footprint counts, conducts a Fisher's tes... | def main():
start_time = time.perf_counter()
phase,stat = io(i, o)
df = parse_ribomap(i)
orf = orf_finder(r)
df = footprint_counts(orf, df)
fisher_test(df, phase, stat)
print('Finished all analysis in',
round((time.perf_counter()-start_time)/60), 'min',
(time.perf_counte... |
def initialize_population(self):
population = Population()
for _ in range(self.num_of_individuals):
individual = self.generate_individual()
individual.calculate_objectives(self.graph, self.demand_matrix)
population.append(individual)
return population
def fast... | This code implements a multi-objective genetic algorithm (NSGA-II) to optimize two objectives. It initializes a population, iteratively evolves it through selection, crowding distance calculation, and offspring generation. The algorithm maintains non-dominated fronts, selects individuals based on dominance and diversit... | def run(self):
self.population = self.initialize_population()
self.fast_non_dominated_sort(self.population)
for front in self.population.fronts:
self.calculate_crowding_distance(front)
children = self.create_children(self.population)
returned_population = None
... |
def up(self):
if self.snake.direction != "down":
self.snake.direction = "up"
def right(self):
if self.snake.direction != "left":
self.snake.direction = "right"
def down(self):
if self.snake.direction != "up":
self.snake.direction = "down"
def left(self):
... | This code executes a specified action (up, right, down, left) in an environment, updates the state via `self.main()`, retrieves the current state, and returns the new state, reward, termination flag, and additional info (empty dict) for reinforcement learning training. | def step(self, action):
if action == 0:
self.up()
if action == 1:
self.right()
if action == 2:
self.down()
if action == 3:
self.left()
self.main()
state = self.getState()
return state, self.reward, self.done, {} |
def multipol_handler(my_pol):
if my_pol.geom_type == 'MultiPolygon':
my_pol = max(my_pol, key=lambda a: a.area)
return my_pol
def get_stain(name):
return name.rpartition('-')[-1].partition('.')[0]
def register_annot_v1_cyt(annot_move_wkt, img_inst_move, img_inst_static, init_path_img, full_aff=False, plot_fig=Fal... | The code evaluates the performance of a registration algorithm on annotation pairs by calculating centroid error and IoU (Intersection over Union) for both base and registered annotations. It processes groups of annotations, computes metrics per group and stain type, tracks registration failures, and outputs overall av... | def metrics_reg_all(annot_group_coll, init_path_imgs="dl-file/526102245/reduced_img/", full_aff=False):
annot_grp_ids = []
annot_grp_n_pairs = []
annot_grp_fails = []
metrics_base = []
metrics_reg = []
n_pair = 0
mean_centroid_err_base = 0
mean_IoU_base = 0
mean_centroid_err_reg = 0
mean_IoU_reg = 0
fails ... |
def register_annot_v1_cyt(annot_move_wkt, img_inst_move, img_inst_static, init_path_img, orb=True, full_aff=False, plot_fig=False):
img_move_PIL = Image.open(init_path_img+img_inst_move.originalFilename+".jpg")
img_static_PIL = Image.open(init_path_img+img_inst_static.originalFilename+".jpg")
new_annot = registe... | The main task of the code is to register an annotation by aligning sub-images from moving and static images. It extracts regions of interest (ROIs) around the annotated centroid, resizes them proportionally, and performs secondary registration using these ROIs. The function returns the adjusted annotation after validat... | def register_annot_v2(annot_move_wkt, img_inst_move, img_inst_static, init_path_img, tmp_folder="", orb=True, plot_fig=[False, False, False]):
#perform annotation on whole image
annot_cent_moved = register_annot_v1_cyt(annot_move_wkt.centroid, img_inst_move, img_inst_static, init_path_img, orb=orb, plot_fig=plot_fig... |
def register_annot_v1_cyt(annot_move_wkt, img_inst_move, img_inst_static, init_path_img, orb=True, full_aff=False, plot_fig=False):
img_move_PIL = Image.open(init_path_img+img_inst_move.originalFilename+".jpg")
img_static_PIL = Image.open(init_path_img+img_inst_static.originalFilename+".jpg")
new_annot = registe... | The main task of the code is to register annotations between a moving image and a static image by aligning regions around the centroid of an annotation. It extracts sub-images centered on the registered centroid, adjusts window sizes based on image dimensions, performs secondary registration on these sub-images, and re... | def register_annot_v2_large(annot_move_wkt, img_inst_move, img_inst_static, init_path_img, tmp_folder="", orb=True, plot_fig=[False, False, False]):
#perform annotation on whole image
annot_cent_moved = register_annot_v1_cyt(annot_move_wkt.centroid, img_inst_move, img_inst_static, init_path_img, orb=orb, plot_fig=pl... |
def add_qr(participant, ticket):
draw = ImageDraw.Draw(ticket)
qr = qrcode.QRCode(version=1, box_size=6, border=2)
qr.add_data(
BASE_URL
+ base64.b64encode(
str.encode(
'{{"id":{},"nim":{}}}'.format(participant['id'], participant['nim'])
)
).de... | The main task of the code is to generate a personalized ticket image by adding a QR code and text information for a participant, then save the final image with a filename derived from the participant's details. | def generate(participant):
ticket = Image.open('./template.jpg')
add_qr(participant, ticket)
add_text(participant, ticket)
# ticket.show()
ticket.save(ticket_filename(participant)) |
def conj_quat(quat: np.ndarray) -> np.ndarray:
"""Returns the conjugate quaternion of `quat`.
Any number of leading batch dimensions is supported.
Args:
quat: Array of shape (B, 4).
Returns:
Conjugate quaternion(s), array of shape (B, 4).
"""
quat = quat.copy()
quat[..., 1... | The function `vec_world_to_local` converts vectors from world coordinates to a local reference frame using quaternions. It takes a world vector (`world_vec`), a root quaternion (`root_quat`), and an optional hover-up direction quaternion (`hover_up_dir_quat`). If provided, `hover_up_dir_quat` adjusts the root quaternio... | def vec_world_to_local(world_vec, root_quat, hover_up_dir_quat=None):
"""Local reference frame representation of vectors in world coordinates.
Any number of leading batch dimensions is supported.
Args:
world_vec: Vector in world coordinates, (B, 3).
root_quat: Root quaternion of th... |
def get_dquat(quat1, quat2):
"""Returns 'delta' dquat quaternion that transforms quat1 to quat2.
Namely, multiplying dquat and quat1 as mult_quat(dquat, quat1) gives quat2.
"""
return mult_quat(quat2, reciprocal_quat(quat1))
def quat_to_angvel(quat, dt=1.):
"""Convert quaternion (corresponding to or... | The function `quat_seq_to_angvel` converts a sequence of quaternions into angular velocities. It calculates the difference between consecutive quaternions, converts these differences to angular velocities using a specified timestep `dt`, and adjusts the reference frame (global or local) based on the `local_ref_frame` p... | def quat_seq_to_angvel(quats, dt=1., local_ref_frame=False):
"""Covert sequence of orientation quaternions to angular velocities.
Args:
quats: Sequence of quaternions. List of quaternions or array (time, 4).
dt: Timestep.
local_ref_frame: Whether to return angular velocity in global... |
def getOptionChain(self, chain, start="1979-01-01", end="2050-01-01", debug=False):
resp = self.get_api_data(self.apiUrl, self.construct_options_payload(chain["ID"]), debug)
if resp["count"] == 0:
return None
data = resp["data"]
if data is not None:
data = pd.D... | The function retrieves historical option chain data for multiple options, processes each into a structured DataFrame with calculated fields (expiry, time-to-expiry, IV, etc.), and aggregates results. It handles API requests, data normalization, timezone conversion, and returns a consolidated DataFrame with multi-indexi... | def getOptionData(self, chain, start, end, records, debug):
if records == 1:
return self.getOptionChain(chain, start, end, debug)
optionData = pd.DataFrame(index=pd.MultiIndex(levels=[[], []], codes=[[], []], names=[u'Date_Time', u'ID']))
for option in chain["options"]:
... |
def conv2d(filters, kernel_size, strides=1, **kwargs):
return keras.layers.Conv2D(filters=filters,
kernel_size=kernel_size,
strides=strides,
padding='same',
use_bias=False,
kernel_initializer... | This code constructs a neural network model using Keras, building a DenseNet-like architecture with conditional layers based on 'bottleneck' and 'compression' parameters. It processes input data through dense blocks, transition blocks, global average pooling, and a softmax classifier, returning the compiled model with ... | def build(self, input_shape, classes):
inputs = keras.Input(shape=input_shape)
if self.bottleneck and self.compression:
outputs = conv2d(filters=2 * self.growth_rate,
kernel_size=(3, 3))(inputs)
else:
outputs = conv2d(filters=16, kernel_size=... |
def conv2d(filters, kernel_size, strides=1, **kwargs):
return keras.layers.Conv2D(filters,
kernel_size,
strides=strides,
padding='same',
use_bias=False,
kernel_i... | The code constructs a residual neural network (ResNet) with convolutional layers, batch normalization, ReLU activation, and residual blocks. It processes input data through multiple stages of feature extraction, progressively increasing filter counts via widening factors, applying downsampling where needed, and conclud... | def build(self, input_shape, classes=10):
filters = 16
inputs = keras.Input(shape=input_shape)
outputs = batch_normalization()(inputs)
outputs = relu()(outputs)
outputs = conv2d(filters=filters, kernel_size=(3, 3))(outputs)
filters = filters * self.widening
f... |
def have_allcontributorsrc():
try:
find_allcontributorsrc()
return True
except FileNotFoundError:
return False
def find_allcontributorsrc():
"""Find the full path of the .all-contributorsrc file"""
return find_file_in_path_list(".all-contributorsrc", allcontributorsrc_path_list(... | This function writes a dictionary to the `.all-contributorsrc` file, determining the correct file path by checking if the file already exists or if the current directory is a Git repository. If neither condition applies, it creates the file in the current working directory or the repository root. The data is saved as J... | def write_allcontributorsrc(data):
"""Write a dictionary into the allcontributorsrc file"""
if have_allcontributorsrc():
filename = find_allcontributorsrc()
else:
# Use the current working directory as the location of the newly
# created allcontributorsrc file unless we are in a git... |
def parse_args():
parser = argparse.ArgumentParser(prog="data", description="")
parser.add_argument("-c", "--command", type=Command.from_string, required=True,
help=f"The command to run.", choices=list(Command))
parser.add_argument("-i", "--in_dir", metavar="PATH", type=str, required=True,
... | The main task of the code is to execute data processing workflows based on a command-line argument. It parses input/output directories and dispatches to specific functions like `data_preprocess`, `data_a1`, `data_a2`, or `data_a3` depending on the `Command` enum value, handling different stages of data transformation o... | def main():
command, in_dir, out_dir = parse_args()
if command == Command.preprocess:
data_preprocess(in_dir, out_dir)
elif command == Command.a1:
data_a1(in_dir, out_dir)
elif command == Command.a2:
data_a2(in_dir, out_dir)
elif command == Command.a3:
data_a3(in_dir, out_dir) |
def k0(self, x, y, z):
return self.h * self.f(x, y, z)
def k1(self, x, y, z):
return self.h * self.f(
x + 0.5 * self.h, y + 0.5 * self.k0(x, y, z), z + 0.5 * self.l0(x, y, z)
)
def k2(self, x, y, z):
return self.h * self.f(
x + 0.5 * self.h, y + 0.5 * self.k1(x, y... | The code implements the 4th-order Runge-Kutta method (RK4) to numerically solve a system of two ordinary differential equations (ODEs) for variables y (pressure) and z (mass) over a radius x. It initializes arrays for x, y, z, applies RK4 steps with weighted averages of four intermediate slopes (k0–k3 for y, l0–l3 for ... | def RK4(self):
x, y, z = np.zeros(self.N), np.zeros(self.N), np.zeros(self.N)
y[0], z[0] = self.y0, self.z0
x[0] = self.a
for i in range(self.N - 1):
y[i + 1] = (
y[i]
+ (
self.k0(x[i], y[i], z[i])
+ ... |
def init_weights(self, input_dim, output_dim, name, std=0.1, reg=None):
return tf.get_variable(name, shape=[input_dim, output_dim], initializer=tf.random_normal_initializer(0.0, std),
regularizer=reg)
def init_bias(self, output_dim, name):
return tf.get_variable(name, shap... | The code initializes a neural network with LSTM-like gates (input, forget, output) and a decomposition layer, setting up placeholders for inputs and labels. It defines trainable parameters for training mode (with regularization) or testing mode (no initialization). The model includes fully connected layers for output, ... | def __init__(self, input_dim, output_dim, hidden_dim, fc_dim, train):
tf.reset_default_graph()
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.input = tf.placeholder('float', shape=[None, None, self.input_dim])
self.labels = tf.placeholder('float', shape=[None, outpu... |
def alone(self, obs):
# Check for enemies
y = 0
if u'entities' in obs:
for x in obs["entities"]:
if x['name'] in mobs:
y += 1
if y == 0:
agent_host.sendCommand("quit")
def calc_state(self, obs):
line_of_sight... | The code implements a Q-learning agent that updates its Q-table based on the current reward, selects actions using an epsilon-greedy strategy, and sends commands to the environment. It processes observations, calculates the current state, initializes Q-values if needed, updates Q-values from previous states, and choose... | def act(self, world_state, agent_host, current_r ):
"""take 1 action in response to the current world state"""
obs_text = world_state.observations[-1].text
obs = json.loads(obs_text) # most recent observation
if obs["WorldTime"] > 18010:
self.alone(obs)
... |
def getPotentialDocs(self, query, k, postings):
potentialIDS = {}
#get all documents that match all query terms
for word in query:
try:
for docid in postings[word]:
if docid[0] not in potentialIDS:
potentialIDS[docid[0]] = 1... | The code computes cosine similarity scores for documents based on query terms' tf-idf weights, normalizes query vectors, accumulates scores for potential documents, and returns top 50 URLs using max-heap selection. | def cosineScores(self, q, dfScores, postings):
scores = {}
#get all documents that either match all query terms or match all but one query term
potentialDocs = self.getPotentialDocs(q, 50, postings)
#store query as dictionary with query term frequency as values
q = self.getFreq(q... |
def filter_comments(sourcecode_file):
global filelines
singleline_comment_op_pos = -1
multiline_comment_start_op_pos = -1
multiline_comment_end_op_pos = -1
filtered_lines = []
inside_comment = False
for line in sourcecode_file:
filelines.append(line)
if not line.strip():
... | The code processes input files by removing comments and string literals, tokenizes the remaining code, counts operands and operators, and computes Halstead metrics including program length, difficulty, and other complexity measures based on token frequencies. | def main():
file = fileinput.input()
lines = filter_comments(file)
for line in lines:
st_line = filter_string(line, "\"")
st_line = filter_string(st_line, "\'")
tokens = st_line.strip().split()
for token in tokens:
filter_token(token)
print_result()
opera... |
def update_score(self):
black_score, white_score , won_player = self.ai_engine.get_current_score()
self.canvas.itemconfigure(self.black_score_txt, text="Human Score: %s" % black_score)
self.canvas.itemconfigure(self.white_score_txt, text="Computer Score: %s" % white_score)
if won_player != 'none':
self.handl... | This function executes a regular move by determining the move type and direction from the AI engine, updates the score, and either performs the GUI move along with the computer's response or alerts the user of an illegal move. | def _exec_regular_move(self):
move_type, direction = self.ai_engine.make_move(
HUMAN_COLOR, self.first_item_selected, self.second_item_selected)
self.update_score()
if move_type:
self._make_gui_move(move_type, direction, self.first_item_selected, self.second_item_selected)
self._exec_computer_move()
... |
def _make_gui_move(self, move_type, direction, from_cell, to_cell=None):
if move_type == MovesType.WALK:
self._make_walk_move(from_cell, to_cell)
if move_type == MovesType.PUSH:
self._make_push_move(from_cell, to_cell, direction)
if move_type == MovesType.PUSH_OUT:
self._make_push_out_move(from_cell, dir... | This function handles a push-out move action when a single cell is selected. It validates the selection, generates the move via the AI engine, updates the GUI and score, checks game status, and triggers the computer's response if the game continues. Illegal moves or invalid selections show appropriate alerts. | def _on_push_out_move_click(self, event):
if not (self.first_item_selected and not self.second_item_selected):
messagebox.showinfo("Info", "For making push out move you need to select only one cell")
else:
move_type, direction = self.ai_engine.make_move(
HUMAN_COLOR, self.first_item_selected)
if move_... |
def set_keys(self):
"""
sets the initial keys for the inventory file
"""
self.inventory_dict['all'] = {'children': {}}
self.inventory_dict['all']['vars'] = {}
backup_management_node = 'No'
self.inventory_dict['all']['children'] = {'primary': {'hosts': '{}'.for... | This code's main task is to configure system keys, set up HAProxy, manage DHCP lease times, update node inventory, and collect user inputs for a task. It orchestrates infrastructure setup and task preparation by initializing critical components and gathering necessary user parameters. | def run(self):
self.set_keys()
self.set_haproxy()
self.dhcp_lease_times()
self.set_nodes_inventory()
self.get_user_inputs_for_task() |
def get_function_entrypoint(hf):
return hf.getFunction().getEntryPoint()
def get_entrypoint_block(entrypoint, blocklist):
entry_block = None
for block in blocklist:
if(block.getStart().equals(entrypoint)):
entry_block = block
return entry_block
def get_block_data(block, hf):
data... | The function constructs a control flow graph (CFG) for a given function `hf`, starting from its entry point. It skips blocks in the `blocklist` and creates a directed graph using NetworkX, adding nodes for basic blocks and their data. If the entry point is valid, it recursively adds child blocks to the graph. Returns t... | def cfg_per_function(hf, blocklist):
digraph = None
entrypoint = get_function_entrypoint(hf)
entrypoint_block = get_entrypoint_block(entrypoint, blocklist)
if entrypoint_block is not None: # None happens for functions like _init or _start
traversed = []
digraph = nx.DiGraph()
dig... |
def list_all_functions():
funcs_list = []
func = getFirstFunction()
while func is not None:
x = func.isThunk()
if not x:
funcs_list.append(func)
func = getFunctionAfter(func)
return funcs_list
def open_program():
iface = DecompInterface()
iface.openProgram(currentPr... | The main task of the code is to retrieve and save control flow graphs (CFGs) for all functions in a program. It lists all functions, extracts their CFGs using an interface, organizes them in a dictionary by function name, and exports each CFG as JSON files. The process involves fetching function data, analyzing basic b... | def main():
hfs = []
listing = list_all_functions()
iface = open_program()
print("\nRetrieving CFGS per each function...\n")
for func in listing:
hfs.append(get_hf(iface, func))
basic_blocks_list = []
cfgs = {}
for hf in hfs:
if hf is not None:
basic_blocks_list.append(get_basic_blocks_per_function(hf))
... |
def get_conf(tool_path='./', platform='Linux'):
ptname = 'Posix'
if platform == 'Windows':
ptname = 'Windows'
surtr_path = '{tool_path}/Surtr/Templates'.format(tool_path=tool_path)
# get building Makefile template
fname = '{surtr_path}/Build.{pt}.mk'.format(surtr_path=surtr_path, pt=ptname... | This function generates a Makefile by compiling configuration data, source files, and build settings into a template. It retrieves build configurations, processes source files to create object file lists, constructs build commands, and writes the formatted Makefile with compiler flags, includes, and target definitions. | def gen_makefile(surtr_path='./', platform='linux', outdir='build'):
is_posix = platform != 'Windows'
build_mk, obj_mk, build_conf = get_conf(surtr_path, platform)
sources = get_all_sources(build_conf['sources_paths'], valid_exts=build_conf['extensions'])
objs_list = []
buildobjs_list = []
for ... |
def get_options():
parser = argparse.ArgumentParser(description='Surtr C/C++ building tool')
parser.add_argument('surtr_path', nargs='?', help='relative path of `Surtr`')
parser.add_argument('option', nargs='?', help='config|build|rebuild|clean|remove the project')
args = parser.parse_args()
return ... | The main task of the code is to build or manage a project using a Makefile, handling platform-specific build tools (nmake/make) and options like 'build', 'clean', 'rebuild', or 'remove'. It generates output directories, configures build settings, and executes commands based on user-specified options, defaulting to 'bui... | def main():
surtr_path, option = get_options()
if option == 'remove':
do_remove()
return
if surtr_path is None:
surtr_path = '../'
platform = get_platform()
gen_outdir()
gen_makefile(surtr_path=surtr_path, platform=platform, outdir=OUTDIR)
if option == 'config':
... |
def __get_step(self, step=None):
if step is None:
step = self.step
else:
step = pd.Timedelta(step).asm8.astype('<m8[m]')
if self.__day % step:
raise ValueError(f"there should be whole number of steps in 1 day")
steps_per_day = self.__day // step
... | This function generates a double actogram to visualize activity patterns over time, displaying night intervals and activity onsets for each day. It allows customization of bin size, log scaling, activity bout calculation, and convolution kernel parameters for onset detection. The plot features two horizontally aligned ... | def plot_actogram(self, step=None, bouts=False, log=False, activity_onset='step', percentile=20, N='6h', M='6h',
filename=None, width=1000, height=100, dpi=100):
"""Plot double actogram with right half shifted by 1 day.
Night intervals for each day are also plotted on actogram as ... |
def update_link(self, mod='c'):
update_link(mod)
self.read_available_links()
def use_scihub_url(self, index):
self.scihub_url = self.scihub_url_list[index]
print(STD_INFO + 'Choose the available link %d: %s' %(index, self.scihub_url))
if self.scihub_url[-3:] == "red":
... | This function downloads a PDF using a DOI via SciHub URLs. It auto-selects valid URLs, handles errors (e.g., 404/429), updates links if needed, checks for CAPTCHA or PDF content, and downloads the paper. If invalid, it attempts alternative URLs. The result is saved to the specified output path. | def download(self, choose_scihub_url_index=-1):
"""Download the pdf of self.doi to the self.out path.
params:
choose_scihub_url_index: (int)
-1: Auto-choose the scihub urls.
>=0: index of scihub url in scihub url links.
"""
# Auto ch... |
def index_closest_to_point(self, curve):
a = 0
b = len(curve)-1
c = (a+b)//2
sqdist_a = np.hypot(curve[a].pos.x - self.x, curve[a].pos.y - self.y)
sqdist_b = np.hypot(curve[b].pos.x - self.x, curve[b].pos.y - self.y)
sqdist_c = np.hypot(curve[c].pos.x - self.x, curve[c]... | This function projects a point onto a curve by finding the closest curve segment, computing interpolated points, comparing distances, and returning the closest projection with its curve index. | def proj_on_curve(self, curve):
ind = self.index_closest_to_point(curve)
curveind = None
footpoint = None
if ind > 0 and ind < len(curve)-1:
t_lo = get_lerp_time(curve[ind-1].pos, curve[ind].pos, self)
t_hi = get_lerp_time(curve[ind].pos, curve[ind+1].pos, self)
... |
def is_defined(self, var_name, var_feat = ""):
if var_feat == "":
v_name, v_feat = self.split_name_feat(var_name)
else:
v_name = var_name
v_feat = var_feat
if not v_name in self.DB["vars"]:
return False
if v_feat != 'NONE':
i... | This function adds a variable to a dictionary, ensuring it's not already defined. It maps `var_origin` to `var_target`, checks feature consistency, and handles feature assignments. If `var_origin` has a feature, it links it to `var_target`'s feature. Errors are raised for duplicates or incompatible features. | def add_variable(self, var_origin, var_target=""):
if self.is_defined(var_origin):
print(f"{'[ interfaceDictionary ] ERROR add_variable : ' : <45}{' trying to add a variable already defined in the dictionary '}{var_origin}")
return
if var_target == "":
var_target =... |
def is_defined(self, var_name, var_feat = ""):
if var_feat == "":
v_name, v_feat = self.split_name_feat(var_name)
else:
v_name = var_name
v_feat = var_feat
if not v_name in self.DB["vars"]:
return False
if v_feat != 'NONE':
i... | This method converts a variable or constant by validating its definition and features, then returning a formatted result. It checks if the input is a constant or variable, verifies existence, retrieves target and feature values, and constructs the output using `build_with_target_format`, returning errors if validations... | def convert(self, sVar, sFeat, sInd = ""):
### CONSTANT ###
if sVar == self.CONSTANT_label:
if not self.is_defined(sVar):
print(f"{'[ interfaceDictionary ] convert : ' : <45}{'ERROR : no constant defined'}")
return self.CONVERSION_ERROR
if (not ... |
def find_first_var(self, targetString):
result = "NONE"
vPos = -1
stringShift = 0
while stringShift < len(targetString):
t1, t1_pos = self.get_token(targetString[stringShift:], underscore_allowed=False)
if self.is_defined(t1):
return t1, (str... | This function parses an input string to extract variable names, their associated features, and indices recursively. It builds a list of variables in a specific format, removes duplicates, and returns the processed list. The function handles nested structures by recursively processing index fields and remaining string s... | def get_var_list(self, inputString):
varList = []
if inputString == "":
return varList
# sHeader = ""
varName = "NONE"
varFeature = "NONE"
# varIndex = "NONE"
# sFooter = ""
# Find first variabl... |
def source_format(self, vType):
source_format = self.VARIABLE_label
if vType in self.typesWithFeature: source_format+='_'+self.FEATURE_label
if vType in self.typesWithIndex: source_format+='['+self.INDEX_label+']'
return source_format
def load_DB(self, dbFileName):
se... | The code initializes an interface dictionary object by setting up data types (scalar, vector, etc.), labels (VARIABLE, FEATURE), and format configurations. It creates dictionaries for base/target formats, initializes variables, loads a database if a file is provided, updates internal info, and prints a creation message... | def __init__(self, interfaceName = "", db_file = ""):
self.name = interfaceName
self.comment = ""
self.CONVERSION_ERROR = "CONVERSION_ERROR"
self.VARIABLE_label = "VARIABLE"
self.FEATURE_label = "FEATURE"
self.INDEX_label = ... |
def find_first_var(self, targetString):
result = "NONE"
vPos = -1
stringShift = 0
while stringShift < len(targetString):
t1, t1_pos = self.get_token(targetString[stringShift:], underscore_allowed=False)
if self.is_defined(t1):
return t1, (str... | The function translates a string by recursively identifying and converting variables, features, and indexes. It extracts headers, processes features, translates index fields, and combines results using a conversion method, returning the modified string. | def translate_string(self, inputString):
# if not self.do_translate: return inputString
if inputString == "": return inputString
sHeader = ""
varName = "NONE"
varFeature = "NONE"
varIndex = "NONE"
sFooter = ""
# F... |
def parse_arguments_to_settings():
parser = argparse.ArgumentParser()
parser.add_argument("-j", "--settings_json", default=None, required=True)
args = parser.parse_args()
if args.settings_json:
settings = json.load(open(args.settings_json))
else:
settings = [{}]
return settings
d... | The main task of the code is to process FASTQ samples by parsing settings, loading sample data, configuring directories, and generating shell scripts for each sample. It initializes a script directory, updates sample metadata with paths, and prepares execution scripts using `prepare_sh_for_sample` for downstream proces... | def main():
settings = parse_arguments_to_settings()
samples_dict = load_fastq_samples(settings)
samples_list = samples_dict_to_list(samples_dict)
script_dir = settings["script_dir"]
print(f"script_dir: {script_dir}")
os.makedirs(script_dir, exist_ok=True)
for sample_dict in samples_list:
... |
def list_all_races():
race_names = ["Human", "Dwarf", "Orc"]
names_str = ', '.join(race_names)
print(names_str)
return race_names
def choose_race(all_races):
race_list_in_lower = []
for race in all_races:
race_list_in_lower.append(race.lower())
race_selection = True
while race_s... | The function confirms a player's selected race and class. If the user declines, it prompts for new choices, recursively reconfirming until confirmation. It returns the confirmed race and class as a list. | def player_character_confirmation(race_choice, class_choice):
while True:
character_current_confirm = input(f"\nYou have currently selected a {race_choice} {class_choice}. Do you want to confirm this choice: (y/n) ")
if character_current_confirm.lower() == 'y':
char_list = [race_choice, ... |
def display_all_options_to_player(self):
self.all_player_options()
player_choices = self.choice_book_lower
player_choice = input()
if player_choice.lower() in player_choices:
return player_choice.lower()
else:
print(f"{player_choice} is not an option ava... | This function processes player commands by executing corresponding game actions. It checks the selected option and triggers methods like displaying stats, managing inventory, initiating attacks (with distance checks), using items, regenerating resources, moving, or checking the map. It handles interactive choices, incl... | def player_option_execution(self):
player_option = self.display_all_options_to_player()
if player_option == 'stats':
self.print_stats()
elif player_option == 'spellbook':
self.print_spellbook()
elif player_option == 'spell check':
self.print_spell()
... |
def set_new_throw(self):
"""Resets the throw variables in order to start a new throw"""
new_throw_first_point = (self.pos_list_x[-1], self.pos_list_y[-1])
self.was_successful = 0
# Clean positions of last throw
self.pos_list_x = []
self.pos_list_y = []
# Append f... | The code detects a ball's trajectory in a video frame, identifies new throws, and evaluates throw success based on the ball's position relative to a hoop. It tracks the ball's coordinates, checks if it crosses a threshold (half-frame x-position) to signal a new throw, and assesses whether the ball passes through a pred... | def detect_throws(self, img, frame):
# Initialization of the frame
img_color, mask = find_colors(img, self.hsv_val)
img_contours, contours = cvzone.findContours(img, mask, minArea=self.min_area)
try:
# Ball detected
if contours:
ball_x, ball_y = c... |
def base_datos(imgs):
## Definition de los momentos de cada clase de hoja
hoja_s = np.zeros((7, imgs.shape[0]))
k = 0
for img in imgs:
# Filter Image nois in the background
src = filter_leafs(img)
section, roi = ROI(src, img)
hu_moments = momentos_hu(roi)
hoja_s[... | The code processes images to detect and analyze leaf features by calculating Hu moments, comparing them to a database for classification, applying transformations, filtering noise, extracting regions of interest (ROI), and saving results with visualizations. | def pregunta_4(imgs, path):
## Definition de los momentos de cada clase de hoja
hoja_s = base_datos(imgs)
## Valores random para verificar funcionamiento
random_image = np.random.randint(5, size = 5)
angles_image = [0, 180, 90, 0, 180]
scales_image = [1, 0.9, 0.8, 1.1, 1.2]
j = 0
for i... |
def get_config_variables():
with open('config.yaml') as f:
data = yaml.load(f, Loader=yaml.FullLoader)
return data
def copy_worksheet(workbook, sheetName):
source = workbook.active
target = workbook.copy_worksheet(source)
target.title = sheetName
return target
def step_six(worksheet):
#Lesson, do not use arra... | The main task of the code is to process two Excel workbooks (stream and model) by copying worksheets, modifying their contents via predefined steps (step_six to step_nine and step_twelve), and saving updates. It uses progress bars to track completion, with the stream workbook undergoing four 25% steps and the model wor... | def main():
with tqdm(total=100, file=sys.stdout) as pbar:
for i in range(1):
#print("Main Source file called")
inputData = get_config_variables()
streamWorkbook = inputData["streamBookName"]
#print("Working on: " + str(streamWorkbook))
wb_stream = openpyxl.load_workbook(streamWorkbook)
modifiedWS ... |
def parserChanged(self, itemName):
"""
This function is called when the file format selection has changed.
:param itemName: The newly selected file format's name.
:type itemName: str
"""
chosenParser = strToEnum(PARSERS, itemName)
self.setDescription("Parser", ch... | This code handles user events in a GUI application by updating selected options (format, PRNG, test type) and triggering corresponding methods. It processes "Run" to execute a task with a provided path and "Clear logs" to reset log output. Each event updates internal state variables and invokes functions like parserCha... | def handleEvents(self, event, values):
if event == "-formatselection-":
self.selectedFormat = values["-formatselection-"]
self.parserChanged(self.selectedFormat)
if event == "-prngselection-":
self.selectedPrng = values["-prngselection-"]
self.selectedFor... |
def view_employee_admin(self, employee):
# Passed argument is list for that employee
# Creates Toplevel window labels and entry boxes
# Entry boxes are prepopulated with that employees info, empty if None
# Same layout as add_employee window
if employee == None: # no employee was... | The main task of the code is to dynamically update the Employee Directory UI based on user permissions, adding/admin-specific buttons (Add Employee, View/Edit, Submit Receipt/Timecard, Run Payroll, Archive/Unarchive) and displaying a sorted list of employees with visual indicators for archived/missing info entries. It ... | def update_frame(self):
'''Update frame function for Employee Directory Page
Adds the Add Employee Button if user is an admin.
Iterates through employee database and adds employees
to the list for viewing.
Adds a View Employee Button for the user to get more info
about th... |
def focus_game():
# noinspection PyBroadException
eqw = None
try:
if APP.process and APP.is_process_running():
LOG.info("Already have APP handle.")
else:
if config.EQ_WINDOW_TITLE_REGEX:
LOG.info("Connecting to APP via title regex.")
AP... | The main task of the code is to automate a game login process by monitoring the game's state progression. It focuses the game window, repeatedly checks the current state, logs progress, and handles potential stalls by moving the mouse. Once the state reaches the login threshold or after 15 attempts, it triggers the log... | def automate_login(char_info: models.Character) -> bool:
focus_game()
state = constants.STATE_UNKNOWN
progress_count = 0
while state < constants.STATE_LOGIN and progress_count < 15:
last_state = state
try:
state = progress_state()
except LookupError:
pass
... |
def choose(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
http://stackoverflow.com/questions/3025162/statistics-combinations-in-python/3025194#3025194
"""
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
... | The function performs a grid search over a discretized $d$-dimensional space, dividing each dimension into $c$ equal parts. It generates all combinations of $n$ cubes (points) and evaluates subsets of $k$ points to maximize the minimum regret. It filters combinations without dominated points and ensures coverage across... | def grid_search(k, d, n, c, utility_repeats):
''' Does a discretized space search in which each dimension is divided into c equal chunks
and from all possible cubes all combinations of n are picked so that the best subset of
k of these n has the largest possible regret
'''
# generate cubes o... |
def create_response(type=None, data=None, id=None):
response = {
"response": type,
"data": data,
"id": id
}
return response.copy()
def request_sender(data):
connection = get_connection(data["id"])
request_ = json.dumps(data)
request_ = request_.encode()
if connection:... | This function handles a client's request to join a game. It checks if the client can access the pre-game hub when the game hasn't started. If valid, it adds the client to the hub, sends access confirmation, and initiates game join; otherwise, it returns an error indicating the game has already started. | def response_join_to_play(data):
global hub
if data["id"] not in hub and not game_started:
print("joining to hub...")
hub.append(data["id"])
response = create_response("get_access_to_hub", None, data["id"])
request_sender(response)
print("joined to hub", data["id"])
... |
def is_row_empty(self, row: ReadOnlyRow) -> bool:
"""
Checks if column is empty contains only empty or whitespace rows.
"""
for index in self.column_mappings.values():
if index > len(row):
# End of row
return True
value = row[index].value
if value is None:
# If ... | This function parses a row from a spreadsheet, checks if it's empty or a header row, validates headers if needed, and returns parsed data as a dictionary or None. It skips empty/headers rows, otherwise processes the row internally for database storage. | def parse_row(self, row: ReadOnlyRow) -> typing.Optional[dict]:
"""
Parses a row and saves parsed instance to database.
"""
if self.is_row_empty(row):
return None
if self.is_header_row(row):
# Sometimes there are copies of header in the XLS, see
# validate_internal_header for the r... |
def cache(self, ending):
return self.CACHES + self.cache_name + ending
def load(self):
"""
fetches the store
"""
fj = self.cache('.json')
fb = self.cache(ending='.bin')
dim, sents = from_json(fj)
self.vstore = VecStore(fb, dim=dim)
self.vstore.load... | The function stores sentences and their embeddings by checking if cached files exist. If not, it generates embeddings, initializes a vector store, adds the embeddings, and saves both the embeddings in a binary file and metadata in a JSON file for future retrieval. | def store(self, sents,multi_cpu=False):
"""
embeds and caches the sentences and their embeddings
unleass this is already done or force=True
"""
fj = self.cache('.json')
fb = self.cache('.bin')
if exists_file(fj) and exists_file(fb):
self.load()
... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def load_and_cache_examples(args, tokenizer, labels, pad_token_label_id, file_path, mode):
# Load data features from cache or dataset fil... | This code trains and evaluates a BERT-based token classification model (like NER) using provided arguments. It handles CUDA/GPU setup, logging, model loading, training with a custom dataset, saving checkpoints, and evaluation/prediction on dev/test sets. The core task is fine-tuning BERT for sequence labeling with opti... | def run_ae_with_args(args):
if os.path.exists(args.output_dir) and os.listdir(
args.output_dir) and args.do_train and not args.overwrite_output_dir:
raise ValueError(
"Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format(
... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def mask_tokens(inputs, tokenizer, args, unigram_similarities=None, bigram_similarities=None):
""" Prepare masked tokens inputs/labels fo... | This code trains a language model using masked language modeling (MLM) with optional custom/bigram masking. It sets up distributed training, optimizers, learning rate scheduling, gradient accumulation, and logging. The model processes batches, computes loss, performs backpropagation, and saves checkpoints. It supports ... | def train(args, train_dataset, model, tokenizer):
""" Train the model """
if args.local_rank in [-1, 0]:
tb_writer = SummaryWriter(log_dir=f'runs/{os.path.basename(args.output_dir)}')
if args.custom_masking:
unigram_similarities = {domain: json.load(open(sim_index)) for domain, sim_index in... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def load_and_cache_examples(args, tokenizer, evaluate=False):
dataset = CustomTextDataSet(tokenizer,
file... | The code trains and evaluates transformer-based models (BERT, RoBERTa, etc.) with checks for required flags (e.g., --mlm for masked language modeling), handles GPU/distributed training setup, loads/configures models and tokenizers, trains on datasets, saves checkpoints, and evaluates model performance. It ensures prope... | def main(args):
if args.model_type in ["bert", "roberta", "distilbert"] and not args.mlm:
raise ValueError("BERT and RoBERTa do not have LM heads but masked LM heads. They must be run using the --mlm "
"flag (masked language modeling).")
if args.eval_data_file_domain_1 is None a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.