dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def initUI(self):
########################################
# Create Widgets
########################################
self.loadPushButton = qtw.QPushButton(
"Load Image",
self,
objectName = "loadPushButton",
shortcut=qtg.QKeySequence("Ctrl+f")
)
self.sigmaSpinBox = qtw.QD... | The code defines a Qt MainWindow constructor for a lesion augmentation image viewer. It initializes GUI elements, VTK pipeline components for image processing (Gaussian smoothing, thresholding, contouring), and sets up parameters like brightness, window level, and zoom. The class loads input medical images, applies fil... | def __init__(self,
input_file,
gaussian,
radius,
thresh,
zoom,
zSlice,
brightness,
window_size,
colorWindow,
colorLevel,
*args, **kwargs):
"""MainWindo... |
def get_daft_listings(property_type, offset):
daft = Daft()
daft.set_county('Dublin')
daft.set_listing_type(property_type)
daft.set_min_price(200)
daft.set_offset(offset)
return daft.search()
def validate_listings(listings, property_information, property_type):
for listing in listings:
... | The code fetches property listings from Daft, validates them, and aggregates data across pages until no more listings are found. It removes duplicates and writes the final dataset to a file, organized by property type. The loop increments the offset by 10 per iteration to paginate through results. | def get_property_information(property_type):
property_information = []
pages = True
offset = 0
while pages:
listings = get_daft_listings(property_type, offset)
if not listings:
pages = False
property_information = validate_listings(listings, property_information, pro... |
def load_frames(finger_name, crop):
files = os.listdir('images/'+finger_name)
frames = []
for f in files:
img = cv2.imread('images/'+finger_name+'/'+f)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# convert to grayscale
img = crop_image(img, crop)
frames.append(img)
names ... | The main task of the code is to process and analyze finger motion data by loading frames, applying thresholding and blob-based masking, visualizing results through image display and saving, and detecting blobs with a keypoint detector. It demonstrates image processing pipelines for motion analysis, including thresholdi... | def main():
finger_name = 'Index'
t1_frames, names = load_frames(finger_name, crops[finger_name])
print(t1_frames.shape)
# Testing the thresholding
t2_frames_thresh = apply_thresholding(t1_frames, thresh_params[finger_name])
# Testing the masking with blobs
t3_frames = mask_wi... |
def open_X(X, M, F, G, CT):
"""
function to unpack the variable vector X into the 6 vectors
TH, TWH, TWC, T_air, PH, PC
"""
T_PF_in = F.T_PF_in
T_air_in = F.T_air_in
n_cells = G.n_cells
n_rows = G.n_rows
n_CPR = G.n_CPR
n_CP = G.n_CP
n_passes = G.n_passes
P_PF_in = F.P_P... | The code computes energy balance errors for each cell in a heat exchanger model by solving fluid dynamics (pressure drop, flow rates), heat transfer (convective, conductive, and wall conduction), and boundary condition equations. It calculates temperature and pressure distributions, heat flux terms (q1–q9), and compare... | def equations(X, G, F, M, I, flag, CT):
"""Equations to solve energy balance for each cell in the model, and return
the energy balance error"""
# Initialise error vector
if M.cooler_type == 1:
error = np.zeros((4 * G.n_cells) + G.n_rows + 1 + CT.solver_type)
else:
error = np.zeros((... |
def get_X0_iter(G, F, M, I, CT):
# Function to get initial values for iterative solver
if M.cooler_type == 1:
X0 = np.zeros((4 * G.n_cells) + (G.n_rows) + 1 + CT.solver_type)
mdot_init = CT.mdot_PF_total / ((CT.A_fr / CT.dA_HX))
else:
X0 = np.zeros((4 * G.n_cells) + (G.n_rows))
... | The code solves a heat exchanger (HX) system by numerically solving a set of nonlinear equations to determine fluid temperatures, pressures, mass flows, and energy balances. It initializes model geometry, fluid properties, and iteratively computes thermal performance metrics using Newton-Krylov optimization. The soluti... | def solve(hx_inputs, mod=None, X0=None, fig_switch=0, verbosity=0):
M = Model()
F = Fluid()
G = Geometry()
CT = CT_Geometry()
hx_inputs(G, F, M, CT)
if (
mod
): # A function that operates on input classes - for iterative optimisation only
# TODO: Can I find a more elegant ... |
def read_file(filename):
lines = []
with open(filename, 'r') as file:
line = file.readline()
l = line.split()
for i in range(0, len(l)):
l[i] = float(l[i])
lines.append(l)
while line:
line = file.readline()
if line:
l =... | The code processes data from a file by reading, separating features (x) and labels (y), augmenting x with a bias term (x0_value), and scaling down each feature array by a factor of n. It then iterates the Perceptron Learning Algorithm (PLA) 1000 times on the modified data, collecting the number of iterations (a) and we... | def combined(path, x0_value, n):
l = []
w0 = []
lines = read_file(path)
y, x = seperate_x_and_y(lines)
x = add_x(x, x0_value)
for array in x:
scale_down(array, n)
for _ in range(1000):
a, b = pla(x, y)
l.append(a)
w0.append(b)
return median(l), median(w0) |
def print_menu(menu_options):
for key in menu_options.keys():
print(key, '...', menu_options[key])
def login(cnx):
# Get username and password
username = input("Enter Username: ")
password = input("Enter Password: ")
# Check that the inputted account is in the database and is correct
cur... | The function `loginRegister` provides a menu-driven interface for user login, registration, or exit. It loops until the user selects "Exit," handling invalid inputs and invoking `login(cnx)` or `register(cnx)` based on the choice. | def loginRegister(cnx):
menu_options = {
1: "Login",
2: "Register",
3: "Exit"
}
while (True):
print("Login Menu:")
print_menu(menu_options)
menu_selection = ''
try:
menu_selection = int(input('Menu Selection: '))
except:
... |
def get_map_file(self):
"""
Try to get a user inputted path to map_file or use the default.
:return:
"""
map_file = "../data/map.yaml"
prompt = f"""
Available map file:
1. {map_file}
Input number (e.g. 1) to select a file from the above liste... | This code initializes a ROS node to serve a map file for navigation. It loads the map, sets up publishers, and creates an action server to handle map-loading requests. The node checks for a provided map file or retrieves one if unspecified, then configures its status, publishers, and action server to process map-relate... | def __init__(self, map_file=None):
"""
:param map_file:
"""
self.map_pub = None
self.ok = True
self.meta_data_pub = None
self.map_file = map_file
if self.map_file is None:
self.get_map_file()
rospy.loginfo(f"Got map file '{self.map_fil... |
def check_eat_apple(self):
for apple in self.apples:
if apple.get_location() in self.snake.get_coordinates():
return True
def snake_self_collision(self):
if len(set(self.snake.get_coordinates())) < len(
self.snake.get_coordinates()):
return True
... | This function handles a single game turn for the snake by validating and applying directional input, moving the snake, managing counter logic for apple consumption, checking collisions (self, board, bomb), updating bomb status, and triggering game over conditions if collisions occur. It also processes apple eating, bom... | def single_turn(self, direction):
if self.snake.is_valid_move(direction):
self.snake.change_direction(direction)
self.snake.move_snake()
if self.snake.get_counter() > 0:
self.snake.minus_counter()
if self.check_eat_apple():
self.snake.plus_counter()
... |
def ie_preprocess(segments):
sentences = nltk.sent_tokenize(segments)
prepared_sents=[]
for sent in sentences:
prepared_sents=prepared_sents+nltk.word_tokenize(sent)
words_list=[]
for sent in prepared_sents:
words_list=words_list+nltk.word_to... | The main task of the code is to generate "Who" questions from input sentences by parsing noun phrases (NP) and verb phrases (VP) using a custom grammar. It identifies NP-VB pairs, removes the NP to form a question stem, converts the verb, and constructs "Who [verb] [question stem]?" questions, pairing them with the ide... | def QSG_1(sentence):#Questions starting with Who.
try:
segments = sentence.rstrip().rstrip(".").split(",")
tagged_segments=[ie_preprocess(segment) for segment in segments]
doc=nlp(sentence)
grammer=r'''
NP:{<DT>?<JJ.?>*(<IN|DT|CC|VBN>*<NN.?|PRP|PRP\$|POS|VBG>+)+} ... |
def ie_preprocess(segments):
sentences = nltk.sent_tokenize(segments)
prepared_sents=[]
for sent in sentences:
prepared_sents=prepared_sents+nltk.word_tokenize(sent)
words_list=[]
for sent in prepared_sents:
words_list=words_list+nltk.word_to... | The code generates question-answer pairs for sentences containing personal pronouns by parsing noun phrases (NP) and verb phrases (VP) using custom grammar rules. It splits the input sentence into segments, identifies chunks via syntactic parsing, and constructs "Whose" questions by extracting noun phrases while omitti... | def QSG_3(sentence): #Questions for answer's with personal pronoun
try:
segments = sentence.rstrip().rstrip(".").split(",")
tagged_segments=[ie_preprocess(segment) for segment in segments]
doc=nlp(sentence)
grammer=r'''
NP:{<DT>?<JJ.?>*(<IN|DT|CC|VBN>*<NN.?|PRP|PRP... |
def get_average_data(self, feature):
data = IceExp.objects.all().aggregate(avg=Avg(feature))['avg']
data = round(data, 2)
return data
def get_min_data(self, feature):
data = IceExp.objects.all().aggregate(min=Min(feature))['min']
data = round(data, 2)
return data
def get_... | The main task of the code is to aggregate statistical data (average, min, max) for temperature, humidity, thickness, weight, and duration, and prepare chart data (pie, line, scatter plots) for visualization. It populates the context dictionary with these metrics to be used in templates for displaying analytics and grap... | def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['avg_temp'] = self.get_average_data('temp')
context['min_temp'] = self.get_min_data('temp')
context['max_temp'] = self.get_max_data('temp')
context['avg_rh'] = self.get_average_data('humid... |
def line_menu(self):
''' Context menu for lines '''
# COPY & PAST
self.menu = QtGui.QMenu(self)
self.menu.addAction("Copy", self.line_copy)
self.menu.addAction("Cut", self.line_cut)
self.menu.addAction("Delete", self.ax_delete)
self.menu.addSeparator()
... | This function handles mouse click events in a matplotlib plot. It checks if an artist is selected (via select_flag) and shows context menus for different element types (lines, arrows, text, etc.) on right-clicks. Left-clicks return 0. If no selection exists, it unselects all artists and triggers further click processin... | def on_click_select(self, event):
''' click when selected line '''
# if was pick event
if self.select_flag == 1:
self.select_flag = 0
# mooving timer
if event.button == 1:
return 0
# show menu of selec... |
def get_set_narrative_idx(self, narrative_uid:str=None):
if narrative_uid is None:
return self.get_head_narrative_idx()
uid_index = self.get_uid_index()
idx = uid_index.get(narrative_uid, len(uid_index))
uid_index[narrative_uid] = idx
with open(self.uid_index_fpath, '... | This function generates a file path for a conversation, using the provided or most recent narrative UID and conversation index. If no conversation index is given, it retrieves the latest one from the narrative tree. It then formats the path using the determined indices. | def get_conversation_fpath(self, narrative_uid:str=None, conversation_index:int=None):
# If narrative_uid is None, look in the most recent narrative
# If conversation_index is None, return the most recent conversation
narrative_idx = self.get_set_narrative_idx(narrative_uid)
if conversa... |
def get_set_narrative_idx(self, narrative_uid:str=None):
if narrative_uid is None:
return self.get_head_narrative_idx()
uid_index = self.get_uid_index()
idx = uid_index.get(narrative_uid, len(uid_index))
uid_index[narrative_uid] = idx
with open(self.uid_index_fpath, '... | This code creates a new conversation record by generating a unique index within a narrative, updating a JSON-based narrative tree structure, and initializing an empty file for the new conversation. It ensures directory creation, tracks conversation history, and maintains structured storage for narrative data. | def create_conversation_record(self, narrative_uid):
narrative_idx = self.get_set_narrative_idx(narrative_uid) # Force creation of a new directory
narrative_tree = self.get_narrative_tree()
current_conversation_list = narrative_tree.get(str(narrative_idx), [])
new_conversation_index = le... |
def resetBoard(self):
self.board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
def botTurn(self):
targetRow = random.randint(0, 2)
targetColumn = random.randint(0, 2)
for i in range(3):
if abs(sum(self.board[i])) == 2:
ta... | This code initializes and manages a game loop, handling user input, bot turns, and rendering. It runs until the game ends, processing events like mouse clicks and keyboard presses. When the game ends, it allows restarting via the 'R' key. | def start(self):
self.clock.tick(FPS)
self.gameOver = False
self.turn = 1
self.winner = 0
self.resetBoard()
while self.gameOver == False:
if self.turn == -1:
self.botTurn()
for event in pygame.event.get():
if ev... |
def get_simplified_gt(db_name, hostname, gt_file):
df = get_reportables(db_name, hostname)
print('Generating simplified data frame...')
# Remove MiSeq entries
df = df.iloc[[i for i, miseq in enumerate(df['miseq_run']) if not miseq]]
df.reset_index(drop=True, inplace=True)
# Initialize lists
... | The code combines variant calling data with ground truth data, merging samples, identifying true positives/false negatives, checking coverage via a BED file, and classifying calls. It outputs a tab-separated report with annotations on coverage, reportability, and caller performance. Key steps include merging datasets, ... | def combine(db_name, hostname, bed_file, samples_dir):
# File system
main_dir = os.path.abspath(os.path.join(sys.path[0], '..'))
output_dir = os.path.join(main_dir, 'output')
gt_file = os.path.join(
main_dir, 'data', 'ground_truth', 'ground_truth.csv'
)
# Determine whether to use cs... |
def get_comb_weights(df):
reportables = len([rep for rep in df['REPORTABLE'] if rep])
covered = len([
i for i in range(0, df.shape[0])
if df['REPORTABLE'][i] or df['COVERED'][i]
])
callers = utils.get_og_callers(df)
weights = {}
for k in range(1, len(callers) + 1):
... | The function determines the optimal cutoff for caller classification using maximum MCC from training data, computes weighted values, and assigns new caller labels to the dataframe's NAME column based on this cutoff. | def add_caller(df, training):
callers = utils.get_og_callers(df)
weights = get_comb_weights(training)
cutoffs = get_cutoffs()
vals = get_roc(training)
mccs = [
utils.get_mcc(
vals['TP'][i], vals['TN'][i], vals['FP'][i], vals['FN'][i]
) for i in range(0, le... |
def get_indiv_weights(df):
callers = utils.get_og_callers(df)
weights = {}
for caller in callers:
tp = utils.get_tp(df, caller).shape[0]
fp = utils.get_fp(df, caller).shape[0]
tn = utils.get_tn(df, caller).shape[0]
fn = utils.get_fn(df, caller).shape[0]
all_calls = tp... | The code determines the optimal threshold (cutoff) for classifying samples using the highest Matthews Correlation Coefficient (MCC) derived from training data. It calculates MCC values for each cutoff, selects the cutoff with the maximum MCC (resolving ties by choosing the last occurrence), and applies this cutoff to a... | def add_caller(df, training):
callers = utils.get_og_callers(df)
weights = get_indiv_weights(training)
cutoffs = get_cutoffs(df)
vals = get_roc(training)
# Get list of all possible Matthews Correlation Coefficients
mccs = [
utils.get_mcc(
vals['TP'][i], vals['TN']... |
def again(player1):
t=int(input())
if isspacefree(game,(t-1)):
game[t-1]=player1
print_game()
else:
again()
def checkresult(bo,p):
solution1=list(set((bo[0],bo[4],bo[8])))
solution2=list(set((bo[0],bo[3],bo[6])))
solution3=list(set((bo[1],bo[4],bo[... | The code allows two players to choose their symbols (X or O) and alternates turns, with the human player and computer taking turns to place their symbols on a grid. After each move, it checks if the current player has won, exiting the game if a win condition is met. The loop continues until a player wins, with the comp... | def begin():
print("press\n 1) player1='x' and player2='0'\n 2) player1='0' and player2='x'")
tr=int(input())
if tr==1:
player1='x'
player2='0'
else:
player1='0'
player2='x'
print("player1 =",player1+"\nplayer2 =",player2)
while True:
print("-------------... |
def checkresult(bo,p):
global c
solution1=list(set((bo[0],bo[4],bo[8])))
solution2=list(set((bo[0],bo[3],bo[6])))
solution3=list(set((bo[1],bo[4],bo[7])))
solution4=list(set((bo[3],bo[4],bo[5])))
solution5=list(set((bo[2],bo[5],bo[8])))
solution6=list(set((bo[2],bo[4],bo[6])))
solution7=... | The function `b11()` handles a player's move in a turn-based game, updates the game grid, checks for a win, disables the button after the move, and triggers the computer's turn. It increments a move counter, updates the game state, and evaluates win conditions for both players, disabling the button to prevent further a... | def b11():
global n
global c
c=c+1
n=0
a11=Button(play,text=player1,width=12,anchor=CENTER,height=3)
a11.grid(row=0, column=0 ,padx=5,pady=5)
game[0]=player1
# print(game)
if checkresult(game,player1):
dis(player1)
n=1
... |
def checkresult(bo,p):
global c
solution1=list(set((bo[0],bo[4],bo[8])))
solution2=list(set((bo[0],bo[3],bo[6])))
solution3=list(set((bo[1],bo[4],bo[7])))
solution4=list(set((bo[3],bo[4],bo[5])))
solution5=list(set((bo[2],bo[5],bo[8])))
solution6=list(set((bo[2],bo[4],bo[6])))
solution7=... | This function handles a player's move in a game by updating the game state, checking for a win, and disabling the button. It increments a counter, resets a flag, creates a button for the player's move, checks win conditions, lets the computer play if no win, and disables the button after the move. | def b12():
global c
c=c+1
global n
n=0
a12=Button(play,text=player1,width=12,anchor=CENTER,height=3)
a12.grid(row=0, column=1 ,padx=5,pady=5)
game[1]=player1
# print(game)
if checkresult(game,player1):
dis(player1)
n=1
... |
def checkresult(bo,p):
global c
solution1=list(set((bo[0],bo[4],bo[8])))
solution2=list(set((bo[0],bo[3],bo[6])))
solution3=list(set((bo[1],bo[4],bo[7])))
solution4=list(set((bo[3],bo[4],bo[5])))
solution5=list(set((bo[2],bo[5],bo[8])))
solution6=list(set((bo[2],bo[4],bo[6])))
solution7=... | This code handles a player's move in a game, updates the game state, checks for a win, and triggers the computer's response if no win occurs, disabling the button after the move. | def b13():
global c
c=c+1
global n
n=0
a13=Button(play,text=player1,width=12,anchor=CENTER,height=3)
a13.grid(row=0, column=2 ,padx=5,pady=5)
game[2]=player1
# print(game)
if checkresult(game,player1):
dis(player1)
n=1
... |
def checkresult(bo,p):
global c
solution1=list(set((bo[0],bo[4],bo[8])))
solution2=list(set((bo[0],bo[3],bo[6])))
solution3=list(set((bo[1],bo[4],bo[7])))
solution4=list(set((bo[3],bo[4],bo[5])))
solution5=list(set((bo[2],bo[5],bo[8])))
solution6=list(set((bo[2],bo[4],bo[6])))
solution7=... | This code handles a turn in a game, updating the UI with a button for player1's move, checking for a win, then letting the computer play as player2, updating the game state, and disabling the button if the game ends without a win. | def b21():
global c
c=c+1
global n
n=0
a21=Button(play,text=player1,width=12,anchor=CENTER,height=3)
a21.grid(row=1, column=0 ,padx=5,pady=5)
game[3]=player1
# print(game)
if checkresult(game,player1):
dis(player1)
n=1
... |
def checkresult(bo,p):
global c
solution1=list(set((bo[0],bo[4],bo[8])))
solution2=list(set((bo[0],bo[3],bo[6])))
solution3=list(set((bo[1],bo[4],bo[7])))
solution4=list(set((bo[3],bo[4],bo[5])))
solution5=list(set((bo[2],bo[5],bo[8])))
solution6=list(set((bo[2],bo[4],bo[6])))
solution7=... | This function handles a game turn by updating the UI with player1's move, checking for a win, then letting the computer play its move, updating the game state, and disabling the button to prevent further actions after the turn. | def b22():
global c
c=c+1
global n
n=0
a22=Button(play,text=player1,width=12,anchor=CENTER,height=3)
a22.grid(row=1, column=1 ,padx=5,pady=5)
game[4]=player1
# print(game)
if checkresult(game,player1):
dis(player1)
n=1
... |
def checkresult(bo,p):
global c
solution1=list(set((bo[0],bo[4],bo[8])))
solution2=list(set((bo[0],bo[3],bo[6])))
solution3=list(set((bo[1],bo[4],bo[7])))
solution4=list(set((bo[3],bo[4],bo[5])))
solution5=list(set((bo[2],bo[5],bo[8])))
solution6=list(set((bo[2],bo[4],bo[6])))
solution7=... | This function handles a player's move in a game, updates the game state, checks for a win, disables the button if a win occurs, and triggers the computer's move. It increments a counter, resets a flag, creates a button, updates the game array, checks results for both players, and disables the button if the game ends. | def b23():
global c
c=c+1
global n
n=0
a23=Button(play,text=player1,width=12,anchor=CENTER,height=3)
a23.grid(row=1, column=2 ,padx=5,pady=5)
game[5]=player1
# print(game)
if checkresult(game,player1):
dis(player1)
n=1
... |
def checkresult(bo,p):
global c
solution1=list(set((bo[0],bo[4],bo[8])))
solution2=list(set((bo[0],bo[3],bo[6])))
solution3=list(set((bo[1],bo[4],bo[7])))
solution4=list(set((bo[3],bo[4],bo[5])))
solution5=list(set((bo[2],bo[5],bo[8])))
solution6=list(set((bo[2],bo[4],bo[6])))
solution7=... | The function `b31()` handles a turn in a two-player game by updating the game state with player1's move, checking for a win, disabling the button if player1 wins, letting the computer make a move, updating the game state with player2's move, and checking if player2 wins. It manages GUI elements, game logic, and flow co... | def b31():
global c
c=c+1
global n
n=0
a31=Button(play,text=player1,width=12,anchor=CENTER,height=3)
a31.grid(row=2, column=0 ,padx=5,pady=5)
game[6]=player1
# print(game)
if checkresult(game,player1):
dis(player1)
n=1
... |
def checkresult(bo,p):
global c
solution1=list(set((bo[0],bo[4],bo[8])))
solution2=list(set((bo[0],bo[3],bo[6])))
solution3=list(set((bo[1],bo[4],bo[7])))
solution4=list(set((bo[3],bo[4],bo[5])))
solution5=list(set((bo[2],bo[5],bo[8])))
solution6=list(set((bo[2],bo[4],bo[6])))
solution7=... | This function handles a player's move in a game, updates the game state, checks for a win, disables the button after the move, and triggers the computer's response if no win condition is met. | def b32():
global c
c=c+1
global n
n=0
a32=Button(play,text=player1,width=12,anchor=CENTER,height=3)
a32.grid(row=2, column=1 ,padx=5,pady=5)
game[7]=player1
# print(game)
if checkresult(game,player1):
dis(player1)
n=1
... |
def checkresult(bo,p):
global c
solution1=list(set((bo[0],bo[4],bo[8])))
solution2=list(set((bo[0],bo[3],bo[6])))
solution3=list(set((bo[1],bo[4],bo[7])))
solution4=list(set((bo[3],bo[4],bo[5])))
solution5=list(set((bo[2],bo[5],bo[8])))
solution6=list(set((bo[2],bo[4],bo[6])))
solution7=... | This function handles a player's move in a tic-tac-toe game by updating the game state, creating a button for the player's move, checking for a win, then letting the computer make a move. It increments a counter, disables the button after the move, and checks if either player has won, displaying the result if applicabl... | def b33():
global c
c=c+1
global n
n=0
a33=Button(play,text=player1,width=12,anchor=CENTER,height=3)
a33.grid(row=2, column=2 ,padx=5,pady=5)
game[8]=player1
# print(game)
if checkresult(game,player1):
dis(player1)
n=1
... |
def list_threads(self, verbose):
"""Prints OpenMP threads only that are being tracking inside the "threads" dictionary.
See handle_stop_event and add_thread.
"""
list_tids = []
curr_inferior = gdb.selected_inferior()
for in... | This function compares OMPT tool data with OMPD function data for parallel regions by checking thread states, IDs, levels, task frames, and other ICV-mapped variables. It validates consistency between OMPT and OMPD values, printing mismatches for fields like `ompt_state`, `omp_thread_num`, and `ompt_parallel_data`, ens... | def compare_ompt_data(self):
"""Compares OMPT tool data about parallel region to data returned by OMPD functions.
"""
# make sure all threads and states are set
self.list_threads(False)
thread_id = gdb.selected_thread().ptid[1]
... |
def get_n_days_ago(self, n: int):
utc_now = datetime.now(tz=timezone.utc)
n_days_ago = utc_now - timedelta(days=n)
n_days_ago_str = n_days_ago.strftime('%Y-%m-%d')
return n_days_ago_str
def get_addresses(self, n_days: int, limit: int):
n_day_ago = self.get_n_days_ago(n_days)
... | The function generates a ranked DataFrame of addresses based on transaction activity, profitability, and WETH trade percentages. It filters addresses by last transaction time, retrieves transaction and balance data, calculates metrics like profit and WETH trade ratios, sorts results by profit, and returns a structured ... | def get_df(self, limit: int, days: int, last_tx_time: int, n_visible_rows: int):
days_ago = self.get_n_days_ago(days)
address_list = self.get_addresses(days, limit)
txns_dict = {}
last_txn_time_dict = {}
last_txn_timestamp_limit = (
datetime.utcnow() - timedelta(... |
def turn_right():
#Unable to turn right, we have Karel turn left 3 times.
for i in range(3):
turn_left()
def turn_around():
#purpose it turns Karel around
for i in range(2):
turn_left()
def odd_row_beeper():
"""
Karel will place beepers on the bottom row, leaving a space between ... | The main task of the code is to direct Karel to create or adjust the top row for odd-numbered scenarios. It checks if the left path is blocked, navigates accordingly, and places a beeper if none exist. The function ensures Karel ends at the top row's first column after completing the row setup, handling movement and be... | def check_make_top_row():
"""
Karel makes the laws row for odd numbers
pre:if row is clear due to odd number, makes row
post: karel is at top row, first col with last row made.
"""
if left_is_blocked():
turn_right()
move()
if no_beepers_present():
turn_around(... |
def odd_row_beeper():
"""
Karel will place beepers on the bottom row, leaving a space between each beepr
#pre:Karel starts at bottom left.
#post:Karel ends at bottom left, and beepers is placed in the romw
"""
if front_is_blocked():
put_beeper()
while front_is_clear():
put_be... | The main task of the code is to have Karel create a checkerboard pattern by alternating beepers in odd and even rows. It moves up each row, fills beepers accordingly, checks for the last row, and returns to the starting position. | def main():
"""
Karel will fill the world with a checkerboard pattern
"""
while left_is_clear():
#odd number rows of Beeper
#Purpose: Create a start point for each row regardless of size of world
odd_row_beeper()
#karel moves up a row
karel_row_up()
#even ... |
def prepare_email_data_one_chart(event_internal):
subject_str = "Relative " + event_internal['ticker_1'] + "-" + event_internal['ticker_2']
local_file_name = LOCAL_FOLDER + event_internal['chart_filename']
s3.download_file(BUCKET_NAME, event_internal['chart_filename'], local_file_name)
mail_imputs_data_... | The code processes incoming events to prepare email data with charts. Depending on the event type ("Stocks_relative_two", "Stocks_single", or "FX"), it uses different functions to generate data. It then sends an email with the prepared data and returns the email message ID. If the event type is invalid or data preparat... | def lambda_handler(event, context):
# print("Incoming event:")
# print(event)
inputs_data_store = None
try:
if event['type'] == "Stocks_relative_two":
msg, inputs_data_store = prepare_email_data_one_chart(event)
if (event['type'] == "Stocks_single") or (event['type'] == "FX")... |
def _prepare_stock_ticker_import_url(stock_ticker):
url_backbone = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&outputsize=full&datatype=csv&apikey="
symbol_backbone = "&symbol="
return url_backbone + alpha_vantage_api_key + symbol_backbone + stock_ticker
def _import_preprocess_ticker_data(... | This function imports stock ticker data from a prepared URL, preprocesses it, validates the result as a DataFrame, renames the 'volume' column to 'Volume', uploads the data as a pickle file, and returns True on success or logs failures by appending to a list and returning False on invalid data. | def _import_stock_ticker_data(ticker_code, failed_imports_list, ticker_file_name):
print("Fresh ", ticker_code, " data file NOT found in our S3, so now import it")
data_import_url = _prepare_stock_ticker_import_url(ticker_code)
imported_data = _import_preprocess_ticker_data(data_import_url)
if not isins... |
def _check_fresh_file_in_bucket(file_key, max_age_minutes=10):
print(
"Trying to find the ",
file_key,
" file in the S3 bucked and check if it is fresh or outdated",
)
try:
res = s3.head_object(Bucket=BUCKET_NAME, Key=file_key)
except Exception as e:
print(file_ke... | The function processes an FX data row by checking if the combined ticker exists in failed imports or S3 storage. If found in failed imports, it returns a failure response. If a fresh S3 file exists, it returns success without reimporting. If no file exists, it attempts to import the data, updating failure records or re... | def process_fx_row(event_internal, failed_imports_internal):
combined_ticker_fx = event_internal["Ticker1"] + "-" + event_internal["Ticker2"]
print("Row is FX - ", combined_ticker_fx)
# search FX ticker in failed_imports
if combined_ticker_fx in failed_imports_internal:
print(
combi... |
def process_stocks_relative_two(event_internal):
print("Function process_stocks_relative_two started - ", event_internal['ticker_1'], "-", event_internal['ticker_2'])
data_1 = _download_pickle_data_from_s3(event_internal['file_1'])
data_2 = _download_pickle_data_from_s3(event_internal['file_2'])
chart_f... | This AWS Lambda function processes incoming financial data events by routing them to specific handling functions based on their type (Stocks_relative_two, FX, or Stocks_single), executes the corresponding processing logic, and returns the result in a standardized HTTP response format with a 200 status code. | def lambda_handler(event, context):
# print("Incoming event:")
# print(event)
response_dict = None
if event['type'] == 'Stocks_relative_two':
response_dict = process_stocks_relative_two(event)
if event['type'] == 'FX':
response_dict = process_fx_row(event)
if event['type'] == 'St... |
def get_failed_imports_list():
failed_imports_file_fresh = _check_fresh_file_in_bucket(FAILED_IMPORTS_FILE_REMOTE)
if failed_imports_file_fresh:
s3.download_file(
BUCKET_NAME,
FAILED_IMPORTS_FILE_REMOTE,
"/tmp/" + FAILED_IMPORTS_FILE_REMOTE,
)
with ope... | This Lambda function processes incoming financial events (Forex or Stocks) by determining the event type, using the appropriate processing function (process_fx_row or process_stocks_row) with a list of failed imports, and returning a 200 OK response containing the processed data in JSON format. | def lambda_handler(event, context):
# print('Incoming event:')
# print(event)
failed_imports = get_failed_imports_list()
if event["Type"] == "Forex":
response_dict = process_fx_row(event, failed_imports)
return {"statusCode": 200, "body": response_dict}
else:
# stocks - sing... |
def draw_board(board):
"fungsi untuk mmenggambar papan permainan"
print(board[0] + "|" + board[1] + "|" + board[2])
print("-+-+-")
print(board[3] + "|" + board[4] + "|" + board[5])
print("-+-+-")
print(board[6] + "|" + board[7] + "|" + board[8])
def get_best_move(board, player):
"Fungsi utk mendapatkan ... | This code implements a Tic Tac Toe game where a human player ('x') competes against an AI ('o'). The game alternates turns, with the human inputting moves and the AI selecting optimal moves via the get_best_move function. It checks for wins/draws after each move, displaying the board state and announcing results. | def tic_tac_toe():
"Fungsi untuk menjalankan permainan Tic Tac Toe"
board = [" ", " "," ", " ", " ", " ", " ", " ", " "]
players = ["x", "o"]
turn = random.choice([0,1])
while True:
draw_board(board)
print("player"+players[turn]+"'s turn.")
if players[turn] == "x":
move = int(input("Enter ... |
def convert_microbenchmark(
self,
f: TextIOWrapper,
num_layers: int
) -> None:
layers = self.get_layers(f, num_layers)
for npu_id in range(self.num_npus):
output_filename = "%s.%d.et" % (self.output_filename, npu_id)
with open(output_filename, "wb") as... | The code reads an input file to determine a parallelism type (e.g., MICRO, DATA, MODEL, HYBRID variants) and number of layers, then converts the data using specialized methods based on the detected type, handling hybrid configurations with additional parameters, raising an error for unsupported types. | def convert(self) -> None:
with open(self.input_filename, "r") as f:
first_line = f.readline().strip().split()
parallelism_type = first_line[0]
num_layers = int(f.readline().strip())
if parallelism_type == "MICRO":
self.convert_microbenchmark(f, n... |
def get_pytorch_node_type(
self,
node: Dict[str, Any]
) -> PyTorchNodeType:
if self.is_gpu_op(node):
return PyTorchNodeType.GPU_OP
elif (node["op_schema"] or node["outputs"])\
or ("fc00:db20:35b:7399::5" in node["name"] or ("nccl:" in node["name"])):
... | The code performs a depth-first search (DFS) to traverse a graph of nodes, identifying and storing PyTorch CPU operators in `pt_cpu_node_dict`. It avoids GPU operators and recursively processes child nodes, excluding the root node. For LABEL nodes, it computes the largest node ID (NID) in the subtree. The function retu... | def dfs(
self,
node: Dict[str, Any],
root_nid: int,
) -> int:
"""
Discovers all PyTorch CPU operators under a given node while populating
pt_cpu_node_dict, After that, returns the largest NID in the tree.
"""
nid = node["id"]
node_type = self.g... |
def find_root_nids(
nodes: List[Any]
) -> int:
"""
Finds a root node and return its NID.
* Assumption: There could be multiple root node in a given execution trace.
"""
root_nids = []
for node in nodes:
if "[pytorch|profiler|execution_graph|thread... | (The function discovers PyTorch CPU operators by performing a depth-first search (DFS) on root nodes, identifying phase root nodes, and populating a dictionary with CPU operators. It collects the largest node ID (NID) from each phase, stores them in a list, and sorts the list to ensure increasing order, enabling depend... | def discover_pytorch_cpu_ops(
self
) -> None:
"""
Discovers PyTorch CPU operators and populate pt_cpu_node_dict.
Run DFS on a root node and phase root nodes as they may have CPU operators.
DFS populates pt_cpu_node_dict and returns the largest NID within the phase.
"... |
def convert_pytorch_node_to_chakra_node(
self,
pt_node: Dict[str, Any]
) -> ChakraNode:
"""
Converts a PyToch node to a Chakra node.
"""
ck_node = ChakraNode()
ck_node.id = pt_node["id"]
ck_node.name = pt_node["name"]
ck_node.type = self.get_ch... | This function converts a PyTorch GPU node to a Chakra node by retrieving the corresponding PyTorch node from a dictionary, handling errors for duplicate entries, adding communication attributes for collective operations, linking data dependencies, and storing the resulting Chakra node in the ck_node_dict. | def add_gpu_chakra_node(
self,
ck_cpu_node: ChakraNode
) -> None:
"""
Converts a PyTorch GPU node to a Chakra node and add it to ck_node_dict.
"""
assert ck_cpu_node.id in self.pt_gpu_node_dict.keys()
pt_gpu_node = self.pt_gpu_node_dict[ck_cpu_node.id][0]
... |
def create_xpath_dict(html, only_body=True, max_length=200): # used to generate dict nodes
''' Create a list of xpaths and a list of dict of attributes of all elements in the html'''
soup = BeautifulSoup(html, 'html.parser')
if only_body:
root = soup.body
else:
root = soup.html
eleme... | The function retrieves the top N HTML elements most relevant to a query by converting HTML content into structured nodes with XPaths, using embeddings and BM25 retrieval. It processes data in memory-efficient groups, ranks results by relevance, and returns the highest-scoring nodes with their XPaths as metadata. | def get_results(query, html, embedder, top_n=5, group_by=10, rank_fields=None): # used to generate and retrieve dict nodes
''' Return the top_n elements of the html that are the most relevant to the query as Node objects with xpath in their metadata'''
xpath_list, attributes_list = create_xpath_dict(html)
a... |
def prepare_demos(demographics_file, level, subject_ids=None, session_ids=None, ):
"""
splits demo df into age (1 val per subject) and age (1 val per session)
sex_df has subject_id as index
age_df has (subject_id, session_id) as index
Returns df (selected by level {"subject", "session"})
"""
... | This function uploads behavioral study data to a project by connecting to a session, preparing demographic and behavioral data, filtering sessions with available data, creating behavioral sessions, and uploading the data while timing each step. | def upload_bids_behavioral_study(space, project, behavdata_dir, behav_demographics_file, subject_ids=None,
session_ids=None):
# fixme username
session = open_connection(username="admin")
## behav session
# fixme get real behav sessions
behav_session_df = prepare_dem... |
def setup_project(session, space, project):
# creates project and BIDS specific collections
# 1. Project
p = session.new_project(space=space, code=project, description="BIDS project")
p.save()
# 2. Collections
for c in ["SUBJECT_COLLECTION", "MRI_SOURCEDATA_COLLECTION", "BEHAVIORAL_SESSION_COLLE... | The code uploads MRI data from BIDS format into a project by creating subjects, MRI sessions, and uploading data. It prepares demographic and session dataframes, filters sessions with available MRI data, registers entities in the project, and uploads MRI files while timing each step. | def upload_bids_mri_study(space, project, sourcedata_dir, behavdata_dir, demographics_file, subject_ids=None,
session_ids=None):
# fixme username
session = open_connection(username="admin")
try:
session.get_project(project)
except:
setup_project(session, space,... |
def send(self, message):
"""
Send a message through client socket
:param message: Message got sent
:return:
"""
self.sock.send(message)
def recv_large(self):
"""
Receive a "large" piece of Message iteratively until it finishes
:return: the ACTUAL... | This code implements a client's workflow in a federated learning system. It establishes communication, preprocesses data, performs dimensionality reduction, exchanges model parameters with a federator, trains a local model, and reports results. The client receives initial models, trains them on reduced data, and partic... | def work(self):
"""
Client working pipeline
:return:
"""
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Connection establishment stage (single)
pk_pem = self.pk.exportKey()
init_msg = Message(pk_pem, CommStage.CONN_ESTAB)
... |
def scrape_main(html):
"""
Receives the full html from the main page and returns a list of urls to all the articles.
:param html: str
:return: list
"""
soup = BeautifulSoup(html, 'html.parser').find('div', class_='story-stack')
links = pd.Series(
[URL + link.get('href') for link in s... | (The function scrapes HTML content to extract article data (titles, summaries, authors, etc.), processes it in batches, and inserts the structured data into a MySQL database using provided credentials. It uses a dictionary (`scrape_by`) to define scraping rules, splits links into batches, creates `Article` objects, che... | def scraper(html, batch, scrape_by, user, password, host, database):
"""
scrapes the html source code and save the data into the database in batches
:param html: string of html source code
:param batch: int size of batch
:param scrape_by: dictionary defining how to scrape
:param user: username o... |
def welcome():
"""
Gets the category and number of articles required by the user, with argparser,
and outputs the relevant URL suffix for these articles together with the number of articles.
the program also response to the flag -h for help.
return: category: relevant category URL suffix.
... | The main task of the code is to scrape specified data (title, summary, author, link, tags, date-time) from Coindesk articles based on a given category and number of articles. It uses Selenium to retrieve HTML, processes the data, stores it in a database, and optionally enriches tags. The script measures and prints the ... | def main():
"""Receives Coindesk topic category and number of articles to print as command parameters.
Uses selenium to retrieve the required html script.
Scrapes and prints each article for the following data:
Title, Summary, Author, Link, Tags and Date-Time"""
before = time.time()
category... |
def get_topological_order(bn):
order = []
vars = list(bn.keys())
while(len(order) < len(vars)):
for v in vars:
pars = bn.get(v).get('parents')
if(set(pars).issubset(set(order))):
if(not int(v) in order):
order.append(int(v))
... | The function `metropolis_hastings` performs Metropolis-Hastings sampling on a Bayesian network (`bn`) to estimate the distribution of a query variable (`qv_name`). It combines Gibbs sampling and weighted sampling to generate samples, updating counts of occurrences for the query variable's states (0 and 1). The algorith... | def metropolis_hastings(p, qv_name, bn, N, E = {}):
order = get_topological_order(bn)
counts = [0, 0]
x = {}
r_val = random.random()
true_count = 0
while(N>0):
while(r_val < p and N>1):
true_count+=1
r_val = random.random()
N-=1
... |
def get_unique_advertises_with_lowest_price(
creatives: List[Creative], country: Optional[CountryType] = None,
) -> IdCreativesMapType:
unique_creatives: IdCreativesMapType = {}
for entity in get_creatives_filtered_by_country(creatives, country):
existing_entities = unique_creatives.get(entity.adver... | The function `auction` selects the top `number_winners` creatives by prioritizing unique advertisers with the lowest prices, using a random generator to choose winners from eligible candidates, ensuring fair competition based on pricing and randomness. | def auction(
creatives: List[Creative],
number_winners: int,
country: Optional[CountryType] = None,
rng: Optional[np.random.Generator] = None,
) -> List[Creative]:
if rng is None:
rng = RNG
# Build a dict of unique advertiser creatives with lowest price
unique_creatives = get_unique_... |
def load_cached_data():
try:
if os.path.exists(cache_file):
with open(cache_file, "r") as cache:
data = json.load(cache)
timestamp = data.get("timestamp")
if timestamp and (datetime.now() - datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")) < timed... | The main task of the code is to provide a menu-driven interface for managing GitHub repositories. It loads cached or fetches repository data, then allows users to filter, search, display statistics, export to JSON, create/delete repositories, check rate limits, or exit. The code handles errors during data retrieval and... | def fetch_repositories():
repositories = load_cached_data()
if repositories is None:
repositories = fetch_all_repositories()
if repositories is None:
error_message = "Failed to retrieve repository data."
logging.error(error_message)
print(error_message)
... |
def get_regular_moves(board, player, row, col):
moves = []
directions = []
if board[row][col] == PLAYER_1:
directions = [(1, -1), (1, 1)]
elif board[row][col] == PLAYER_2:
directions = [(-1, -1), (-1, 1)]
else:
directions = [(1, -1), (1, 1), (-1, -1), (-1, 1)]
for dir_r... | This function generates all possible moves for a player on a checkers board, distinguishing between regular moves and captures. If mandatory captures are required, only capture moves are considered; otherwise, both are combined. Moves are sorted by their evaluation value, prioritizing the most advantageous ones, and re... | def get_possible_moves(board, player):
moves = []
regular_moves = []
eating_moves = []
for i in range(8):
for j in range(8):
if board[i][j] == player or board[i][j] == player + 2:
regular_moves += get_regular_moves(board, player, i, j)
eating_moves +=... |
def evaluate(board, current_player):
score_player_1 = 0
score_player_2 = 0
eatingScore = 1
kingScore = 2
for row in board:
for cell in row:
if cell == PLAYER_1:
score_player_1 += eatingScore
elif cell == KING_1:
score_player_1 += king... | This code implements the Minimax algorithm with alpha-beta pruning for a two-player game. It recursively evaluates all possible moves up to a specified depth, alternating between maximizing the current player's score and minimizing the opponent's score. The algorithm uses alpha-beta pruning to optimize performance by c... | def minimax(board, depth, alpha, beta, maximizing_player, current_player):
if depth == 0 or not any(PLAYER_1 in row or PLAYER_2 in row for row in board):
return evaluate(board, current_player)
if maximizing_player:
max_eval = float('-inf')
for move in get_possible_moves(board, current_p... |
def get_possible_moves(board, player):
moves = []
regular_moves = []
eating_moves = []
for i in range(8):
for j in range(8):
if board[i][j] == player or board[i][j] == player + 2:
regular_moves += get_regular_moves(board, player, i, j)
eating_moves +=... | The code implements the minimax algorithm with alpha-beta pruning to determine the optimal move for the current player on a given board. It evaluates all possible moves, selects those with the highest evaluation values, and randomly chooses one from them to ensure strategic depth and avoid predictability in gameplay. | def get_best_move(board, current_player):
best_moves = []
best_val = float('-inf')
alpha = float('-inf')
beta = float('inf')
for move in get_possible_moves(board, current_player):
new_board = make_move(board, move)
move_val = minimax(new_board, search_depth - 1, alpha, beta, False, ... |
def getLastPage(url):
page = requests.get(url)
tickSoup = BeautifulSoup(page.content, 'html.parser')
li = tickSoup.find_all('a', class_ = 'no-click') # find the pagination elements
noclick = [route.text for route in li]
p = re.compile(r'\d+')
for el in noclick:
if p.findall(el):
... | The code aggregates ticks data from multiple pages of a website by iterating through each page (determined by getLastPage), constructing page URLs, retrieving ticks from each page, and compiling them into a single list. | def getUserTicks(url):
userTicks = []
for i in range(1, getLastPage(url)+1):
pageurl = getPageURL(i, url)
pageTicks = getPageTicks(pageurl)
userTicks+=pageTicks
return userTicks |
def reset(self):
self.writeRFID(self.CommandReg, self.COMMAND_SOFT_RESET)
def writeRFID(self, addr, val):
val = self.spi.xfer2([(addr << 1) & 0x7E, val])
def AntennaOn(self):
temp = self.readRFID(self.TxControlReg)#Reads value of TxControlReg
if (~(temp & 0x03)):#If antenna driver pins a... | The main task of the code is to initialize the MFRC522 RFID module by resetting it and configuring critical registers with predefined values. This includes setting timing parameters (TModeReg, TPrescalerReg, TReloadRegL/H), communication settings (TxASKReg), and operational mode (ModeReg). The final `AntennaOn()` enabl... | def initRFID(self):
self.reset()#Reset MFRC522
#Set register to starting values
self.writeRFID(self.TModeReg, 0x8D)
self.writeRFID(self.TPrescalerReg, 0x3E)
self.writeRFID(self.TReloadRegL, 30)
self.writeRFID(self.TReloadRegH, 0)
self.writeRFID(self.TxASKReg, 0x4... |
def new_uuid(prefix:str="uuid") -> str:
return prefix + "-" + str(uuid.uuid4())
def update_metadata(aip_path:Path, sip_name:str):
# Update referencese to SIP name with new AIP name
# TODO Update different types of metadata
# Descriptive DC.xml
dc_metadata_path = (aip_path / 'metadata' / 'descriptiv... | The function transforms a Source Information Package (SIP) into an Archival Information Package (AIP) by creating a new directory with a unique identifier, copying SIP contents, updating metadata, and modifying METS files to conform to AIP specifications. | def transform_sip_to_aip(sip_path:Path, output_path:Path) -> str:
sip_name = sip_path.stem
aip_name = new_uuid()
# For Testing
# aip_name = sip_name
aip_path = (output_path / aip_name)
# Update metadata to reflect new directory name
update_metadata(aip_path, sip_name)
# (Re-)create ... |
def get_sequence_from_Data(x:Data, attr:str = "node_id", three_to_one:bool = False, return_chain:bool = True):
"""Generate sequence from pyg Data by "node_id" attr, note ``chain_dict`` is consist of chian_list.
``chain_dict`` looks like: {"A":[["VAL", 1], ["LEU", 2]], "B":[["MET", 1], ["LEU", 2]]}. Generally... | This function modifies a protein PyG graph by incorporating SNP mutations, updating node metadata, and adding mutation-specific attributes. It processes input SNPs to generate mutated sequences, updates graph labels, and applies Graphein node metadata functions to create chain-level embeddings, returning the enhanced P... | def generate_nsSNP_pyg(x:Data,
SNP:Union[str, Dict[str, str]],
node_metadata_functions:Optional[Dict[str, Callable]] = None,
graph_label:Optional[Union[int, Dict[str, int]]] = None,
# graphein_config: ProteinGraphConfig = ProteinGraphConfig(),
three_to_one:bool = False):
"""turn protein pyg into... |
def batchnorm_relu(inputs):
x = BatchNormalization()(inputs)
x = Activation("relu")(x)
return x
def residual_block(inputs, num_filters, strides=1):
""" Convolutional layer"""
x = batchnorm_relu(inputs)
x = Conv2D(num_filters, 3,padding="same",strides=strides)(x)
x = batchnorm_relu(x)
x =... | This code constructs a ResUNet model for image segmentation. It uses residual blocks in encoders, a downsampling bridge, and decoder blocks with skip connections to reconstruct features, ending with a sigmoid-activated output layer for binary segmentation tasks. | def build_resunet(input_shape):
inputs = Input(input_shape)
"""Encoder 1"""
x = Conv2D(64,3,padding="same",strides=1)(inputs)
x = batchnorm_relu(x)
x = Conv2D(64, 3,padding="same",strides=1)(x)
s = Conv2D(64,1,padding="same",strides=1)(inputs)
s1 = x + s
"""Encoder 2 ,3"""
s2 = res... |
def compute_bias_metrics_for_model(dataset, subgroups, model, label_col, include_asegs=False):
"""Computes per-subgroup metrics for all subgroups and one model."""
records = []
for subgroup in subgroups:
record = {
'subgroup': subgroup,
'subgroup_size': len(dataset[dataset[su... | The main task of the code is to evaluate a machine learning model's performance by computing bias metrics and combining them with an overall AUC score. It processes validation data, applies sigmoid activation to predictions, converts identity columns to numeric values, calculates fairness metrics, prints performance re... | def get_value(df_valid, valid_outputs, model_name):
df_valid[model_name] = torch.sigmoid(torch.tensor(valid_outputs)).numpy()
df_valid[config.IDENTITY_COLUMNS] = df_valid[config.IDENTITY_COLUMNS].replace('none', '0')
df_valid[config.IDENTITY_COLUMNS] = df_valid[config.IDENTITY_COLUMNS].astype(float)
... |
def crawl(directory):
"""
Parse a directory of HTML pages and check for links to other pages.
Return a dictionary where each key is a page, and values are
a list of all other pages in the corpus that are linked to by the page.
"""
pages = dict()
# Extract all links from HTML files
for f... | The code computes and prints PageRank scores for web pages in a given corpus using two methods: sampling and iterative calculation. It first validates input, crawls the corpus, calculates ranks via sampling with a specified number of samples, then uses an iterative approach. Results are displayed sorted by page name, s... | def main():
if len(sys.argv) != 2:
sys.exit("Usage: python pagerank.py corpus")
corpus = crawl(sys.argv[1])
ranks = sample_pagerank(corpus, DAMPING, SAMPLES)
print(f"PageRank Results from Sampling (n = {SAMPLES})")
for page in sorted(ranks):
print(f" {page}: {ranks[page]:.4f}")
... |
def getSnifferFile(wireless_file_name, config):
df = pd.read_csv('rawdata/' + str(config['date']) + '/' + wireless_file_name + '.csv', parse_dates=[0])
df.columns = ['time','mac','type','rssi','uuid']
df = df.drop('mac', axis=1)
df = df.drop('type', axis=1)
df = df.astype({'time':'string'})
df =... | The main task of the code is to preprocess wireless data by aggregating experiment results for each mobile device. It reads sniffer files, generates DataFrames using configuration parameters, concatenates experiment data, and returns a dictionary of processed DataFrames. The function handles multiple mobile devices and... | def getWirelessData(config):
file_list = []
for file_name in config['sniffer_list']:
file_list.append(getSnifferFile(file_name, config))
df_dict = {}
for mobile_name in config['mobile_list']:
printLog("Start preprocessing " + mobile_name + ".")
df = createDF1(config = config)
... |
def authorize():
creds = False
token_path = r"..\config\token.json"
if os.path.exists(token_path):
try:
creds = Credentials.from_authorized_user_file(token_path, SCOPE)
except Exception as e:
print(f"[ERROR] {e}")
disable_uploading()
return
... | The function uploads files from a local directory to a specified Google Drive folder. It extracts the folder name from the provided path, authorizes access to Google Drive, collects files from the local path, and uploads them to the designated backup folder in Google Drive using the gathered files and authorization cre... | def upload_files_to_google(path, backup_folder_id):
folder_name = os.path.split(path)[-1]
drive = authorize()
if drive is not None:
files = gather_files(path)
upload_files_to_folder(files, folder_name, backup_folder_id, drive) |
def eat(self, expected_type):
"""
Consumes the current token if it matches the expected type.
Args:
expected_type: The expected type of the token.
Returns:
None
Raises:
Exception: Raised when an unexpected token is encountered.
"""
... | The main task of the code is to parse an expression starting with a condition token ("?"), evaluate the condition, and return the parsed reply if true, otherwise return None. It consumes tokens, checks the condition, and conditionally parses a reply using parse_reply() or returns None based on the condition's truth val... | def parse_expr(self):
"""
Parses an expression in the input code.
Returns:
The result of the parsing.
"""
token = self.current_token
if token.value == "?":
self.eat("?")
condition = self.parse_condition()
self.eat(":")
... |
def get_all_links(self, max_pages=200, wait=10):
'''
Get the links of all talks
:return: list of string
'''
from tqdm import tqdm
url_templ = 'https://www.ted.com/talks?sort=newest&language=' \
+ self.language + '&page={}'
pbar = tqdm(range(... | The main task of the code is to crawl and retrieve transcripts from web pages by iterating through provided or generated links, extracting HTML content, and storing it in a dictionary with optional auto-saving. It handles link gathering, rate limiting, progress tracking, and transcript extraction to compile a collectio... | def get_all_webpages(self, max_webpages: int = None,
links: list = None, max_link_pages: int = 200,
wait: int = 10, auto_save: bool = True) -> dict:
'''
Get the transcripts of all talks
:param (list) links: list of links that you want to crawl t... |
def get_all_webpages(self, max_webpages: int = None,
links: list = None, max_link_pages: int = 200,
wait: int = 10, auto_save: bool = True) -> dict:
'''
Get the transcripts of all talks
:param (list) links: list of links that you want to crawl t... | This function retrieves or loads webpage transcripts, parses HTML content into structured text, and saves the results. It either fetches webpages (if `read_existing_file` is False) or loads pre-saved data from a JSON file. Transcripts are parsed from HTML, aggregated into a dictionary, and flattened into sentences. The... | def get_all_transcripts(self, read_existing_file: bool = False,
max_webpages: int = None, links: list = None,
max_link_pages: int = 200, wait: int = 10) -> None:
from tqdm import tqdm
from efficiency.function import flatten_list
if not rea... |
def checkPortal(self):
if self.game.maze.getMaze(self.posn) == 's':
self.posn = Vector(1, 30)
self.pxPosn = Vector((self.posn.x + 0.5) * self.settings.block_size,
(self.posn.y + 0.5) * self.settings.block_size)
elif self.game.maze.getMaze(self.pos... | This code updates a ghost's behavior in a game, switching between scatter and normal modes based on tick counts, handling states like being eaten, scared, or dead, and adjusting movement speed and direction accordingly. It updates the ghost's position, triggers sound effects, and manages transitions between states, ens... | def update(self, ticks):
# print(self.isScared)
self.checkPortal()
if ticks % 15000 <= 10000:
self.isScatter = False
# print('in scatter mode')
elif ticks % 15000 > 10000:
self.isScatter = True
# print('out of scatter mode')
if self... |
def set_params(self, w, b):
"""
Set the model parameters.
Params
------
w (ndarray, shape = (n_features,)):
coefficient of the linear model.
b (float): bias term.
"""
self.w = w
self.b = b
def subgradient(self, wb, X, y... | This code trains a Support Vector Machine (SVM) using subgradient descent with a decaying learning rate. It initializes parameters, iteratively updates weights and bias by computing subgradients, tracks the objective function value at each iteration, and retains the best parameters that minimize the objective. The proc... | def fit(self, X, y, lr=0.002, iterations=10000):
"""
Fit the model using the training data.
Params
------
X : (ndarray, shape = (n_samples, n_features)):
Training input matrix where each row is a feature vector.
y : (ndarra... |
def syntactic(doc):
t_units = 0
t_length = len(doc)
complex_t = 0
n_sents = 0
n_clauses = 0
for sent in doc.sents:
n_sents += 1
sent_nlp = parser.raw_parse(sent.text)
for item in sent_nlp:
n_clauses += count_clauses(item, [])
t_info = count_t(item,... | The code processes senator-related text data by categorizing documents into election/non-election and hurricane/non-hurricane groups, computing linguistic metrics (syntactic, logical, readability scores), and saving results in JSON files. It aggregates processed data for all senators into a dictionary for further analy... | def run_experiment(election_senators, hurricane_senators):
big_data = {}
senators_to_process = sorted(list(set(election_senators) | set(hurricane_senators)))
for senator in senators_to_process:
sen_file = "Senators/" + senator + ".csv"
in_file = open(sen_file, 'r', encoding='utf-8')
... |
def divide_image(matrix):
submatrices = []
for i in range(0, 120, 40):
if not (i // 40) & 1: # zigzag
for j in range(0, 320, 40):
submatrices.append(((i, j), matrix[i:i+40, j:j+40]))
else:
for j in range(280, -40, -40):
submatrices.append(... | The code generates a path through non-zero regions of a matrix by dividing it into submatrices, solving the Traveling Salesman Problem (TSP) for optimal routes between endpoints, and compiling movement commands to traverse these routes. It skips zero regions, calculates distances between route endpoints, and constructs... | def pathing(matrix):
commands, current = [], (0, 0)
for offset, submatrix in divide_image(matrix):
if np.all(submatrix == 0):
continue
commands += goto_next(current, offset, plot=False)
current = offset
routes = label_routes(submatrix, offset)
endpoints = [(... |
def get_h(config_path):
global h #hyperparameters for audio & MEL # don't need to define as global here.
# used to store h parameters for mel
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
if not os.p... | The main task of the code is to generate and visualize mel spectrograms from audio files using a specified configuration. It parses command-line arguments, loads a configuration file, processes an input WAV file to create a mel spectrogram, converts it to a numpy array, plots the spectrogram, and optionally saves it as... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input_wav_path', default='speech_clips/audioclipglory1_1.mp3')
parser.add_argument('--config_path', default='bigvgan_24khz_100band_config.json')
parser.add_argument('--input_wav_dir', default='speech_clips')
parser.add_argument('... |
def cname(o):
return o.__class__.__name__
def compile_expression(self, expression):
self.logger.info('Expression: %s', expression)
typ = cname(expression)
if typ == 'Expression':
ops = expression.op
if len(ops) == 1:
self.compile_expression(ops[0])
... | This function compiles an assignment statement by logging it, determining its type, and generating bytecode (OP_STORE) to store a variable's value at a calculated memory offset. If the statement isn't an assignment, it raises an error. | def compile_statement(self, statement):
self.logger.info('Statement: %s', statement)
typ = cname(statement)
if typ == 'Assignment':
self.compile_expression(statement.value)
varname = statement.variable_name
offset = self._var_offsets[varname]
print... |
def cname(o):
return o.__class__.__name__
def compile_variable(self, variable):
self.logger.info('Variable: %s', variable.name)
var_size = self.var_sizes[variable.typ]
offset = self._mem_pool_offset
self.emit_listing('Placing variable {} at {}'.format(variable.name, offset))
... | The code compiles a program by initializing memory offsets and variable storage, then processes each declaration in the input. It identifies declaration types (Variable/Function) using `cname`, compiles them accordingly, and logs progress. Unknown types trigger errors. The core task is translating program declarations ... | def compile_program(self, m):
self._mem_pool_offset = 0
self._var_offsets = {}
for declaration in m.declarations:
self.logger.info('declaration: %s', declaration)
typ = cname(declaration)
if typ == 'Variable':
self.compile_variable(declaration... |
def prompt_user_input(story, level, scene):
print("What will you do? Type the number of the option or type '/h' to show help.\n")
choices = story['choices'][f'lvl{level}'][f'scene{scene}']
choices_print = ""
for choice in choices:
choices_print += choice[-1] + '- ' + choices[choice]
retur... | The main task of the code is to manage a text-based adventure game loop, handling scene progression, user input processing, inventory updates, life management, and game-ending conditions. It loads story data, applies effects from player actions (e.g., adding/removing items, modifying lives), triggers saves, and transit... | def main_game_loop(char, user_name, diff_str, inv, level, scene):
my_path = os.path.join('.', 'story', 'story.json')
with open(my_path) as story_file:
story = json.load(story_file)
while True:
print_red_on_cyan = lambda x: cprint(x, "red", "on_cyan")
print_red_on_cyan(story['sto... |
def create_character(saved_game):
if saved_game is None:
print("Create your character:")
char = {"name": input("1- Name \n").capitalize(), "species": input("2- Species \n").capitalize(),
"gender": input("3- Gender \n").capitalize()}
print("Pack your bag for the journey:")... | The main task of the code is to initialize a new game session by prompting the user for a username, creating a character and inventory, setting difficulty levels, displaying character stats and game details, and launching the main game loop with initial parameters. It allows returning to the menu if the user chooses '/... | def start_new_game():
print("Starting a new game...")
user_name = input("Enter a user name to save your progress or type '/b' to go back\n")
if user_name == "/b":
print("Going back to menu...")
return
char, inv = create_character(None)
diff_str, char["lives"] = set_difficulty()
... |
def list_save_files():
# print(os.listdir())
all_files = os.listdir('./game/saves')
save_files = []
users = []
for f in all_files:
user = re.search(r"^(.+)\.json$", f)
if user is not None:
user = user.group(1)
users.append(user)
save_files.append(f... | The main task of the code is to load a saved game by retrieving user-specific data from a JSON file, reconstructing the character and inventory, and resuming the game loop with preserved parameters like difficulty, level, and scene. It checks for existing saves, validates the user, and initializes the game state from t... | def load_saved_game():
# print("No save data found!")
users, save_files = list_save_files()
if save_files is None:
print("No save data found!")
else:
print(f'Saved games for these users: {users}')
user = input("Type your user name:\n")
if user not in users:
pr... |
def process_top_menu_input(top_menu_input):
if top_menu_input == "1" or top_menu_input.lower() == "start":
return 1
elif top_menu_input == "2" or top_menu_input.lower() == "load":
return 2
elif top_menu_input == "3" or top_menu_input.lower() == "quit":
return 3
else:
retu... | The code defines a function `top_menu()` that handles a game's main menu loop. It repeatedly processes user input to execute actions: starting a new game, loading a saved game, quitting, or alerting for invalid input. The loop continues until the user selects the quit option (choice 3), which exits the program with a "... | def top_menu():
while True:
top_menu_choice = process_top_menu_input(get_top_menu_input())
if top_menu_choice == -1:
alert_unknown_input()
elif top_menu_choice == 3:
# prompt_to_quit_game()
print("Goodbye!")
sys.exit()
elif top_menu_c... |
def parse_args():
parser = argparse.ArgumentParser('argument for training')
parser.add_argument('--data_path', type=str, help='data path to train the target model')
parser.add_argument('--pretrained_model', type=str, default='supcon') #resnet
parser.add_argument('--pretrained_path', type=str, help='path... | The code's main task is to execute multiple trials (up to 5) of a training/validation process, aggregate their results, and print the final outcomes. It parses input arguments, iterates through trials, collects training and validation results in dictionaries, and displays aggregated statistics. Each trial's output is m... | def main():
args = parse_args()
train_total_results = {}
val_total_results = {}
max_trials = 5
for trial_id in range(1, max_trials + 1):
train_res, val_res = do_helper(args, trial_id)
update_results(train_res, train_total_results)
update_results(val_res, val_total_results)
... |
def pos_to_xy(self, pos):
return (pos % self.board.width, pos // self.board.height)
def reveal(self, x, y, already_revealed):
if not self.valid_pos(x, y):
return already_revealed
# if already checked
for rev in already_revealed:
if rev['x'] == x and rev['y'] == y:... | This function handles a client's selection on a game board by converting the input position to coordinates, revealing cells starting from that position, and either triggering a bomb hit if no cells were revealed or updating the client with the revealed cells and saving them for future reference. | def client_selected_square(self, pos):
x, y = self.pos_to_xy(pos)
reved = self.reveal(x, y, [])
print(reved)
if len(reved) == 0:
self.hit_bomb(self.board.cells.get(x=x, y=y))
else:
self.send_client('change-board', reved)
self.save_revealed(reve... |
def pos_to_xy(self, pos):
return (pos % self.board.width, pos // self.board.height)
def reveal(self, x, y, already_revealed):
if not self.valid_pos(x, y):
return already_revealed
# if already checked
for rev in already_revealed:
if rev['x'] == x and rev['y'] == y:... | This function handles a client's selection on a board by converting the input position to coordinates, revealing cells starting from that position, and either triggering a bomb explosion if no cells are revealed or sending updated board data to the client if cells are revealed. It also saves the revealed cells for trac... | def client_selected_square(self, pos):
x, y = self.pos_to_xy(pos)
reved = self.reveal(x, y, [])
print(reved)
if len(reved) == 0:
self.hit_bomb(self.board.cells.get(x=x, y=y))
else:
self.send_client('change-board', reved)
self.save_revealed(reve... |
def send_new_board(self):
self.send_client('new_board', '')
self.send_client('message', '<i>New board generated!</i>')
def board_generator(self):
self.board = MinesweeperBoard.objects.create(user=self.user)
self.cells = []
for y in range(self.board.height):
self.cells... | This method processes incoming data to control a game board. It handles 'generate' commands to reset and create a new board, 'clicked' actions to select tiles (if the game isn't over), and 'flagged' actions to mark tiles (if the game isn't over), while checking win conditions and managing board state transitions. | def receive(self, text_data):
data = json.loads(text_data)
if data['type'] == 'generate':
self.board.delete()
self.send_new_board()
self.board_generator()
elif data['type'] == 'clicked' and not self.board.is_game_over():
self.client_selected_square... |
def send_new_board(self):
self.send_client('new_board', '')
self.send_client('message', '<i>New board generated!</i>')
def board_generator(self):
self.board = MinesweeperBoard.objects.create(user=self.user)
self.cells = []
for y in range(self.board.height):
self.cells... | This code handles WebSocket messages for a game, processing actions like generating a new board, handling player clicks, and flagging tiles. It parses incoming JSON data, updates the game state based on the 'type' field, and triggers actions such as board deletion, new board creation, tile selection, and win checks, en... | def receive(self, text_data):
data = json.loads(text_data)
if data['type'] == 'generate':
self.board.delete()
self.send_new_board()
self.board_generator()
elif data['type'] == 'clicked' and not self.board.is_game_over():
self.client_selected_square... |
def redo(self):
if self.RStack.size() > 1:
text = self.RStack.peek()
self.TextBox.delete('1.0', END)
self.TextBox.insert(END, text)
self.UStack.add(text)
self.RStack.remove()
def undo(self):
self.isFileChange = True
if self.UStack.size(... | This code handles keyboard events to trigger actions like undo, redo, file operations, and text changes. It updates an undo stack (UStack) whenever text is modified, tracks file changes via `isFileChange`, and manages stack operations based on key presses, including removing/adding entries for undo functionality. | def key_pressed(self, event):
if event.char == "\x1a" and event.keysym == "Z":
self.redo()
elif event.char == "\x1a" and event.keysym == "z":
self.undo()
elif event.char == "\x13":
self.retrieve_input()
elif event.char == "\x0f":
self.open_... |
def check(board,play):
for i in range(0,9,3):
if board[i]==board[i+1]==board[i+2]==play:
return True
for i in range(0,3):
if board[i]==board[i+3]==board[i+6]==play:
return True
if board[0]==board[4]==board[8]==play or board[6]==board[4]==board[2]==play:
return... | This code implements a Tic-Tac-Toe game where a player and AI alternate turns on a 3x3 board. The loop continues until a player or AI wins, or the board fills. The player inputs a position (0-8), which is validated and marked. If the player wins, the game ends immediately. The AI then makes a move via the make_move fun... | def play():
while not check(board,player) and not check(board,ai) and not is_full(board):
print_board(board)
print('player Turn')
w=int(input('enter 0-8: '))
if board[w] !='_':
print('invalid')
continue
board[w]=player
if check(board,player) or... |
def get_parser() -> ArgumentParser:
"""Get the argument parser."""
parser = ArgumentParser(
prog="toml-sort",
formatter_class=argparse.RawDescriptionHelpFormatter,
description="Toml sort: a sorting utility for toml files.",
epilog="""\
Examples:
- **Stdin -> Stdout**: cat inpu... | The code implements a CLI tool for sorting TOML files based on command-line arguments. It validates input parameters, checks for conflicts (e.g., incompatible flags), and processes files by reading, sorting TOML content, and writing results. Options include in-place editing, checking for changes, or outputting to a spe... | def cli( # pylint: disable=too-many-branches
arguments: Optional[List[str]] = None,
) -> None:
"""Toml sort cli implementation."""
args = get_parser().parse_args(args=arguments) # strip command itself
if args.version:
print(get_version())
sys.exit(0)
filenames_clean = args.filenam... |
def is_terminal(self, node):
return not self.has_valid_moves(node.board)
def get_legal_moves(self, board):
# Implement a function to get the legal moves based on the current board state
# Return a list of (col, row) tuples representing legal moves
legal_moves = []
for col in ran... | This code simulates a game by randomly selecting legal moves from the current node's board state until a terminal state is reached. It alternates the player's turn after each move, updates the board with the current player's symbol (1 or 2), and returns the final game result. The simulation continues only if legal move... | def simulate(self,node):
while not self.is_terminal(node):
legal_moves = self.get_legal_moves(node.board)
if not legal_moves:
break #no legal moves, end the simulation
random_move = np.random.choice(np.ravel(legal_moves)) # Flatten the legal_moves array
... |
def handle_click(self):
# get board position
x, y = pygame.mouse.get_pos()
col, row = xy_to_colrow(x, y, self.size)
if not is_valid_move(col, row, self.board):
self.ZOINK.play()
return
self.consecutive_passes = 0
# update board array
self.... | This function processes game events, handling mouse clicks, quitting, and key presses (like passing). When it's the AI's turn, it uses MCTS to generate a move, updates the board with a white stone, toggles the turn, resets pass counters, and redraws the board to reflect changes, ensuring smooth gameplay and AI interact... | def update(self):
# TODO: undo button
events = pygame.event.get()
for event in events:
if event.type == pygame.MOUSEBUTTONUP:
self.handle_click()
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYUP:
... |
def select_node(self, node):
while node.children:
node = max(node.children, key=lambda child: self.ucb_score(child))
return node
def expand_node(self, node):
legal_moves = self.get_legal_moves(node.board)
if not legal_moves:
return None
child_nodes = []
... | The main task of the code is to implement the Monte Carlo Tree Search (MCTS) algorithm to determine the AI's optimal move in a game. It initializes a root node with the current board state, performs selection, expansion, simulation, and backpropagation steps iteratively, then selects the best move based on the MCTS res... | def get_move(self, board):
# Implement the MCTS algorithm to get the AI's move based on the current game state
# Return the chosen move as (col, row)
root = Node(board.copy()) # Create a root node with the current board state
# Add your MCTS algorithm here
# Run MCTS for a ce... |
def few_shot_messages(exclude=None):
messages = []
for entry in few_shots():
if exclude is not None and entry['fsw'] == exclude:
continue
messages.append(create_user_message(entry['fsw']))
messages.append({"role": "assistant", "content": entry['description']})
return mes... | The code generates a description for a given sign (fsw) by combining a system prompt, few-shot examples (excluding fsw), and the specific sign input. It uses OpenAI's GPT-4 model to produce a caption, returning the generated text as the result. | def describe_sign(fsw: str):
messages = [{"role": "system", "content": SYSTEM_PROMPT}] + few_shot_messages(exclude=fsw)
# Add the specific sign
messages.append(create_user_message(fsw))
# Call OpenAI GPT-4 for image caption
response = get_openai_client().chat.completions.create(
model="gpt... |
def load_trained_model(cfg, device, weight_path):
model = call_RepConvResNeXt(cfg, device, deploy=True)
model.load_state_dict(torch.load(weight_path, map_location=device), strict=False)
if cfg.half==1:
model.half().float()
summary(model, (3, cfg.input_size, cfg.input_size))
return model
def ... | The main task of the code is to load a trained model using the provided configuration and weights, convert it to ONNX format for deployment, and perform inference on a specified image using the converted model and configuration settings. | def main(cfg, device, weight_path, img_path):
model = load_trained_model(cfg, device, weight_path)
onnx_file_name = Convert_ONNX(model, device)
inference(onnx_file_name, img_path, cfg) |
def getX(cities):
x = [] #creates empty list to store x coordinates
for city in cities: #loops through all lines in cities
row = city.split() #splits each number on a line into a new list
x.append(row[1]) #adds x coordinate to list 'x'
return x
def getY(cities):
y = ... | The code reads a text file containing city coordinates, removes the first 7 non-coordinate lines, extracts X/Y values, calculates the shortest path between cities, and plots the route. | def main():
print("Please enter path for text file")
file = input()
#open file with open(), 'with' is used to close file afterwords
with open(file) as file_object:
cities = file_object.readlines() #stores each line of file in a list
for _ in range(7): #for loop deletes non coor... |
def read_inv_db(person, count=False): #read inventory of any specified person as an optional parameter
result = query_manage("select user_inv from user_info WHERE user_id = %s", (person,))
if result != 0 and result != []: # result is [] when the table is empty
if count == True:
person_inv = ... | The main task of the code is to allow a user to spin a roulette, granting them a randomly selected item based on predefined rarity tiers. It checks if the user has an inventory and sufficient spins, then selects an item from lists corresponding to rarity levels (uncommon, rare, etc.). The item is added to the user's in... | def spin_roulette_db(ctx):
person = str(ctx.author.id)
person_inv = read_inv_db(person)
if person_inv == 0:
return "You don't have an inventory, yet. Make one. (//help if you're unsure of what to do)"
check_spins = get_num_of_spins(person)[0][0]
if check_spins <= 0:
return "You don't... |
def query_manage(the_query, data=None): # handles queries ---- MOVE TO TOP
DATABASE_URL = os.environ['DATABASE_URL']
con = psycopg2.connect(DATABASE_URL, sslmode = 'require')
cursor = con.cursor() #used to execute commands like a mouse cursor is used to click things
try:
if data==None:
... | The function retrieves all user IDs from the 'user_info' table, iterates through each user, and applies two operations: granting 3 spins and setting a refresh status for each user. Its main task is to批量 process user data by querying the database and triggering specific actions (give_3_spins, set_refresh_for) on all ret... | def redeploy_refresh():
a = query_manage("select user_id from user_info")
print(a)
if (isinstance(a, list)):
i = 0
list1 = []
while i < len(a):
user = a[i][0]
print('redeploy_refresh for ', user)
list1.append(user)
i+=1
print(l... |
def exec_arbitrage_trade(St, tau):
global alpha
global x, y
[bid, ask] = bid_ask(tau)
b=bid
a=ask
if St==18076.5:
pass
num_arb = 0
if b>St:
[dx, dy] = sell_arbitrage(St, tau)
swap(dx, 0, tau)
num_arb=1
elif a<St:
[dx, dy] = buy_arbitrage(St, ta... | The code simulates a trading strategy involving arbitrage, small, and large trades over time steps defined by `S`. It tracks variables like asset holdings (`X`, `Y`), exchange rates, and financial metrics (Vbh, Vlp, IL, Phi) while recording trade counts. Probabilities (`prob_small`, `prob_trade`, `prob_buy`) dictate tr... | def sim(prob_small, prob_trade, y_start, tau):
global alpha
global x, y
global S
eps = 1e-3
prob_buy = 0.5
x = beta * y_start/S[0]
y = y_start
x0 = x
#[X, Y, px, total_arb_trades, total_large_trades, total_small_trades]
df = pd.DataFrame(columns=["S", "X", "Y", "px", "Vbh", ... |
def draw_piece(self, piece, pos, stamp=False):
piece.goto(helpers.screen_coordinates_from_grid_position(pos, self.board_dimensions))
if stamp:
piece.stamp()
def update_score_display(self):
self.score_turtle.clear()
self.score_turtle.goto(0, -350)
self.score_turtle.wri... | The code moves an opponent along a predefined path, checks if it reaches the treasure, updates the score if so, and triggers game over conditions when the target score is met. It handles path navigation, collision detection with treasure, score tracking, and game state transitions. | def move_opponent(self):
# Get next position in path
try:
next_pos = self.opponent_path.pop(0)
except IndexError:
return
# Move opponent to next position
self.draw_piece(self.opponent, next_pos, self.show_path)
# Check for collision with treasure
... |
def draw_piece(self, piece, pos, stamp=False):
piece.goto(helpers.screen_coordinates_from_grid_position(pos, self.board_dimensions))
if stamp:
piece.stamp()
def update_score_display(self):
self.score_turtle.clear()
self.score_turtle.goto(0, -350)
self.score_turtle.wri... | The code moves the player in the specified direction if the new position is within bounds and not an obstacle. It checks for treasure collision, updates the score, and triggers game over logic if the target score is met. If not, it resets the game after a delay. | def move_player(self):
# Calculate potential new position
if self.player_direction != "stop":
new_pos = (self.player_pos[0] + config.offset_parameter[self.player_direction][0],
self.player_pos[1] + config.offset_parameter[self.player_direction][1])
# if ne... |
def init_nodes(self, n_inputs, n_outputs, n_hidden):
for i in range(n_inputs):
id = -i-1
self.nodes[id] = Node(id, NodeType.INPUT, self.random_activation(), layer=0,device=self.device)
for i in range(n_outputs):
id = -n_inputs-i-1
self.nodes[id] = Node(id,... | The code initializes a neural network genome by setting up input, hidden, and output nodes, creating connections between them based on a given probability, and organizing nodes into layers. It prepares the network structure for evolutionary algorithms or training processes. | def init_genome(self, n_inputs, n_hidden, n_outputs, init_connection_prob):
self.nodes = {}
self.connections = {}
self.init_nodes(n_inputs, n_outputs, n_hidden)
self.init_connections(init_connection_prob)
self.update_node_layers() |
def random_uniform(self, minval=-1, maxval=1):
return np.random.uniform(minval, maxval)
def add_node(self):
c = self.random_connection()
if not c.enabled:
return
c.enabled = False
new_node = Node(max([n for n in self.nodes.keys()])+1, NodeType.HIDDEN, self.random_acti... | The code performs structural and parameter mutations on a neural network with probabilistic selection. It adds/removes nodes, adds/disables connections, mutates activation functions, and adjusts weights based on given probabilities, then updates node layers to reflect changes. | def mutate(self,
add_node = 0.8,
add_connection = 0.8,
remove_node = 0.1,
disable_connection = 0.1,
mutate_activations = .1,
mutate_weights = 0.01):
if self.random_uniform(0.0,1.0) < add_node:
self.add_node()
i... |
def drawCanvasForSLAM(self):
self.figure = plt.Figure(figsize = (5.5, 5.5), facecolor = '#12232E') #width 550, heigth = 550
self.canvas = FigureCanvasTkAgg(self.figure, master=self.root)
self.canvas.get_tk_widget().place(x = 10, y = 10) #put figure on canvas
self.ax = self.figure.gca() #... | The main task of the code is to draw and update a graphical user interface (GUI) for a system, likely related to robotics or control systems. It initializes interface elements such as angle labels, PWM indicators, gyro labels, a SLAM canvas, reference angles, buttons, and triggers an update to render the interface. The... | def drawInterface(self):
drawAngleLabel(self.root)
drawPWMIndicator(self.root)
drawGyroLabel(self.root)
self.drawCanvasForSLAM()
self.drawRefAngle()
self.drawButtons()
self.updateInterface() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.