dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def __len__(self):
return int(len(self.all_batches) / self.batch_size)
def __getitem__(self, idx):
batch_images = self.all_batches[idx * self.batch_size : (idx + 1) * self.batch_size]
X = []
y = []
for batch_image in batch_images:
image_path = os.path.join(se... | This code defines an iterable object that yields items one by one using __getitem__ during iteration. When the last item is reached, it triggers the on_epoch_end() method, commonly used to perform actions like data shuffling or resetting states at the end of an epoch in machine learning workflows. | def __call__(self):
for i in range(self.__len__()):
yield self.__getitem__(i)
if i == self.__len__()-1:
self.on_epoch_end() |
def showStartScreen(SCREEN,FPS):
titlefont = pygame.font.Font('freesansbold.ttf', 100)
titleText = titlefont.render('PYGLIDE.', True, DARKGREEN)
if FPS is None:
FPS = 3
while True:
SCREEN.fill(BGCOLOR)
titleTextRect = titleText.get_rect()
titleTextRect.center = (WINDOWWID... | The main task of the code is to run a Snake game using Pygame, handling level selection, game speed adjustment, and screen transitions. It initializes game components, displays a start screen, lets players choose a level, sets FPS based on the level, runs the game loop, and shows a game-over screen after each round. | def main(SCREEN):
global CLOCK, FONT, level, FPS
pygame.init()
CLOCK = pygame.time.Clock()
FONT = pygame.font.Font('freesansbold.ttf', 18)
pygame.display.set_caption('Snake Game')
showStartScreen(SCREEN,FPS=None)
while True:
pygame.mixer.music.play(-1, 0.0)
level = showLevel... |
def find_riders(det):
riders = []
combined = set()
person = 0
for *xyxy, _, cls in reversed(det):
motorcycle = 0
for *xyxy2, _, cls2 in reversed(det):
if (int(cls) == 0 and int(cls2) == 3) and (person not in combined and motorcycle not in combined):
iou,combin... | The code detects people in images using YOLOv7, then identifies smoking behavior via a secondary model. It labels individuals as "Merokok" (smoking) or "Tidak Merokok" (not smoking), annotates images with bounding boxes, and saves results. The function returns detailed detection data including labels, confidence scores... | def detect(inputImage, classes=None, threshold=0.25, saveDir="storage/result", weights=["weights/yolov7.pt"], imageSize=640, save_img=True):
source, weights, view_img, save_txt, imgsz, trace = inputImage, weights, False, False, imageSize, False
# Directories
save_dir = Path(saveDir)
# Initialize
set... |
def get_all_data(self, data_path):
data = {}
try:
data['train'] = json.load(open(data_path+'doc2dial_dial_train.json', 'r'))
data['validate'] = json.load(open(data_path+'doc2dial_dial_validation.json', 'r'))
data['doc'] = json.load(open(data_path+'doc2dial_doc.json', ... | This code initializes a Doc2dial data reader by loading or preprocessing dataset, configuring a tokenizer with special tokens, and setting up necessary IDs for padding and sequence boundaries. It checks for preprocessed JSON files, processes raw data if needed, and prepares the dataset for training by adding special to... | def __init__(self, tokenizer, data_path, context_scheme):
self.nlp = spacy.load('en_core_web_sm')
if os.path.exists(cfg.data_path+'preprocessed_data({}).json'.format(cfg.preprocess_style)):
self.data = json.load(open(cfg.data_path+'preprocessed_data({}).json'.format(cfg.preprocess_style), 'r... |
def get_all_data(self, data_path):
data = {}
try:
data['train'] = json.load(open(data_path+'doc2dial_dial_train.json', 'r'))
data['validate'] = json.load(open(data_path+'doc2dial_dial_validation.json', 'r'))
data['doc'] = json.load(open(data_path+'doc2dial_doc.json', ... | This code initializes a dialogue data reader by loading or preprocessing JSON data, configuring a tokenizer with special tokens, and setting up necessary configurations for training. It checks for preprocessed data, processes raw data if needed, and stores results, while initializing tokenizer parameters like padding a... | def __init__(self, tokenizer, data_path):
self.nlp = spacy.load('en_core_web_sm')
if os.path.exists(cfg.data_path+'span_preprocessed_data({}).json'.format(cfg.preprocess_style)):
self.data = json.load(open(cfg.data_path+'span_preprocessed_data({}).json'.format(cfg.preprocess_style), 'r'))
... |
def get_all_data(self, data_path):
data = {}
try:
data['train'] = json.load(open(data_path+'doc2dial_dial_train.json', 'r'))
data['validate'] = json.load(open(data_path+'doc2dial_dial_validation.json', 'r'))
data['doc'] = json.load(open(data_path+'doc2dial_doc.json', ... | The code initializes a data processor for a dialogue system, loading or preprocessing data from a specified path. It uses spaCy for NLP tasks, checks for preprocessed JSON files, and processes raw data if needed. It configures token IDs for special tokens (padding, start/end markers) using a given tokenizer, adds speci... | def __init__(self, tokenizer, data_path):
self.nlp = spacy.load('en_core_web_sm')
if os.path.exists(cfg.data_path+'judger_preprocessed_data({}).json'.format(cfg.preprocess_style)):
self.data = json.load(open(cfg.data_path+'judger_preprocessed_data({}).json'.format(cfg.preprocess_style), 'r')... |
def rescale_transform(img, out_range=(0, 1)):
img = img - img.min()
img /= (img.max() - img.min())
img *= (out_range[1] - out_range[0])
return img
def run_epoch_adv(self):
for idx, (source_sample, target_sample) in enumerate(zip(self.source_dataloader_AAN, self.target_dataloader_AAN)): # spect... | The code trains a model with adversarial and segmentation branches using random inputs. It initializes parameters, iterates over epochs, alternates between adversarial and segmentation tasks, computes loss with BCELoss, and saves model weights periodically. The commented sections suggest potential image loading and los... | def train_ran(self):
input = rescale_transform(torch.normal(mean=0.5, std=1, size=(1, 3, 512, 512), device=self.device))
input.requires_grad_(True)
'''
source_img = Variable(grey_to_rgb(transforms.ToTensor()(pil_loader(CIRRUS_SAMPLE))).unsqueeze(0).cuda(), requires_grad=False)
ta... |
def set_train(self):
"""Convert all models to training mode
"""
for m in self.models.values():
m.train()
def process_batch(self, inputs):
for key, ipt in inputs.items():
if key != 'case_name':
inputs[key] = ipt.to(self.device)
outputs = {}... | The code executes a single training epoch, performing forward and backward passes on batches from the training data loader, optimizing the model via gradient descent, and logging training metrics. It also triggers validation (`self.val()`) at specified intervals defined by `log_frequency`, ensuring periodic evaluation ... | def run_epoch(self):
"""Run a single epoch of training and validation
"""
print("Training")
self.set_train()
for batch_idx, inputs in enumerate(self.train_loader):
before_op_time = time.time()
outputs, losses = self.process_batch(inputs)
self.m... |
def set_train(self):
"""Convert all models to training mode
"""
for m in self.models.values():
m.train()
def process_batch(self, inputs):
for key, ipt in inputs.items():
if key != 'case_name':
inputs[key] = ipt.to(self.device)
outputs = {}... | The main task of the code is to execute one training epoch by iterating through training data, computing model outputs and losses, performing backpropagation with gradient updates, and logging training metrics. It also triggers validation checks at specified intervals defined by log_frequency, ensuring model optimizati... | def run_epoch(self):
"""Run a single epoch of training and validation
"""
print("Training")
self.set_train()
for batch_idx, inputs in enumerate(self.train_loader):
before_op_time = time.time()
outputs, losses = self.process_batch(inputs)
s... |
def jumpMoves(whiteParam, blackParam, kingParam, color):
jumpChains = []
jumpFunc = ""
currWhite = whiteParam
currBlack = blackParam
currKings = kingParam
# Do the first pass to find possible jump moves
if color == "BLACK":
jumpFunc = blackJump
else:
jumpFunc = whiteJump... | The function generates all valid successor board states and corresponding moves for a checkers game, prioritizing mandatory jumps. It first retrieves jump moves; if none exist, it uses adjacent moves. For jumps, it recursively explores all possible jump paths, while for regular moves, it updates board states by moving ... | def successors(whiteParam, blackParam, kingParam, colorParam):
currMoves = jumpMoves(whiteParam, blackParam, kingParam, colorParam)
if not currMoves:
currMoves.append(adjMoves(whiteParam, blackParam, kingParam, colorParam))
# Initialize successorBoards and first check if there aren't any valid move... |
def convert_country_data_datestring_keys_to_datetime(country_data: dict):
country_data["cases"] = convert_dict_string_keys_to_datetime(country_data["cases"])
country_data["recovered"] = convert_dict_string_keys_to_datetime(country_data["recovered"])
country_data["deaths"] = convert_dict_string_keys_to_datet... | The function processes a country's daily data by converting date keys to datetime objects, calculating new cases, adjusting deaths/recovered data within the date range, and converting datetime keys back to date strings for the output. | def process_country_daily_data(country_data : dict):
country_data = convert_country_data_datestring_keys_to_datetime(country_data)
max_date = max(country_data["cases"].keys())
min_date = min(country_data["cases"].keys())
country_data = process_deaths_and_recovered_daily_data(country_data, min_date, max_... |
def priorOutputSigmaPoints(k, index):
return priorSigmaPointEstimations(k, index)
def outputSigmaPoints(k):
priorOutputs = 0
scalarWeightWix = 1 / (2 * (L + mu))
for i in range(2*L):
if i == 0:
priorOutputs += scalarWeightW0x * priorOutputSigmaPoints(k, i)
else:
... | The code computes the cross-covariance between prior sigma points and output sigma points using scalar weights. It iterates over sigma points, calculates weighted differences, and accumulates their product to estimate cross-covariance for a given state index k, likely in an Unscented Kalman Filter context. | def crossCovariance(k):
crossCovariance = 0
scalarWeightWiy = 1 / (2 * (L + mu))
for i in range(2*L):
if i == 0:
crossCovariance += scalarWeightW0y * (priorOutputSigmaPoints(k, i) - outputSigmaPoints(k)) * math.pow(priorOutputSigmaPoints(k, i) - outputSigmaPoints(k), 1)
else:
... |
def validasi_pinjamgadget(datas_gadget_id , datas_gadget_jumlah): #validasi value tiap atribut peminjaman gadget
cek = 0
while cek < 2:
cek = 0
cek_id = input('Masukan ID item: ').upper()
tanggal_pinjam = input('Tanggal peminjaman (DD/MM/YYYY... | The function processes a gadget loan by validating user input, checking existing loans, updating gadget inventory, and recording the transaction. It ensures the gadget exists, the user hasn't exceeded limits, then updates the gadget's stock, logs the loan in a dictionary, converts it back to a list, and adds the transa... | def pinjam(user_name , identity , datas_gadget , buku_hutang_li , gadget_borrow_history):
#list datas secondary (gadget) -> untuk mengecek keberadaan item gadget
datas_gadget_id = [data[0] for data in datas_gadget]
datas_gadget_jumlah = [data[3] for data in datas_gadget]
#VALIDASI DATA
tanggal_... |
def li_to_dic_buku_hutang(buku_hutang_li):
buku_hutang_dic = {"nama" : [] , "nama_gadget": [] , "jumlah" : []}
buku_hutang_dic["nama"] = [data[0] for data in buku_hutang_li]
buku_hutang_dic["nama_gadget"] = [data[1] for data in buku_hutang_li]
buku_hutang_dic["jumlah"] = [int(data[2]) for data in buku_h... | The function processes the return of borrowed gadgets by updating inventory, adjusting debt records, and logging return history. It checks user's borrowed items, validates return data, increments gadget stock, and removes entries if items are fully returned. It maintains consistency across gadget data, debt lists, and ... | def kembalikan(user_name , user_identity , datas_gadget , buku_hutang_li , gadget_borrow_history , gadget_return_history):
#list datas secondary (gadget) -> untuk mengecek keberadaan item gadget
datas_gadget_name = [data[1] for data in datas_gadget]
buku_hutang_dic = li_to_dic_buku_hutang(buku_hutang... |
def _time(now: datetime) -> str:
"""
Return the current time.
now: datetime
A datetime.now() object.
"""
return f"[TIME] {Fore.MAGENTA}{now.strftime('%H:%M:%S')}"
def _date(now: datetime) -> str:
"""
Return the current date.
now: datetime
A datetime.now() object.
""... | The code defines a CLI function to display current time, date, and weather information using formatted outputs. It initializes color settings, retrieves the current datetime, and prints time, date, and weather data with reset formatting. | def cli():
"""Command Line Interface for time, date, and weather information."""
init(autoreset=True)
now: datetime = datetime.now()
print(
f"{_time(now)}{Fore.RESET}\n{_date(now)}{Fore.RESET}\n{_weather()}{Fore.RESET}"
) |
def analyseMemoryRequest(self):
ret = []
properRequest = self.properMemoryRequest()
if properRequest is None:
return ret
if self.memoryRequest is None:
ret.append(
"Memory request has not set, proper value would be %sMi"
% (math.ce... | The main task of the code is to aggregate results from multiple analysis methods. It collects memory and CPU-related constraints (requests and limits) by calling `analyseMemoryRequest`, `analyseMemoryLimit`, `analyseCpuRequest`, and `analyseCpuLimit`, extending a list (`ret`) with their outputs. Finally, it returns the... | def analyseMessage(self):
ret = self.analyseMemoryRequest()
ret.extend(self.analyseMemoryLimit())
ret.extend(self.analyseCpuRequest())
ret.extend(self.analyseCpuLimit())
return ret |
def tableHeaderRow(self):
tr = self.soup.new_tag("tr")
for header in self.HEADERS:
th = self.soup.new_tag("th")
th.string = header
tr.append(th)
return tr
def tableDataRow(self, workload):
tr = self.soup.new_tag("tr")
self.appendTd(tr, workl... | The code generates an HTML table by creating a table element, adding a header row, populating it with data rows from the workloadList, and appending a footer. It structures the table dynamically using BeautifulSoup, embedding each workload as a row. | def setBody(self, workloadList):
table = self.soup.new_tag("table")
self.soup.body.append(table)
table.append(self.tableHeaderRow())
for workload in workloadList:
table.append(self.tableDataRow(workload))
self.setFooter() |
def create_player_file(file, player):
player_file = file[file['Name'] == player].sort_values(by = 'Date').reset_index(drop = True)
# path = Path('P:/NBA Injuries Python Breakdown/Player Files/' + player + '/Main.csv')
# player_file.to_csv(path)
return player_file
def format_player(player, injury_dates):... | The main task of the code is to process player injury data from a CSV file, generate structured player-specific reports using helper functions, and compile results into a DataFrame containing injury status, dates, and eligibility details. It iterates through each player, extracts relevant information, formats it, and a... | def check_all_players(simple_file, players, player_information):
result_frame = pd.DataFrame(columns = ['Name', 'Injury', 'Start Date', 'Eligible Date', 'Recurrent Met Date', 'Claim Games'])
players = set(simple_file['Name'].tolist())
print(players)
print(len(players))
for player in players:
... |
def create_folder(player):
if not os.path.exists('P:/MLB Python/' + str(player)):
os.makedirs('P:/MLB Python/' + str(player))
return
def create_player_file(main_file, player):
player_file = main_file[main_file['Player ID'] == player]
return player_file
def evaluate_player(player_file, player):
... | The code evaluates each player's injury and eligibility data from input files, aggregates the results into a structured DataFrame, removes duplicates, sorts by claim games, and exports the final data to a CSV file for analysis. | def evaluate_all_players(main_file, players):
result_frame = pd.DataFrame(columns = ['Name', 'Injury', 'Start Date', 'Eligible Date', 'Recurrent Met Date', 'Claim Games'])
for player in players:
create_folder(player)
player_file = create_player_file(main_file, player)
player_sheet = eval... |
def create_folder(player):
if not os.path.exists('P:/MLB Python/' + str(player)):
os.makedirs('P:/MLB Python/' + str(player))
return
def create_player_file(main_file, player):
player_file = main_file[main_file['Player ID'] == player]
return player_file
def evaluate_player(player_file, player):
... | The main task of the code is to evaluate injury timelines for multiple players by processing individual player data, aggregating formatted results into a structured DataFrame, and exporting the compiled information (including injury details, dates, and claim games) to a CSV file for analysis. | def timeline_evaluate_all_players(main_file, players):
print('TIMELINEEVALALLPLAYERS')
result_frame = pd.DataFrame(columns = ['Name', 'Injury', 'Start Date', 'Eligible Date', 'Recurrent Met Date', 'Claim Games'])
for player in players:
create_folder(player)
player_file = create_player_file(m... |
def update(self, data, user = None):
self.visit_page('questions')
if user is None:
user = AnonymousUser()
self.state.update(data, self.log, user)
def add_tag(self, tag):
self.update({'tags': set([tag])})
def assert_tags_are(self, *args):
self.assertEqual(self.state.ta... | This test verifies that setting a query and adding a tag are correctly recorded in the state, and that resetting the query (by setting 'reset_query': True) clears the query value without affecting existing tags. It checks the state's query and tags after each operation to ensure proper functionality. | def test_query_and_tags1(self):
self.update({'query': 'hahaha'})
self.add_tag('tag1')
self.assertEquals(self.state.query, 'hahaha')
self.assert_tags_are('tag1')
self.update({'reset_query':True})
self.assertEquals(self.state.query, None)
self.assert_tags_are('tag1'... |
def add_tag(self, tag):
self.update({'tags': set([tag])})
def assert_tags_are(self, *args):
self.assertEqual(self.state.tags, set(args))
def remove_tag(self, tag):
self.update({'remove_tag': tag}) | This test verifies the functionality of adding and removing tags sequentially. It checks that tags are correctly appended and removed, ensuring the final state matches expectations after each operation. The test confirms that multiple tags can be added, removed individually, and the system correctly tracks the remainin... | def test_add_remove_tags(self):
self.add_tag('tag1')
self.assert_tags_are('tag1')
self.add_tag('tag2')
self.assert_tags_are('tag1', 'tag2')
self.add_tag('tag3')
self.assert_tags_are('tag1', 'tag2', 'tag3')
self.remove_tag('tag3')
self.assert_tags_are('tag1... |
def reinstate_loggers(self):
""" Set the saved logger handlers to the current logger. """
for name, handlers in self.logger.items():
logging.getLogger(name).handlers = handlers
def pathstr(key: str, *args: str) -> str:
""" Wrapper to get the path (as string! Because MADX wants strings)
... | This function sets up a nominal accelerator lattice configuration by initializing beam parameters, loading optics and sequence data, applying slicing and cycling for orbit calculations, defining beam optics, and saving twiss data for later use in corrections. It handles year-specific file paths, injection optics adjust... | def setup_machine(self):
""" Nominal machine setup function.
Initialized the beam and applies optics, crossing. """
self.reinstate_loggers()
madx = self.madx # shorthand
mvars = madx.globals # shorthand
# Load Macros
madx.call(pathstr("optics2018", "toolkit", "... |
def reinstate_loggers(self):
""" Set the saved logger handlers to the current logger. """
for name, handlers in self.logger.items():
logging.getLogger(name).handlers = handlers
def pathstr(key: str, *args: str) -> str:
""" Wrapper to get the path (as string! Because MADX wants strings)
... | The main task of the code is to apply magnetic and structural errors to a particle accelerator model using MADX, simulating uncorrected machine states. It loads error subroutines, reads measured error tables, applies errors to specific elements (e.g., dipoles, quadrupoles), and saves uncorrected twiss parameters and er... | def apply_errors(self):
""" Apply the errors onto the machine. The state is uncorrected afterwards. """
self.reinstate_loggers()
madx = self.madx # shorthand
if self.df_twiss_nominal is None:
raise EnvironmentError("The machine needs to be setup first, before applying error... |
def find_influancers(G):
"""
Find influencers in the network
Parameters
----------
G : graph
Returns
-------
List of nodes
"""
# calculating the number of nodes in our data
nodes = G.number_of_nodes()
# changing the number of top nodes depending on the nu... | The main task of the code is to identify and return a list of nodes in a network graph based on a specified role (e.g., 'Influencers', 'Followers', 'Bridges', 'Neutrals'). It uses conditional logic to call corresponding helper functions (`find_influencers`, `find_followers`, etc.) that determine nodes matching the role... | def return_nodes(G, word):
"""
Find the nodes with the specified role in the network
Parameters
----------
G : graph
word : str
Returns
-------
List of nodes
"""
if word == 'Influencers':
nodes = find_influancers(G)
elif word == 'Follow... |
def blank_figure():
"""
Function that takes no parameters and returns a completely ampty figure
"""
fig = go.Figure(go.Scatter(x=[], y = []))
fig.update_layout(paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)')
fig.update_xaxes(showgrid = False, showticklabels = ... | The function computes network parameters and visualizations for all combinations of countries and professions, using nodes and edges data. It generates a structured dictionary with metrics like node count, connections, average degree, and plots for categories such as Influencers and Neutrals, handling 'All' selections ... | def all_combinations(nodes, edges, categories=['Influencers', 'Followers', 'Bridges', 'Neutrals', 'None']):
"""
Calculate all the necessary parameters and figures for all the combinations
of countries and professions, and figures with different node categories.
Parameters
----------
nodes : pan... |
def blank_figure():
"""
Function that takes no parameters and returns a completely ampty figure
"""
fig = go.Figure(go.Scatter(x=[], y = []))
fig.update_layout(paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)')
fig.update_xaxes(showgrid = False, showticklabels = ... | The function calculates network statistics and generates visualizations for user categories within a specified date range. It filters nodes and edges, constructs a graph, computes metrics like node count, connections, and average degree, and produces centrality distribution plots. For each category, it creates a graph ... | def other_combinations(nodes, edges, start_date, end_date, categories=['Influencers', 'Followers', 'Bridges', 'Neutrals', 'None']):
"""
Function which calculates all the necessary parameters and
figures for specific countries, professions and also date
Parameters
----------
nodes : pandas data... |
def menu(self):
self.top4 = Toplevel()
self.top4.geometry('1600x900')
bk = Label(self.top4,relief='sunken',bd=15,bg = 'Deepskyblue')
bk.place(x=0,y=0,relheight = 1,relwidth = 1)
label = Label(self.top4,text="SELECT YOUR OPTION",font=("Times", 25,'bold'),bg = 'Deepskyblue... | This function verifies an entered PIN against a stored value. If correct, it proceeds to a menu; if incorrect, it decrements attempt count, updates the balance, blocks the card if attempts exhaust, and displays error messages. | def check_pin(self):
entered_pin = self.e.get()
self.top2.destroy()
if (int(entered_pin)== self.pin):
print("pin verified")
self.menu()
else:
self.pin_count-=1
self.edit_balance("pin_count")
if self.pin_count==0:
... |
def input_validate(self, text, type):
if not self.is_validating:
self.is_validating = True
if type == 'avax':
gv.AVAX = float(text)
elif type == 'flsh':
gv.FLSH = float(text)
elif type == 'days':
gv.DAYS = int(text)
... | This code creates a UI interface for inputting and displaying cryptocurrency-related values (AVAX, FLSH, rFLSH) with validation, calculates squad-based gains and costs, and dynamically updates prediction labels showing projected earnings, conversion rates, and next claim dates. It organizes inputs, results, and metrics... | def on_parent(self, instance, par):
box_inside_1 = BoxLayout(orientation='horizontal', size_hint_y = None, height=dp(50))
avax_label = Label(text='AVAX to Spend: ', size_hint_y=None, height=dp(50), halign='right', valign='middle', text_size=(dp(gv.APP_WIDTH/11), None), size_hint_x=None, width=dp(gv.APP_... |
def _play(self, uri: str) -> None:
"""Starts playback of uri on jukebox."""
if "spotify:track:" in uri:
self.sp.start_playback(device_id=self.device_id, uris=[uri])
self.current_state = self.playing
else:
self.sp.start_playback(device_id=self.device_id, contex... | This function is a generator that processes commands to control media playback. It continuously awaits commands, executing actions like play/pause, stop, forward, reverse, or shuffle based on the received command. If "play/pause" includes a track name, it plays the song; otherwise, it toggles pause. Unknown commands tr... | def _create_playing(self) -> Generator:
while True:
command: str = yield
if command[0].lower() == "play/pause":
if command[1] != "":
# actually call the function to play the song
self._play(command[1])
else:
... |
def _play(self, uri: str) -> None:
"""Starts playback of uri on jukebox."""
if "spotify:track:" in uri:
self.sp.start_playback(device_id=self.device_id, uris=[uri])
self.current_state = self.playing
else:
self.sp.start_playback(device_id=self.device_id, contex... | This code defines a generator function that handles playback control commands when a device is paused. It processes commands like 'play/pause' (to resume or start playback), 'stop', 'forward', 'reverse', and 'randomize' (shuffle toggle). The function yields to receive commands, executes corresponding actions (e.g., res... | def _create_paused(self) -> Generator:
while True:
command: str = yield
if command[0].lower() == "play/pause":
if command[1] != "":
# actually call the function to play the song
self._play(command[1])
elif self._acti... |
def _create_stopped(self) -> Generator:
while True:
command: str = yield
if command[0].lower() == "play/pause":
if command[1] != "":
# actually call the function to play the song
self._play(command[1])
else:
... | This code initializes a Spotify controller by setting up playback states (stopped, playing, paused), authenticating with Spotify using credentials, configuring repeat/shuffle settings, loading records, and starting a background thread for continuous state updates and playback management. | def __init__(self):
self.stopped = self._create_stopped()
self.playing = self._create_playing()
self.paused = self._create_paused()
self.current_state = self.stopped
self.username = SPOTIFY_USERNAME
self.sp, self.sp_auth, self.token = spotipy_instance(username=self.user... |
def get_holiday(ibge_code, date):
"""
Gets a holiday
Args:
ibge_code (string): IBGE code
date (string): Data that might have a holiday
Return:
(Message, code): Return the message result of the get method and the http code
"""
try:
# Check if date is valid
... | This function handles holiday-related API operations (GET, PUT, DELETE) based on the provided IBGE code and holiday information. It retrieves holiday data, adds/upgrades holidays (with flexible date checks), and deletes holidays, returning appropriate messages and HTTP status codes for each operation. | def holiday_methods(ibge_code=None, holiday_info=None):
"""
Setup of all holiday routes and methods of the api
Args:
ibge_code (string): IBGE code
holiday_info (string): Data that might have a holiday date or
holiday name
Return:
(Message, code):... |
def get_xy_center(orbit, image):
"""
Using the target name or MPC file or list of x/y positions, determine the source location in this image.
:param orbit: the orbit object used to compute the ra/dec location of source to centre on.
:param image: an image object that contains the meta-data about the ima... | The code stacks FITS images centered on a celestial object's orbit, creating time-lapse datasets. It calculates cutouts around the orbit's predicted position, applies sky subtraction, masks outliers, and combines images into stacks. When the time duration between stacks exceeds a threshold, it saves the median-combined... | def build_stack(time_sorted_images, orbit,
stack_duration=60 * units.minute, dim=256, output_basename=None, clip=True):
"""
Based on an input .mpc file (a file with MPC formated observations) compute an orbit and
using that orbit stack fits images. We also require a .cat file for each .fits... |
def get_tiled_keypoints(self, img, tile_h, tile_w):
"""AndCompute
Splits the image into tiles and detects the 10 best keypoints in each tile
Parameters
----------
img (ndarray): The image to find keypoints in. Shape (height, width)
tile_h (int): The tile height
... | The main task of the code is to compute the 4x4 transformation matrix between two consecutive frames using stereo image pairs. It tracks keypoints between frames, calculates disparities from left-right image pairs, derives 3D points from disparities, and estimates the transformation matrix using these 3D point correspo... | def get_pose(self,old_imgL, old_imgR, new_imgL, new_imgR):
"""
Calculates the transformation matrix for the i'th frame
Parameters
----------
i (int): Frame index
Returns
-------
transformation_matrix (ndarray): The transformation matrix. Shape (4,4)
... |
def validate_dna(dna_seq):
""" Checks if DNA sequence is valid. Returns True is sequence is valid, or False otherwise. """
seqm = dna_seq.upper()
set_basis = {"A", "T", "C", "G"}
s = (set(dna_seq) - set_basis)
if (set_basis - set(dna_seq)):
raise Exception(f"There are different characters in... | The function `all_orfs` computes all possible proteins from all open reading frames (ORFs) in a given DNA sequence. It validates the DNA, generates all reading frames, and translates each into proteins using `all_proteins_rf`. If `return_positions` is `True`, it also returns the start positions of these proteins. The r... | def all_orfs(dna_seq, return_positions=False):
"""Computes all possible proteins for all open reading frames."""
assert validate_dna(dna_seq), "Invalid DNA sequence"
lt_all_rf = reading_frames(dna_seq)
f = lambda x: all_proteins_rf(x, return_positions)
if return_positions:
lt_proteins = list... |
def is_eof(file_line):
return not file_line
def update_frequency(seq, current_dic):
""" Calculates the frequency of each symbol in the sequence. Returns a dictionary. """
for s in seq.upper():
if s in current_dic:
current_dic[s] += 1
def update_codons(seq_line, codons_stats):
for idx... | The code reads a FASTA file to analyze a DNA sequence. It calculates nucleotide frequencies (A, T, C, G), GC content, and codon usage. It processes the sequence line by line, aggregates statistics, and identifies open reading frames (ORFs). Finally, it prints results and checks for overlaps. The function handles file o... | def calculate_and_print_stats():
fasta_file = open(sys.argv[1], "r", 1024)
full_dna_seq = ""
try:
sequence_len = 0
nucleotides_stats = {'A': 0, 'T': 0, 'C': 0, 'G': 0}
codons_stats = {}
remaining = ""
fasta_file.readline() # skips the first line
while True:
... |
def frequency(s, k, steps):
""" Calculates the frequency of each symbol in the sequence. Returns a dictionary. """
d = {}
for i in range(0, len(s) - k + 1, steps):
if s[i:i+k] in list(d.keys()):
d[s[i:i+k]]+=1
else:
d[s[i:i+k]]=1
return d
def gc_content(dna_seq):
... | The main task of the code is to analyze a DNA sequence by calculating statistical properties (length, frequency, GC content, codon usage), identifying open reading frames (ORFs) across all reading frames, filtering ORFs by length (>40 amino acids), resolving overlaps by selecting longest ORFs, and generating output fil... | def main(sequence):
pdf_proteins = pd.read_csv(folder_path+"proteins_86693_757732.csv")
'''
=====================================//=====================================
STEP 00 - Get statistics
=====================================//=====================================
In this step, we are app... |
def validate_dna(dna_seq):
""" Checks if DNA sequence is valid. Returns True is sequence is valid, or False otherwise. """
seqm = dna_seq.upper()
set_basis = {"A", "T", "C", "G"}
s = (set(dna_seq) - set_basis)
if (set_basis - set(dna_seq)):
raise Exception(f"There are different characters in... | The code's main task is to validate a DNA sequence and, if valid, compute and display its transcription, reverse complement, GC content, direct translation, and proteins from all ORFs sorted by decreasing size. It serves as a testing tool for bioinformatics analyses of DNA sequences. | def test_all():
seq = input("Insert DNA sequence:")
if validate_dna (seq):
print ("Valid sequence")
print ("Transcription: ", transcription (seq))
print("Reverse complement:", reverse_complement(seq))
print("GC content (global):", gc_content(seq))
print("Direct translatio... |
def read_seq_from_file(filename):
""" Reads a sequence from a multi-line text file. """
fh = open(filename, "r")
lines = fh.readlines()
seq = ""
for l in lines:
seq += l.replace("\n","")
fh.close()
return seq
def validate_dna(dna_seq):
""" Checks if DNA sequence is valid. Returns... | The code processes a DNA sequence file by validating its content, transcribing it, calculating its reverse complement and GC content, translating it directly, identifying all open reading frames (ORFs), and saving each ORF to a separate text file. If the sequence is invalid, it notifies the user. | def test_files():
fname = input("Insert input filename:")
seq = read_seq_from_file(fname)
if validate_dna (seq):
print ("Valid sequence")
print ("Transcription: ", transcription (seq))
print("Reverse complement:", reverse_complement(seq))
print("GC content (global):", gc_cont... |
def calculate_cartesian_grid_position(x,y,r):
if(x%2==0):
u=y*2*(sin(pi/6)+1)
v=x*cos(pi/6)
else:
u=(1+y*2)*(sin(pi/6)+1)
v=x*cos(pi/6)
return r*u,r*v
def calculate_hexpoints_from_tl(u,v,r):
u_list = [0,1,1+sin(pi/6),1,0,-sin(pi/6)]
v_list = [0,0,cos(pi/6),2*cos(pi/... | The code initializes a graphical user interface for an ant colony hex grid simulation. It sets up a canvas, generates hexagon positions using trigonometric calculations, draws hexagons for each grid space, maps grid elements to canvas objects, positions nest text labels, and triggers the simulation loop. The primary ta... | def initUI(self,agents):
self.master.title("Ant Colony Hex Grid")
self.pack(fill=BOTH,expand=1)
self.canvas = Canvas(self)
self.agents = agents
self.timer = 0
r = 20
start_position = [sin(pi/6)*r,0]
self.grid_spaces = agents.grid.grid.flatten()
... |
def find_any_empty(self):
for row in range(len(self.board)):
for col in range(len(self.board[0])):
if self.get_val((row, col)) == 0:
return (row, col) # Position of empty space on board
return None
def check_validity(self, num: int, pos: tuple) -> bool:
... | This code solves a Sudoku puzzle using backtracking. It recursively fills empty cells with valid numbers (1-9), checks for validity, and backtracks if a placement leads to no solution. The function returns True if a valid solution is found, otherwise False. | def solve(self):
#print("Point A")
empties_left = self.find_any_empty()
if not empties_left:
#print("Point END")
return True
else:
#print("Point B")
row = empties_left[0]
col = empties_left[1]
for i in range(1,1... |
def choose_random_backups(self,participants, conn):
chosen = random.sample(participants, k=self.k_backups)
for c in chosen:
response = self.request_to_be_backups(c, conn)
if response.status_code != 200:
return False, None
return True, chosen
def broadcast_... | The main task of the code is to repeatedly select random backup participants until a valid selection is made, then broadcast the chosen backups, update the backup list, and request deletion of obsolete entries. It ensures successful backup coordination by looping until a valid choice is confirmed, managing the backup l... | def make_backups(self,data, conn):
status = False
participants = data['participants']
while not status:
status, chosen = self.choose_random_backups(participants, conn)
if not status:
continue
status = self.broadcast_backups_to_booth(chosen, par... |
def _reload_config():
if before_2_0_64:
cli_ctx.config.config_parser.read(GLOBAL_CONFIG_PATH)
return cli_ctx.config
else:
return CLIConfig(config_dir=GLOBAL_CONFIG_DIR, config_env_var_prefix=ENV_VAR_PREFIX)
def get_arguments(command):
if not ARGUMENTS_LOADED.get(command.name):
... | This function populates missing arguments of a command with their configured defaults from the application's configuration. It reloads the config, iterates through each argument of the command, checks if the argument exists in the provided arguments object, and if not, retrieves and assigns the default value from the c... | def _add_defaults(command, arguments):
config = _reload_config()
for name, argument in get_arguments(command).items():
if not hasattr(arguments, name):
default = _find_configured_default(config, argument)
if default:
setattr(arguments, name, default)
return a... |
def get_argument_value_completions(command_table, query, verbose=False):
list = get_argument_value_list(command_table, query, verbose) + \
get_global_argument_value_list(query, verbose)
return [ {
'name': item,
'kind': 'argument_value',
'snippet': '"' + item + '"' if ' ' in item ... | This function generates command-line completion suggestions based on the query's structure. It checks for arguments, subcommands, or snippets, returning relevant completions from command tables or groups. If a subcommand isn't found, it outputs an error message when verbose mode is enabled. | def get_completions(group_index, command_table, snippets, query, verbose=False):
if 'argument' in query:
return get_argument_value_completions(command_table, query, verbose)
if 'subcommand' not in query:
return get_snippet_completions(command_table, snippets) + get_prefix_command_completions(gro... |
def get_player_replay():
'''
Gets the player answer whether wants to replay the game to increase their hi-score:
player_answer_replay = input('Would you like to play again to increase your high score? y/n: ').lower()
Handles answer error cases with a while True loop (try, except Exception as e, else) an... | The main task of the code is to enable replaying the Hangman game by resetting variables, updating scores, and looping until the player chooses to stop. It handles player input, resets game state, displays visuals, and updates the high score during each replay session. | def replay_hangman(hi_score):
'''
sets the get_player_replay() function to the player_answer_replay variable:
player_answer_replay = get_player_replay()
The get_player_replay() function ask the player: input('Would you like to play again to increase your score? y/n: ').lower()
and gives the player f... |
def update_density(self):
'''
Update density and spacial derivatives of density
'''
# zero all values
for i in range(self.N):
self.rho[i] = 0.0
self.drho_1[i] = ti.Vector([0.0, 0.0])
self.drho_2[i] = ti.Matrix([[0.0, 0.0], [0.0, 0.0]])
... | The code's main task is to advance a simulation by one time step, updating the system's density, pressure, and other properties through three sequential update methods: `update_density()`, `update_pressure()`, and `update()`. This function encapsulates the temporal progression of a physical or computational model, ensu... | def step(self):
'''
Step forward in time
'''
self.update_density()
self.update_pressure()
self.update() |
def create_track_bar_callback(self, track_bar_name):
return lambda value: self.update_parameter(track_bar_name, value)
def update(self):
img = self.image_func(self.frames[self.frame_pos])
cv2.imshow(self.window_name, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
def get_config(self):
return Trac... | This code initializes an interactive GUI for adjusting segmentation parameters on a video. It loads the video, preprocesses frames, sets up OpenCV trackbars for parameter tuning, and waits for user input to save configurations. The main task is to provide a visual interface for configuring and testing video segmentatio... | def __init__(self, video_path: Union[str, Path], method: str = 'binary',
roi: Union[bool, tuple, list, np.ndarray, None] = True,
interval: Union[tuple, list, np.ndarray, None] = None, params: Optional[dict] = None,
verbose: int = 0):
self.video_path = video_pat... |
def gen_key(key_dir, key_size=AES.block_size):
key = Random.get_random_bytes(key_size) # 128 bits key
write_file(join_to_path(key_dir, 'secret.key'), key)
return key
def get_dir(file):
if not file:
return None
return os.path.dirname(file)
def get_key(key_file, key_size=AES.block_size):
... | This function encrypts a file using AES-CBC mode with a specified key, padding data to 16-byte blocks, and writes the encrypted result to an output file. It stores the original file size and initialization vector (IV) at the beginning of the encrypted file for decryption. If no output file is provided, it appends '.enc... | def encrypt_file(key_path, in_file, out_file=None, chunk_size=64 * 1024):
if not out_file:
out_file = in_file + '.enc'
if not key_path:
key = gen_key(get_dir(out_file))
else:
key = get_key(key_path)
iv = gen_iv()
encryptor = AES.new(key, AES.MODE_CBC, iv)
file_size = get... |
def __init_snake(self):
snake = []
x0 = self.field_width // 2
y0 = self.field_height // 2
for i in range(Snake.INITIAL_LENGTH):
snake.append({'x': x0, 'y': y0 + i})
return snake
def __init_food(self):
food = {'x': 0, 'y': 0}
while True:
... | The `reset` method reinitializes the game state by resetting the snake, food position, movement direction, and steps counter. It prepares the environment for a new game or training iteration, then returns the current state representation for the AI to process. | def reset(self):
self.snake = self.__init_snake()
self.food = self.__init_food()
self.direction = {'dx': 0, 'dy': -1}
self.steps_without_food = 0
return self.__get_state() |
def __get_direction(self, action: int):
dx, dy = self.direction['dx'], self.direction['dy']
if action == Snake.TURN_LEFT:
return dy, -dx
if action == Snake.TURN_RIGHT:
return -dy, dx
return dx, dy
def __move_snake(self, dx, dy) -> str:
head = self.snake... | This function executes a single step in a snake game environment by applying an action, updating the snake's direction, moving it, checking for terminal conditions (collision with wall/self or no food), and returning the new state, reward, and done status. | def step(self, action: int) -> Tuple[np.ndarray, float, bool]:
if not self.action_space.contains(action):
raise ValueError(f"Action {action} is invalid")
if self.snake is None:
raise ValueError("State is none. Call reset before using step method")
dx, dy = self.__get_di... |
def hdp_stats(pdf, col_width, df, sens_pos_df):
pdf.set_font("helvetica", style="", size=9)
pdf.multi_cell(
w=col_width,
h=5,
txt="All simulations are run with the following static parameters:",
border=0,
ln=2,
)
pdf.multi_cell(
w=col_width,
h=5,
... | The code generates a landscape A4 PDF report with a background image, structured columns for "Hidden Node Detected" statistics and "Data Analytics" explanations, a colored table from input dataframes, embedded plots, and outputs the file as "Cascoda_Report.pdf" | def make_pdf(reduced_df, sens_pos_df, sim_run_df):
pdf = FPDF(orientation="L", unit="mm", format="A4")
pdf.add_page()
pdf.set_font("helvetica", style="B", size=16)
pdf.image("assets/A4_background.png", x=0, y=0, w=297)
pdf.set_auto_page_break(True, margin=1)
col_width_1 = 80
col_width_2 = 2... |
def tshark_get_filtered_packets(pcap_directory: str, pcap_file: str) -> list[str]:
output = subprocess.run(
["tshark", "-r", pcap_directory + pcap_file, "-Y", "icmpv6"],
capture_output=True,
)
string_output = output.stdout.decode("utf-8").rstrip()
split_string_output = string_output.spli... | The main task of the code is to analyze network traffic from pcap files and a configuration file, calculating statistics such as packet counts, unique sequences, retries, and network efficiency. It processes packets from three nodes, filters responses, computes metrics like response rates and theoretical maximums, and ... | def get_stats(pcap_directory, config_file_path) -> dict[str, Any]:
print(f"stats for pcap {pcap_directory} and config {config_file_path}")
stats = dict[str, Any]()
packets_list_node0 = tshark_get_filtered_packets(
pcap_directory, pcap_file="pkt-0-0.pcap"
)
packets_list_node1 = tshark_get_fil... |
def find_augmenting_path():
global parent
forest_nodes = set()
queue = []
verticles_marked = [0 for _ in range(m)]
edges_marked = [[0 for _ in range(m)] for _ in range(m)]
parent = [-1 for _ in range(m)]
verticles_and_blossoms_n = blossom_index
printDebug('verticle_blossom:', verticle_blossom)
for v... | The code implements a recursive algorithm to find a maximum matching in a graph by repeatedly searching for augmenting paths. If an augmenting path is found, it updates the matching, increments the result count, and recurses. If no path exists, it returns the current maximum matching size. Debugging information is prin... | def find_maximum_matching(_debug=False):
global res, debug, blossom_index
debug = _debug
path = find_augmenting_path()
if path:
augment(path)
printDebug('new matching:', mathching_to_string())
res += 2
blossom_index = n
return find_maximum_matching(_debug)
printDebug('no path found:',... |
def build_graph(l):
graph = {}
n = len(l)
for i in range(n):
graph[i] = set();
for i in range(n-1):
for j in range(i+1, n):
if arePairs(l[i], l[j]):
graph[i].add(j)
graph[j].add(i)
return graph, n
def init_blossom_params(_graph, _n):
global blossom_verticles, blosso... | The code computes the maximum matching in a graph using the Blossom algorithm, then returns the number of unmatched vertices by subtracting the matched count from the total vertex count `n`. It builds a graph from input `l`, initializes parameters for handling blossoms (odd-length cycles), executes the matching algorit... | def solution(l, _debug=False):
graph, n = build_graph(l)
init_blossom_params(graph, n)
find_maximum_matching(_debug)
return n - get_matched_verticles() |
def read_smiles_file(smiles_file, readHeader=False, idColumn=1, delimiter=None):
smiles = []
ids = []
if smiles_file.endswith('.gz'):
reader = gzip.open(smiles_file, 'rt')
else:
reader = open(smiles_file, 'rt')
if readHeader:
header = reader.readline()
mol_idx = 0
w... | (The main task of the code is to process molecular fragments and/or SMILES strings, either placing them onto a protein structure or combining fragments into a single molecule, then outputting the results in SDF format. It handles command-line arguments for input files, placement parameters, output configuration, and lo... | def main():
# Example (combine):
# ./merger.py -f data/diamond-x0216_A.mol data/diamond-x0259_A.mol -p data/mac1.pdb -o output/foo.sdf
#
# Example (placement):
# ./merger.py -f data/x0032_0A.mol data/x0103_0A.mol -p data/apo_example1.pdb --smiles-file data/inputs.smi -o output/foo.sdf
#
... |
def select_config_file_path(self, file_type, file_path):
if file_path is not None:
config_path = file_path
else:
if file_type == 'client' or file_type == 'user':
config_path = self.default_configuration_file
elif file_type == 'credential':
... | This code initializes a configuration object by setting its type, selecting a configuration file path and section, loading the configuration, applying provided parameters, and parsing them to prepare for further use. | def __init__(
self, config_type, section_name, config_file=None,
**config_parameters : tuple):
self.config_type = config_type
self.config_path = self.select_config_file_path(
config_type, config_file)
self.config_section = self.select_config_section(section_na... |
def _find_positions(self, code):
if code == [1, 0, 1]:
return 1
elif code == [0, 0, 1]:
return 2
elif code == [0, 1, 1]:
return 3
elif code == [0, 1, 0]:
return 4
elif code == [1, 1, 0]:
return 5
elif code == [1,... | The code monitors motor health by analyzing hall sensor data to detect position changes, calculates RPM, checks for stalls (via position inactivity or low RPM), logs RMS current and RPM to CSV, and identifies overcurrent or stall conditions, returning status messages or "All Good!" if no issues are detected. | def health_check(self, temp_data):
code = [0,0,0]
self.csv_data = []
for i in range(1,4): # Turn hall sensor sensor data into a 3-digit position code
if(temp_data[i] > 1650): # Set a threshold of 1500mV for the hall pulse
code[i-1] = 1
else:... |
def file_open(timestamp, name, action):
file = open(MOTOR_PATH + timestamp + name, action, newline='')
return file
def end_sequence(MC):
MC.killall()
def message_display(msg, desired_answer):
while(1):
if input(msg).lower() == desired_answer:
return 1
else:
print(... | The code runs motor tests with different PWM settings, collects RMS and RPM data, analyzes results, and logs pass/fail status. It initializes motor controllers, executes burn-in and two test modes, writes diagnostic data to CSV files, calculates RMS values, checks thresholds, and determines test outcomes. Files are man... | def run_main():
if(os.path.exists("/home/pi/Documents/FLEX_DATA_FOLDER/rms_data_full")):
file = file_open('', "rms_data_full", 'a')
pass
else:
file = file_open('', "rms_data_full", 'w')
writer = csv.writer(file)
HEADER = ["TIMESTAMP", "TARGET PWM", "DURATION", "PHASE A mi... |
def get_all_players():
all_players = players.get_players()
player_names = []
for player in all_players:
player_names.append(player['full_name'])
return player_names
def common_player_details(player_id):
player_common_details = commonplayerinfo.CommonPlayerInfo(player_id=player_id)
with... | The code displays selected NBA player statistics and profile details using Streamlit. It allows users to choose a player from a dropdown, fetches their ID, and shows their photo, basic info (birthday, height, team), and career details. If no player is selected, it prompts the user to make a choice. | def player_stats():
player_choice = st.sidebar.selectbox('Select a player:', options=get_all_players(), index=None, placeholder="Select an option...")
if player_choice is not None:
player_id = players.find_players_by_full_name(player_choice)[0]['id']
st.header(f"{player_choice}")
... |
def generate_synthetic_data(
n_samples=10000, positive_U=True, seed=711, n_modes=3, B_noise_scale=1.0,
heteroscedastic_B=True, heteroscedastic_noise=True
):
np.random.seed(seed)
df_U = pd.read_csv('data_synth/msigdb-hallmark_U_indices.csv', index_col=0)
df_C_rna = read_hallmark_df('rna')[df_U.index]... | The main task of the code is to evaluate and compare the performance of multi-modal factor analysis methods (PathFA, MOFA, UNIMODAL, PLIER, FA) on synthetic data across varying subsample sizes. It generates synthetic data, runs each model on subsampled data, computes metrics like log-likelihood and parameter accuracy, ... | def main(svd_init=True, seed=711, n_epochs_pathfa=200, n_epochs_mofa=1000, n_epochs_plier=400,
n_modes=3, B_noise_scale=1.0, het_B=False, het_noise=True):
Y_rna, C_rna, sigma_rna, Y_prot, C_prot, sigma_prot, U, B = generate_synthetic_data(
n_samples=6000, positive_U=True, seed=seed, n_modes=n_mode... |
def total_cumulative_points():
total_points = weekly_total_points().sum().sort_values(ascending=False)
total_points_df = pd.DataFrame(total_points).reset_index()
total_points_df.columns = ["Team", "Total Points"]
return total_points_df
def total_win_loss_points():
points_df = weekly_win_loss_point... | The main task of the code is to combine multiple team-related dataframes (total points, trades, win-loss points, and point differentials) into a single sorted table. It merges dataframes on the "Team" column, sorts by "Points" descending, reorders columns, formats indices, adds team name links, and returns the final ra... | def combined_table():
# Merge total_points_df with leaderboard_df on 'Team' column
merged_df = total_cumulative_points().merge(total_win_loss_points(), on="Team")
# Merge trades_df2 with the above merged dataframe on 'Team' column
merged_df = merged_df.merge(total_trades(), on="Team")
merged_df = m... |
def get_atm_option_ids():
eth_price = get_eth_price()
call_options = requests.get(f'{BASE_URL}/v2/products?contract_types=call_options&states=live&page_size=10000').json()['result']
put_options = requests.get(f'{BASE_URL}/v2/products?contract_types=put_options&states=live&page_size=10000').json()['result']
... | The main task of the code is to execute a trading strategy involving selling at-the-money (ATM) call and put options with predefined stop-loss levels. It retrieves ATM option IDs, fetches bid/ask prices, calculates stop-loss thresholds, and places sell orders with bracket orders to manage risk. The strategy aims to pro... | def execute_strategy():
atm_call_id, atm_put_id = get_atm_option_ids()
# Fetch best bid and ask for ATM call and put
call_bid, call_ask = get_best_bid_ask(atm_call_id)
put_bid, put_ask = get_best_bid_ask(atm_put_id)
# Calculate stop loss prices
call_stop_loss = call_bid * STOP_LOSS_FACTOR
... |
def add_constant(self,X):
X0 = np.ones((X.shape[0],1))
return np.concatenate((X0, np.array(X)),axis=1)
def fit(self,theta,x,y):
opt = fmin_tnc(func=self.cost_function,x0 = theta,fprime=self.gradient,args=(x,y.flatten()))
return opt[0]
def predict(self,params,x):
theta = params[:,... | This code implements logistic regression for binary classification. It standardizes target variables to 0/1, adds intercept terms to features, initializes parameters, trains the model using fit(), and predicts class probabilities and labels for both training and test sets using a threshold of 0.5. | def logistic_regression(self):
# Y has only two classes
ths = 0.5
# Y
if self.Y_train.unique().min() != 0:
self.Y_train = self.Y_train - self.Y_train.unique().min()
if self.Y_test.unique().min() != 0:
self.Y_test = self.Y_test - self.Y_test.unique().min() ... |
def linear_regression(self):
# add constant
self.X_tr = self.add_constant(self.X_train)
self.X_tst = self.add_constant(self.X_test)
# estimate coefficients
self.beta = self.get_coefficient(self.X_tr,self.Y_train)
# predict Y
self.Y_tr_hat = np.dot... | This code initializes a data processing and modeling class by loading train/test datasets from user inputs, splitting features/target variables, and executing selected regression or classification models (e.g., linear regression, LDA, QDA, logistic regression) based on user choices. It dynamically handles data formatti... | def __init__(self):
# load data
file_name1 = input("Enter the name of train data file\n: ")
file_name2 = input("Enter the name of test data file\n: ")
sep = " " if int(input("Select the data coding format(1 = 'a b c', 2 = 'a, b, c')\n: ")) ==1 else ","
header = None if input("Doe... |
def init_params(options, Wemb_value=None):
"""
Global (not NN) parameter. For the embeding and the classifier.
"""
rng = numpy.random.RandomState(7896)
params = OrderedDict()
# embeddings of tokens in sentences
if Wemb_value is None:
params['Wemb'] = (numpy.asarray(rng.uniform(
... | The code trains a neural network with LSTM layers and adversarial components for sequence-based tasks. It initializes model parameters, loads data, and builds a Theano-based model. Training involves gradient updates using a specified optimizer (e.g., momentum), early stopping based on validation performance, and advers... | def train_nn(
# Hyper-Parameters
dim_token = 100, # word embeding dimension
lstm_layer_0_n = 50,
lstm_layer_1_n = 50,
ydim0 = 5,
ydim1 = 6,
#win_size = 3,
#n_cueTypes = 4,
n_vocb_words = 31848, # Vocabulary size
#n_locDiffs = 111, # Location difference size
... |
def Merge(VCG,L,R, counter):
U,D,F,G, H = {},{},{},{},{}
for i in L.union(R):
Distance1 = longest_path(VCG,S,i)
Distance2 = longest_path(VCG,i,T)
if Distance1 == float('-inf') or Distance2 == float('-inf'):
continue
U[i] = Distance1
D[i] = Distance2
maxVal... | The code processes a graph (VCG) by merging zones (StartingZones/EndingZones) and iteratively removing nodes based on a maximal set. It updates zones, cleans the graph, and organizes remaining nodes into a display structure, prioritizing nodes with empty connections. The function returns a dictionary mapping node indic... | def NetMerge(VCG,MaximalSet,StartingZones, EndingZones, counter, endTracer):
L = set()
for i in range(0,len(MaximalSet)):
Zi = set(EndingZones[i])
if(i+1 == len(MaximalSet)):
Zi1 = StartingZones[i]
else:
Zi1 = set(StartingZones[i+1])
L = L.union(Zi)
... |
def remove_subsets(d):
keys_to_remove = set()
unique_lists = set()
for k1, v1 in d.items():
sorted_v1 = tuple(sorted(v1))
if sorted_v1 in unique_lists:
keys_to_remove.add(k1)
continue
unique_lists.add(sorted_v1)
for k2, v2 in d.items():
i... | The code processes terminal inputs of a channel to generate a network graph (VCG), identifies maximal sets of connected components, constructs a source-sink graph, and merges nets to produce an output visualized via arrays. It removes subsets to find maximal column spans, connects sources/sinks, and applies NetMerge fo... | def main():
# Define the inputs for terminals of the channel
TOP = [0,1,4,5,1,6,7,0,4,9,10,10]
BOT = [2,3,5,3,5,2,6,8,9,8,7,9]
global S,T
global counter
global Tracks
global Hs
global endTracer
Tracks = []
# We create a hashset to store values
Hs = set()
for i in TOP:
... |
def sample_map_space(self):
#Return an [x,y] coordinate to drive the robot towards
probGoal = np.random.rand()
if probGoal < 0.05:
randX = self.goal_point[0][0] + 3*self.stopping_dist*np.random.rand()
randY = self.goal_point[1][0] + 3*self.stopping_dist*np.random.rand()... | This function implements Rapidly-exploring Random Tree (RRT) path planning. It iteratively samples map space, finds the closest tree node, simulates trajectories towards sampled points, checks for collisions and duplicates, and adds valid nodes to the tree. The process continues until the goal is reached within a stopp... | def rrt_planning(self):
#This function performs RRT on the given map and robot
#You do not need to demonstrate this function to the TAs, but it is left in for you to check your work
i = 0
while True: #Most likely need more iterations than this to complete the map!
... |
def sample_map_space(self):
#Return an [x,y] coordinate to drive the robot towards
probGoal = np.random.rand()
if probGoal < 0.05:
randX = self.goal_point[0][0] + 3*self.stopping_dist*np.random.rand()
randY = self.goal_point[1][0] + 3*self.stopping_dist*np.random.rand()... | This function implements the RRT* algorithm to find a collision-free path from the start to the goal in a map. It iteratively samples points, connects them to the nearest tree node, checks for collisions, and adds valid nodes to the tree. It then rewires nearby nodes to optimize path costs, ensuring the tree converges ... | def rrt_star_planning(self):
#This function performs RRT* for the given map and robot
while True: #Most likely need more iterations than this to complete the map!
#Sample map space
point = self.sample_map_space()
#Get the closest point
closest_nod... |
def compute_logs(x, M, theta, just_bs=False):
log_bs = np.array([log_b_m_x(m, x, theta) for m in range(M)])
if just_bs:
return log_bs
log_ps = np.array(log_p_m_x(log_bs, theta))
return log_bs, log_ps
def logLik(log_Bs, myTheta):
""" Return the log likelihood of 'X' using model 'myTheta' and ... | The code trains a probabilistic model (e.g., Gaussian Mixture Model) for a speaker using the Expectation-Maximization (EM) algorithm. It initializes parameters (weights, means, covariances) and iteratively updates them to maximize the log-likelihood of the input data `X`. The process continues for up to `maxIter` itera... | def train(speaker, X, M=8, epsilon=0.0, maxIter=20):
""" Train a model for the given speaker. Returns the theta (omega, mu, sigma)"""
myTheta = theta(speaker, M, X.shape[1])
# set omega
omega = np.exp(np.random.rand(M, 1))
myTheta.reset_omega(omega / omega.sum())
# set mu
myTheta.reset_mu(X[... |
def conv_layer(x, filters, kernel_size, stride, scope, padding='valid'):
with tf.name_scope(scope):
x = tf.layers.conv2d(x, filters, kernel_size, stride,
use_bias=False, padding=padding, name=scope,
kernel_initializer=layers.xavier_initializer(uniform=True),
kernel_regularizer=layers.l2_r... | This code constructs a DenseNet model by stacking dense blocks with transition layers to compress features, followed by batch normalization, ReLU, global average pooling, and a fully connected layer for classification. | def build_model(self, x):
x = conv_layer(x, self.filters, 3, 1, padding='same', scope='initial_conv')
#x = batch_norm(x, training=self.training, scope='initial_bn')
#x = tf.nn.relu(x, name='initial_relu')
#x = layers.max_pool2d(x, 2, 2, scope='initial_maxpool')
# compresion the feature
compress... |
def _read_machines_config(self) -> dict:
"""Read YAML machine config file.
:return Dictionary with machines' details or None if details
could not be retrieved.
"""
# Python representation of the YAML machine config file
machines = None
try:
w... | The code processes a command by filtering applicable machines from a YAML-configured list, applying include/exclude parameters, and executing the action. It reads BMC details from a config file, validates input (e.g., glob patterns for unsupported commands), identifies matching machines, and runs the command on them, r... | def run(self, command: Command, machines, include, exclude):
"""Build a list of applicable machines and execute an action upon them.
:return: CLI_OK if successful, CLI_ERROR on error.
"""
self.logger.debug(
"Running command {} with parameters: "
"machines={}, inc... |
def read_english_docs(title, text, tokens):
rows = []
# reading csv file
with open(english_data_path, encoding="utf8") as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)
# extracting each data row one by one
for row in csvreader:
rows.appe... | The main task of the code is to process documents in a specified language (English or Persian) by reading text data, removing stop words, and extracting frequent terms. It returns dictionaries mapping document titles to their content, along with frequency data for analysis. | def get_documents_data(language):
text_dic = {}
title_dic = {}
all_tokens = []
if language == "en":
title_dic, text_dic, all_tokens = read_english_docs(title_dic, text_dic, all_tokens)
else:
title_dic, text_dic, all_tokens = read_persian_docs(title_dic, text_dic, all_tokens)
ti... |
def create_indexes(dic, language):
title_dic, text_dic = dic[0], dic[1]
# positional index
index = {}
for docID in range(1, len(title_dic)+1):
# text index :
for position in range(0, len(text_dic[docID])):
token = text_dic[docID][position]
if token in index:
... | The main task of the code is to create and interact with a document index for text processing and retrieval. It allows users to preprocess input text, analyze token frequencies, retrieve posting lists, explore word positions, handle bigrams, and dynamically add/delete documents in English or Persian. The system provide... | def main():
print("Hi!\nCreating index of documents ...")
create_indexes(get_documents_data('en'), 'en')
# create_indexes(get_documents_data('fa'),'fa')
while 1:
order = input(
"What do you want to see?\n1)Your input tokens after preprocess\n"
"2)See the 15 most frequent... |
def _update(self, prior_mean: torch.Tensor, prior_cov: Iterable[torch.Tensor],
obs_mean: torch.Tensor, obs_var: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]:
"""Performs update step
:param prior_mean: current prior state mean
:param prior_cov: current prior state cova... | This code performs Bayesian inference by updating the prior state estimate (mean and covariance) with observations, using either standard or masked updates depending on data validity. It then predicts the next prior state from the updated posterior, returning posterior estimates and predicted next priors. | def forward(self, prior_mean: torch.Tensor, prior_cov: Iterable[torch.Tensor],
obs: torch.Tensor, obs_var: torch.Tensor, obs_valid: torch.Tensor = None) -> \
Tuple[torch.Tensor, Iterable[torch.Tensor], torch.Tensor, Iterable[torch.Tensor]]:
if self.c.never_invalid:
post_... |
def decrypt(self, message, key):
alphabet = ['x', '$', 'W', 't', 'D', '|', 'd', " ", 'E', 'N', '`', 'n', 'X', 'h', 'V', 'A',
'Y', '5', 'a', '¦', '2', 'J', 'C', 'b', 'k', 'H', 'I', 'c', 'f', 'K', '1', '9', 'u', ':', '3',
'#', '%', 'P', 'i', '^', '4', 'O', '(', '[', 'R', '+', 'T', 'o', ... | The main task of the code is to continuously receive and process incoming messages from a socket connection. It decrypts the data, checks for a specific server command prefix, and either inserts the message or executes server commands accordingly. The loop terminates when disconnected, closes the socket, and logs a dis... | def get_messages(self):
while True:
if self.disconnected:
break
data = s.recv(self.data_buff)
if not data:
break
decoded = data.decode("utf-8")
decoded = self.decrypt(decoded, self.encryption_key)
try:
... |
def pay_for_service(hero, cost):
hero.gold = round(hero.gold - cost, 3)
def _cheap_room(hero):
_sleep(hero=hero, room_level='low')
if _event(hero=hero, luck_modifier=CHEAP_ROOM_LUCK_MODIFIER,
rob_percentage=CHEAP_ROOM_ROB_PERCENTAGE):
print("\nHeck! I not only did sleep on a hard bed, ... | The function allows a hero to rent rooms (cheap, well-maintained, luxury) by deducting corresponding gold costs. It displays hero stats, checks gold sufficiency, processes payments, and invokes room-specific functions. If gold is insufficient, it alerts the hero. Choosing "Back" exits the menu. If the hero has no gold,... | def _rent_room(hero):
cheap_room_cost = 5
well_maintained_room_cost = 12
luxury_room_cost = 30
if hero.gold > 0:
while True:
print('\nYour health: {0}/{1}\nYour energy: {2}/{3}\nYou have {4} gold\n'.format(
hero.health, hero.max_health,
hero.energy, h... |
def train_models(data):
transmat = {3:transmat_3(), 4:transmat_4(), 5:transmat_5(), 6:transmat_6()}
models = { n:build_model(data, n, transmat = transmat.get(n, 1.0)) for n in range(2,7) }
predicted = { n:models[n].predict(data) for n in range(2,7)}
return models, predicted
def check_model(self):
... | The code trains models on reshaped data, creates a binary classification column based on eigenvalues, adds HMM features (2-6) using predicted values, extracts and postprocesses HMM3 data, then stores the result as a new HMM5_2 column in a pandas DataFrame. | def analyze(self):
self.model, self.predicted = train_models(self.data.reshape(-1,1))
self.check_model()
indexes = self.mask[self.mask].index
conditions, choices = [(self.loc_eig.E1 >= 0), (self.loc_eig.E1 < 0)], [1,0]
self.loc_eig['binary'] = np.select(conditions, choices, def... |
def build_url(self, query):
pass
def get_JSON_response(url="", cache_days=7.0, folder=False, headers=False):
"""
get JSON response for *url, makes use of file cache.
"""
now = time.time()
hashed_url = hashlib.md5(url.encode("utf-8")).hexdigest()
cache_path = xbmcvfs.translatePath(os.path... | The code fetches data from an API by constructing a URL with the provided search string, retrieves JSON response data, and processes it for further use. | def fetch_data(self, search_str):
url = self.build_url(quote_plus(search_str))
result = get_JSON_response(url=self.BASE_URL.format(endpoint=url), headers=self.HEADERS, folder=self.FOLDER)
return self.process_result(result) |
def parseJson(filename):
# Try to load the json file
try:
with open(filename) as f:
jsonData = json.load(f)
except:
sys.stderr.write("Unable to open file '%s'" % filename)
return
# The json file contains game_states, player_input, messages, and ui_events
gameSta... | The code identifies the clip with the highest action-per-minute (APM) from a game's JSON data by generating candidate clips, filtering those within a trust region, counting actions, and returning the clip with the most actions along with its start/end times and the clipped JSON data. | def generate_clips(file: str):
"""
:param file: the name of json file
:return result: a clip with the most APM, the form is (file_name, (clip_start, clip_end))
game_data['frames'] has 33 attributes:
0 tick
1 time
2 scores
fortress attributes:
3 x
4 y
5 angle
6 al... |
def draw_border(screen):
# Top Bar
screen.move(1, 0)
screen.draw(79, 0, char='-')
# Left Bar
screen.move(0, 1)
screen.draw(0, 24, char='|')
# Bottom Bar
screen.move(1, 23)
screen.draw(79, 23, char='-')
# Right Bar
screen.move(79, 1)... | The main task of the code is to draw a screen with a border, display static elements once, and continuously update dynamic elements in a loop. It waits for a quit command (Q/q) and refreshes the screen at a specified rate, updating only the dynamic data while maintaining the static layout. | def draw_screen(self, screen):
# draw the border
self.draw_border(screen=screen)
# print layout once
for data in self.get_static_screen_data():
screen.print_at(data[0], data[1], data[2])
while True:
# update only the values
for data in self.get... |
def parse_to_html(text):
# Add leading and trailing paragraph tags
text = "<p>" + text + "</p>"
# Use \n for newline on all systems
text = re.sub(r"(\r\n|\n|\r)", r"\n", text)
# Only allow two newlines in a row
text = re.sub(r"\n\n+", r"\n\n", text)
# Double newline -> paragraph
text = text.replace("\n\n", "</p... | This code handles form data submission to update a record, including timezone conversion, input validation, password verification, image processing, and database insertion. It checks for duplicate titles, validates image formats, processes images with PIL, and securely inserts data into MySQL after authentication. | def update():
# Get date in correct timezone
la = pytz.timezone('America/Los_Angeles')
belfast = pytz.timezone('Europe/Belfast')
now = datetime.now(la)
local = now.astimezone(belfast)
date = local.strftime('%Y-%m-%d %H:%M:%S')
# Type
type_value = request.forms.get("type")
type = types[int(type_value)]
# Ot... |
def load_nilmtk_data( DATASET_PATHS,
NILMTK_EXPORT_PATH,
EVALUATION_DATA_PATH,
SAMPLE_PERIOD,
WINDOWS,
TARGET_APPLIANCE,
APPLIANCE_ALIASES ):
NILMTK_EXPORT_FILENAME = os.path.join(
... | The function loads or generates activity data for a target appliance by either retrieving cached data from a pickle file or processing datasets using nilmtk tools. It constructs filenames based on parameters like appliance name and sample period, checks for existing data, and if absent, processes datasets to create a R... | def load_activity_data( ACTIVITY_DATA_PATH,
TARGET_APPLIANCE,
APPLIANCE_ALIASES,
SAMPLE_PERIOD,
WINDOWS,
DATASET_PATHS,
ON_POWER_THRESHOLD,
MIN_ON_DURAT... |
def get_ns(pos):
num_list=[]
if get_coordinates(pos)[0]==get_coordinates(pos+1)[0]:
num_list.append([pos+1,'e',get_md(pos+1)])
if get_coordinates(pos)[0]==get_coordinates(pos-1)[0]:
num_list.append([pos-1,'w',get_md(pos-1)])
if pos+dim<total:
num_list.append([pos+dim,'s',get_md(... | This code implements a flood fill algorithm using a queue to explore nodes, updating their minimum Manhattan distance (MD) by checking available neighbors not blocked by walls. It processes each node, filters unvisited neighbors, and propagates updated MD values to adjacent nodes if a shorter path is found, effectively... | def flood_fill(current):
q=[]
q.append(current)
while len(q)!=0 :
front=q.pop(0)
ns = get_ns(front)
available_ns=[]
for num in ns:
if num[0] not in discovered_walls[front]:
available_ns.append(num)
min_md_data = get_min_md(available... |
def generate_random_group_id(length=24):
characters = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+'
random_string = ''.join(random.choice(characters) for _ in range(length - 3))
return "0" + random_string + "=="
def add_groups(root,group_name,group_id,target_uri,target_uri_id,link):
... | The main task of the code is to update an XML file by generating hierarchical group elements and zone data based on CSV input. It maps CSV entries to unique URIs and group IDs, adds nested group relationships via `<hasChild>/<ref>` elements, and creates zones with address ranges linked to departments. The updated XML s... | def xml_update_with_Groups_Zones(csv_file_path, xml_file_path):
# Parse the XML file
tree = ET.parse(xml_file_path)
root = tree.getroot()
# Read the CSV file into a DataFrame
with open(csv_file_path, mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
# Defining dictionar... |
def default_lighting(options):
light_data = bpy.data.lights.new(name="KeyLight", type='AREA')
light_data.energy = 300
light_data.shape = 'SQUARE'
light_data.size = 5
light_data.color = (1, 1, 1)
light = bpy.data.objects.new(name="KeyLight", object_data=light_data)
bpy.context.collection.obje... | The code defines a function `setup_lighting` that configures lighting settings based on the `lighting_style` attribute in the provided `options` object. It uses conditional checks to call specific lighting functions: `default_lighting`, `bright_lighting`, or `hard_lighting`, depending on the style. The primary task is ... | def setup_lighting(options):
if options.lighting_style == LightingStyle.DEFAULT:
default_lighting(options)
if options.lighting_style == LightingStyle.BRIGHT:
bright_lighting(options)
elif options.lighting_style == LightingStyle.HARD:
hard_lighting(options) |
def fitnessFunction(chromosome):
score = 0
for i in range(1, num_cities):
currentCity = chromosome[i-1]
nextCity = chromosome[i]
score += dist_matrix[currentCity][nextCity]
score += dist_matrix[chromosome[0]][chromosome[-1]]
return score
def initialize(num_cities):
population... | The main task of the code is to perform a genetic algorithm to solve a Traveling Salesman Problem (TSP) by evolving a population of routes over multiple generations within a 59-second time limit. It iteratively improves the best tour's length using the geneticAlgorithm function, updating the optimal solution whenever a... | def generationCycle():
tour = [x for x in range(num_cities)]
tour_length = fitnessFunction(tour)
generationCycle = 0
population = initialize(num_cities)
while time.time() - start_time < 59:
generationCycle += 1
route, score = geneticAlgorithm(generationCycle, population)
if s... |
def fitnessFunction(route):
score = 0
for i in range(1, num_cities):
currentCity = route[i-1]
nextCity = route[i]
score += dist_matrix[currentCity][nextCity]
score += dist_matrix[route[0]][route[-1]]
return score
def initialize(number_of_ants):
list_of_cities = [0 for x in ra... | The main task of the code is to solve the Traveling Salesman Problem (TSP) using Ant Colony Optimization (ACO). It initializes pheromone trails, iteratively updates ant paths, and applies pheromone deposition/decay to find the shortest route. The algorithm balances exploration and exploitation, adjusting routes based o... | def main():
max_iter = 0
best_score = 0
best_route = []
tour = [x for x in range(num_cities)]
tour_length = fitnessFunction(tour)
ant_city_list, unvisited_cities = initialize(number_of_ants)
pheromone_matrix = initial_pheromone_matrix()
heuristic_desirability_matrix = heuristicDesirabili... |
def completion_tasks(data, completion_value, today=None, most_recent=False):
df = data
if today:
df = df[(df.Date <= today)]
df = df.sort_values(by=["Date"]).groupby(["Task"]).tail(1)
if completion_value is None:
df = df[df.Done.isnull()]
else:
df = df[(df.Done == completion_... | The main task of the code is to generate a report of completed tasks by updating the input DataFrame to mark tasks as "DONE", then producing a summary grouped by "Task" with specific formatting (excluding dates/keys, sorting by "Order" ascending), and returning the processed report. | def report_closed_tasks(df):
global _now
df = completion_tasks(df, "DONE", today=_now)
ret = report1(df, groupby="Task", display_date=False, display_key=False, last_only="Task", sortby="Order",
ascending=True)
report_span()
return ret |
def expand(peptides):
result = []
aa_masses = list(AMINO_ACIDS_MASS.values())
for p in peptides:
for m in aa_masses:
result.append(p + [m])
return result
def score_func(peptide, spectrum):
peptide_spectrum = cyclospectrum_mass_peptide(peptide)
result = 0
mass_set = set(pe... | This code identifies the highest-scoring cyclic peptide from a given spectrum using a leaderboard approach. It expands possible peptide sequences, filters those matching the spectrum's mass, trims the leaderboard to keep top N candidates, and updates the leader peptide when a higher-scoring match is found. | def leaderboard_cylopeptide_sequencing(N, spectrum):
leader_board = [[]]
leader_peptide = []
while len(leader_board) > 0:
leader_board = expand(leader_board)
for peptide in leader_board:
if sum(peptide) == spectrum[-1]:
if score_func(peptide, spectrum) > score_fu... |
def parseNotes(self) -> None:
self.notes = []
self.pitches = []
self.instruments: list[Instrument] = []
self.endTick = None
self.condenseTracks = len(self.ps.instruments) > len(Instruments)
# walk through the midi instrument tracks
for rawInstru in self.ps.instru... | This code initializes a MIDI file processor using FluidSynth to convert MIDI data into audio. It loads a soundfont, parses MIDI notes, sets parameters like transpose and sample rate, and prepares to render the audio output to a temporary WAV file. The main tasks include MIDI file parsing, soundfont loading, note initia... | def __init__(self, midiFile: str, soundfont: str, sampleRate: int = 44100, transpose: int = 0, tmpSound: str = "tmp.wav") -> None:
self.ps = mid_parser.MidiFile(midiFile)
self.fl = fluidsynth.Synth()
self.volume = 1
self.sound = []
self.tickTimeMap = self.ps.get_tick_to_time_map... |
def store_basic_information(
self,
dataframe,
column_data_types,
keys,
labels,
features_categorical_classes_2_drop,
):
self.data.df = dataframe.copy(deep=True)
self.data.keys = keys
(
self.data.features,
self.data.featu... | This code initializes an object by storing input data, preprocessing categorical features, and encoding labels for machine learning tasks, using provided data types and configuration parameters. | def __init__(
self,
dataframe,
column_data_types,
keys,
labels,
features_categorical_classes_2_drop=[],
):
self.data = CDML_Object()
self.store_basic_information(
dataframe,
column_data_types,
keys,
labe... |
def paintEdge(self, startLabel, endLabel, color='r'):
p1 = self.nodeLoc(startLabel)
p2 = self.nodeLoc(endLabel)
plt.plot([p1[0], p2[0]], [p1[1], p2[1]], color=color, linewidth=1)
def paintNode(self,nodeLabel,color='r',weight='normal', size='medium'):
p1=self.nodeLoc(nodeLabel)
if... | The code's main task is to visualize graph traversal by clearing previous highlights (edges/nodes) and marking the current explored node and its path in red. It unmarks prior selections, paints the new node and path, then updates the graph display. This supports step-by-step graph exploration visualization. | def exploreNode(self,nodeLabel,nodePath):
# First clean up. Unmark highlights nodes/edges from last step
for edge in self.markedEdges: # first unmark any edges painted in last steps
self.paintEdge(edge[0],edge[1],color='k')
if self.markedNodes: # if there was a previous node explo... |
def create_parking_slots(self, max_capacity):
"""
This method takes in the max capacity of the parking lot and returns a min heap for all available parking lots.
:param max_capacity:int It denotes the maximum capacity of the parking lot.
:return: status:boolean It returns True if a min h... | This method parses and executes parking lot commands (e.g., creating slots, parking/leaving vehicles, querying slot/registration numbers) based on input queries. It validates commands, processes arguments, invokes corresponding operations, handles errors, and outputs results to console or file depending on mode. | def parse_commands(self, query):
"""
This method takes query as input and executes the query on the predefined set of commands and matching methods
to be executed, and prints the output to the console or writes it to a output file based on the mode selected.
Predefined Commands :
... |
def ones_places(x):
# list for ones, hundreds and thousands places
ones_place = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
return ones_place[int(x)]
def tens_places(x):
# list for tens places
tens_place = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', '... | The code converts integers to their word equivalents, handling numbers up to four digits. It uses helper functions for ones, tens, and hundreds places. For four-digit numbers, it processes thousands by checking trailing zeros and combining with the appropriate helper functions. Numbers with more than four digits return... | def num2words(x):
# converting int to string because will be executed on the basis of strings
x = str(x)
# condition check if length of numbers > 4
if len(x) > 4:
return 'numbers greater than 4 digits are not supported'
elif len(x) == 1:
# function invocation
ones_places(x)... |
def data_augment(self, img, mask_GT, GT):
# https://github.com/mdbloice/Augmentor
images = [[img, GT, mask_GT]]
p = Augmentor.DataPipeline(images)
p.flip_random(1)
if self.subject_word=="SRD":
width=random.randint(256,480) # SRD
elif self.subject_word=="ISTD"... | The main task of the code is to load and preprocess images, masks, and ground truth data for a machine learning model. It reads input images, applies data augmentation or resizing if needed, converts color spaces from BGR to RGB, and transforms the data into tensors for model input. | def load_item(self, index):
size_h = self.input_size_h
size_w = self.input_size_w
# load image
img = cv2.imread(self.data[index], -1)
mask_GT = cv2.imread(self.mask[index], -1)
GT = cv2.imread(self.GT[index], -1)
# augment data
if self.augment:
... |
def get_encoder(encoder_param, norm):
encoder = []
index = 0
for param in encoder_param:
if index == 0:
encoder.append(conv2d_layer(param[0], param[1], kernel_size=param[2], stride=param[3], padding=param[4], dilation=1, norm=norm,
activation_fn="R... | This function constructs an encoder-decoder neural network architecture with customizable parameters. It creates an encoder with convolutional layers, a middle block containing ResNet-style residual blocks, and a decoder with upsampling layers. The model uses batch normalization by default and includes a sigmoid activa... | def get_encoder_decoder(in_channels, ResnetBlockNum, Sigmoid=True, norm="batch"):
encoder_param = [
[in_channels, 64, 7, 1, 3],
[64, 128, 4, 2, 1],
[128, 256, 4, 2, 1]]
encoder = nn.Sequential(
*get_encoder(encoder_param, norm))
middle_param = [ResnetBlockNum, 256]
middle... |
def get_news_count_for_gap(row, all_news_sentiment: DataFrame) -> int:
return len(get_news_for_gap(row, all_news_sentiment))
def get_news_sentiment_for_gap(row, all_news_sentiment: DataFrame) -> float:
news = get_news_for_gap(row, all_news_sentiment)
if news.empty:
return 0
scores = news['headl... | The code processes chart data by extracting symbol, timestamp, and bar information from image files, merges it with news sentiment data, calculates news-related metrics for each chart, groups data by symbol, inserts close prices for specified bars, and saves charts with integrated price and news insights. | def create_chart_nth_price_with_news_db(bars_repo: BarsRepo, news_repo: NewsRepo, n_for_prices: List[int]):
file_paths = pd.Series(list(image_dir.glob(r'**/*.png')), name='filepath').astype(str)
symbols = pd.Series(file_paths.apply(lambda x: os.path.split(os.path.split(x)[0])[1]), name='symbol')
timestamps... |
def _init_solver(self):
for idx in range(len(self.buyers)):
self.buyers[idx].reset()
self.levels = [set() for _ in range(self.bound + 1)]
for buyer in self.buyers:
self.levels[0].add(buyer.id)
self.assignment = [defaultdict(lambda: 0) for _ in self.buyers]
def _... | The main task of the code is to allocate resources to items based on buyer demands and constraints, using a stepwise process to reach an optimal solution. It adjusts allocation fractions, ensures buyers meet spending thresholds, and computes an objective value to evaluate the result. | def solve(self, eta):
self.eta = ROUND(eta)
self._init_solver()
for item in self.items:
if item.prediction is None:
self._allocate_equally(item, self.eta)
else:
amount = self._needed_amount_to_reach_limit(item.interested_buyers)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.