dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def GetWeightedEdgeOneHot(self, sum_adj):
device = sum_adj.device
N = sum_adj.shape[0]
# print(N)
# print(sum_adj.shape)
rows, cols = torch.meshgrid(torch.arange(N), torch.arange(N), indexing='ij')
rows, cols = rows.flatten(), cols.flatten()
flat_weights = sum_adj... | The code performs a forward pass through a graph neural network, processing node features with convolutional layers, generating an adjacency matrix via Gumbel softmax, and using it in an encoder-decoder framework to predict outputs. It integrates graph structure learning with temporal sequence modeling for tasks like g... | def forward(self, label, inputs, node_feas, batch_graph, temp, gumbel_soft, labels=None, batches_seen=None):
"""
:param inputs: shape (seq_len, batch_size, num_sensor * input_dim)
:param labels: shape (horizon, batch_size, num_sensor * output)
:param batches_seen: batches seen till now
... |
def newImage(canvas):
imageName= filedialog.askopenfilename()
filetype=""
try: filetype=imghdr.what(imageName)
except:
messagebox.showinfo(title="Image File",message="Choose an Image File!" , parent=canvas.data.mainWindow)
# restrict filetypes to .jpg, .bmp, etc.
if filetype in ['jpe... | This code initializes a Tkinter menu system for a GUI application, creating a "File" menu with options like New, Save, Save As, and Batch Process. Each menu item is linked to specific functions that operate on a canvas, enabling user interaction for tasks such as image creation, saving, and batch processing. | def menuInit(root, canvas):
menubar=tk.Menu(root)
filemenu=tk.Menu(menubar,tearoff=0)
filemenu.add_command(label="New", command=lambda:newImage(canvas))
filemenu.add_separator()
filemenu.add_command(label="Save", command=lambda:save(canvas))
filemenu.add_separator()... |
def newImage(self):
self.imageName= filedialog.askopenfilename()
filetype=""
try: filetype=imghdr.what(self.imageName)
except:
messagebox.showinfo(title="Image File",message="Choose an Image File!" , parent=self.master)
# restrict filetypes to .jpg, .bmp, etc.
... | This code initializes a menu bar in a Tkinter application, creating 'File' and 'Skin' menus. The 'File' menu includes commands for new, save, and save-as actions, while the 'Skin' menu dynamically lists available themes, allowing users to apply different styles via lambda and partial functions. The menubar is then conf... | def menuInit(self):
menubar=tk.Menu(self.master)
filemenu=tk.Menu(menubar,tearoff=0)
filemenu.add_command(label="New", command=lambda :self.newImage())
filemenu.add_separator()
filemenu.add_command(label="Save", command=lambda:self.save())
filemenu.add_separator()
... |
def newImage(self):
self.imageName= filedialog.askopenfilename()
filetype=""
try: filetype=imghdr.what(self.imageName)
except:
messagebox.showinfo(title="Image File",message="Choose an Image File!" , parent=self.master)
# restrict filetypes to .jpg, .bmp, etc.
... | This code creates a top frame with six icon-based buttons using Tkinter. Each button is styled uniformly, positioned in a grid layout, and linked to specific commands like opening files, saving, displaying a camera, and accessing help/web/buy features. Images are loaded from the 'icons' directory, and buttons retain re... | def topFrame(self):
openimg=ImageTk.PhotoImage(file = r"icons/file.png")
saveimg=ImageTk.PhotoImage(file = r"icons/save.png")
camimg=ImageTk.PhotoImage(file = r"icons/cam.png")
helpimg=ImageTk.PhotoImage(file = r"icons/help.png")
webimg=ImageTk.PhotoImage(file = r"icons/web.pn... |
def startCrop(self,event):
if self.croprect is not None:
self.canvas.delete(self.croprect)
self.startCropX=0
self.startCropY=0
self.tempCropX=0
self.tempCropY=0
self.endCropX=0
self.endCropY=0
self.startCropX=event.x
self.startCropY=event.y... | The code defines a `crop` method that enables user interaction to draw a cropping rectangle on an image displayed in a canvas. It shows a message instructing the user to draw the rectangle and press Enter. If an image is loaded, it binds mouse events to methods for starting, drawing, and ending the rectangle selection,... | def crop(self):
self.croprect = None
tk.messagebox.showinfo(title="Crop",message="Draw cropping rectangle and press Enter", parent=self.master)
if self.image!=None:
self.canvas.bind("<ButtonPress-1>",lambda event: self.startCrop(event))
self.canvas.bind("<B1-Motion>",lambda event: se... |
def switch(self,frame,tab):
frame.tkraise()
if tab=='open':
self.settingstab='open'
self.settings(tab)
elif tab=='hist':
self.settingstab='hist'
self.settings(tab)
elif tab=='apply':
self.settingstab='apply'
elif tab=='cancel':
self.setting... | This code creates a GUI layout for an image editing application, setting up a right panel with a histogram display, tabbed interface (Crop/Edit/Print), and configurable sliders for brightness, contrast, saturation, sharpen, and color channel adjustments. It organizes UI elements using grid layouts and binds interaction... | def rightFrame(self):
self.right_frame.grid_rowconfigure(0,weight=0)
self.right_frame.grid_rowconfigure(1,weight=0)
self.right_frame.grid_rowconfigure(2,weight=1)
self.right_frame.grid_columnconfigure(0,weight=1)
self.right_frame.grid_columnconfigure(0,weight=1)
ttk.Label(self.... |
def set_app_style(self):
self.style = ThemedStyle(self.master)
self.style.set_theme('black')
# self.style.theme_settings('equilux', {"TNotebook.Tab": {"configure": {"padding": [30, 15]}}})
# self.style.theme_settings('equilux', {'TButton': {"configure": {"padding": [30, 15]}}})
self.style.map("T... | The code initializes a GUI-based image editor application by setting up a window with a specific layout. It configures screen dimensions, creates multiple frames (top, right, center, left, bottom) using grid layout, and sets their positions and resizing behaviors. The `__init__` method also initializes attributes for i... | def __init__(self, master):
self.master=master
self.canvaswidth=None
self.canvasheight=None
self.image=None
self.folderImages=[]
self.originalImage=None
self.imageSize=None
self.imageForTk=None
self.histCanvasHeight=100
self.histCanvasWidth=256
#=====================... |
def get_data():
data = {}
for field in ListenField:
data[field] = {
TimeFrame.LAST_WEEK: get_last_week_top_x(get_listen_history(), field),
TimeFrame.ALL_TIME: get_all_time_top_x(get_listen_history(), field)
}
return data
def get_email_subject(last_week_top_artists):
... | The main task of the code is to generate an email by retrieving data, then constructing a dictionary with three components: a subject line, HTML content, and plain text content, each derived from the data. The function returns this structured email data for further use. | def generate_email():
data = get_data()
return {
"subject": get_email_subject(data[ListenField.ARTIST][TimeFrame.LAST_WEEK]),
"html_content": get_html_content(data),
"text_content": get_text_content(data)
} |
def cout(msg: str):
if len(__log_path) > 0:
print(f"{now_to_str()} {msg}", file = __log_file)
__log_file.flush()
print(msg, file = sys.stdout)
def cerr(msg: str):
if len(__log_path) > 0:
print(f"{now_to_str()} {msg}", file = __log_file)
__log_file.flush()
print(msg, file ... | This function uploads a zip file to Google Drive using the Google Drive API, checking status via flag files (.ready, .uploading, .uploaded). It ensures the file is not already uploaded or being processed, sets the uploading flag, uploads the file with error handling, and updates the status to uploaded upon success. | def upload_to_google_drive(path: str) -> bool:
""" Upload the zip file to Google Drive """
zp = os.path.abspath(path)
zn = os.path.basename(path)
if not os.path.isfile(f"{zp}.ready"):
cout(f"{zn} is not ready")
return False
if os.path.isfile(f"{zp}.uploaded"):
cout(f"{zn} is... |
def finish_files(save_path: str) -> None:
"""" Search for any unfinished tmp files and rename them """
for f in glob.glob(os.path.join(save_path,
"tweets-"
# 4 digits year, 2 digits months and day
"20[0-9... | The code manages file operations for uploading and cleaning tweet data. It checks for unfinished files, zips eligible files, uploads them to Google Drive, and handles retries or deletions based on age. It cleans orphaned flag files and removes empty files. On Sundays, it sends a weekly digest email if configured. | def worker(save_path: str) -> None:
""" Check all files """
# Check if any tmp file is unfinished
finish_files(save_path)
# Find files to be zipped
zip_tweets(save_path)
files_uploaded = []
files_cleaned = []
# Find files to be uploaded
# Find all zips
for f in sorted(glob.glo... |
def reset_stream(*args):
for arg in args:
arg.truncate(0)
arg.seek(0)
def operate(dataset, loc=0):
return_code = 0
try:
while loc < len(dataset) and dataset[loc] != 99:
raw_value = dataset[loc]
operand = raw_value % 100
param_modes = [(raw_value //... | The code simulates a robot painting panels on a grid. It starts at (0,0) facing north, reads panel colors, processes data to determine new colors and directions, updates the grid, and moves the robot accordingly. The loop continues until a termination condition is met, then returns the final painted panels state. | def paint(initial_panels):
sys.stdin = new_stdin
sys.stdout = new_stdout
panels_painted = initial_panels
current_coords = (0, 0)
current_heading = 0
loc = 0
new_data = data.copy()
while 1:
reset_stream(new_stdin, new_stdout)
if current_coords in panels_painted:
... |
def __find_user_pool_from_name(cognito_client, cognito_params):
next_token = ''
done = False
cur_user_pool = None
while not done:
# check to see if the user pool already exists
resp = cognito_client.list_user_pools(
MaxResults=20 # if less items exist than specified, then wi... | The function deploys or updates an AWS Cognito User Pool based on provided parameters. It checks if a user pool with the specified name exists; if so, it updates it, otherwise creates a new one. After ensuring the user pool is configured, it retrieves and returns the user pool's Amazon Resource Name (ARN) for further A... | def deploy_cognito_userpool(cognito_params: CognitoParams):
cognito_client = session.client('cognito-idp')
logging('Deploying Cognito user pool...')
# after specifying attributes on the actual instance of the object, use the static properties of the class
# to convert these into actual dictionary valu... |
def __get_api_from_name(gateway_client, gateway_params):
# retrieve the existing apis and scan through to get the current api being developed on
cur_api = None
existing_apis = gateway_client.get_rest_apis()
for api in existing_apis['items']:
if api['name'] == gateway_params.api_name:
... | The main task of the code is to deploy or update an AWS API Gateway using provided parameters. It checks for an existing API, creates or updates it, manages resources and integrations, and finally deploys the API, handling errors during deployment. | def deploy_rest_api(gateway_params):
logging(f'Deploying API Gateway...')
gateway_client = session.client('apigateway')
cur_api = __get_api_from_name(gateway_client, gateway_params)
if not cur_api:
__create_api_gateway(gateway_client, gateway_params)
else:
__update_api_gateway(gat... |
def quiet(self, value:bool):
if value:
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
tf.get_logger().setLevel('ERROR')
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
absl.logging.set_verbosity(absl.... | This code initializes a class for CAPTCHA processing by setting up configuration parameters, retrieving training data paths, and establishing character-to-integer mappings for text recognition. It configures output handling, loads model weights, and prepares input dimensions and character sets based on the specified CA... | def __init__(self, captcha_type:CaptchaType, weights_only=True, quiet_out=False):
self.NULL_OUT = open(os.devnull, 'w')
self.STD_OUT = sys.stdout
self.quiet(quiet_out)
self.captcha_type = captcha_type
self.weights_only = weights_only
self.quiet_out = quiet_out
sel... |
def load_prediction_model(self):
if self.weights_only:
model = self.build_model()
model.load_weights(self.weights_path)
else:
model = keras.models.load_model(self.weights_path)
sum = model.summary()
print(sum)
prediction_model = keras.models... | The code validates a prediction model's accuracy on a test dataset by comparing predicted labels with actual labels from image filenames, calculating the accuracy percentage, and measuring the validation time. | def validate_model(self):
start = time.time()
matched = 0
prediction_model = self.load_prediction_model()
pred_img_path_list = self.get_image_files(self.captcha_type, train=False)
for pred_img_path in pred_img_path_list:
pred = self.predict(pred_img_path, prediction_... |
def split_dataset(self, batch_size=16, train_size=0.9, shuffle=True):
# 1. Get the total size of the dataset
image_width, image_height, max_length, characters, labels, train_img_path_list = self.get_train_info()
images = np.array(train_img_path_list)
labels = np.array(labels)
siz... | The code trains a machine learning model using a dataset split into training and validation sets, with optional early stopping based on validation loss. It builds the model, trains it for a specified number of epochs, and saves the model weights or the full model if enabled. | def train_model(self, epochs=100, earlystopping=True, early_stopping_patience:int=8, save_weights:bool=True, save_model:bool=False):
train_dataset, validation_dataset = self.split_dataset(batch_size=16, train_size=0.9, shuffle=True)
model = self.build_model()
if earlystopping == True:
... |
def create_directory(workdir, remove):
if (os.path.exists(workdir))&remove:
shutil.rmtree(workdir)
try:
# Create target Directory
os.mkdir(workdir)
except FileExistsError:
print("Directory " , workdir , " already exists")
return
def extract_initial_moments_maj_locus(i, list_... | This function simulates a population genetics model for a major locus under background selection, running one replicate. It initializes parameters, extracts initial population moments, and executes a continuous-time model to track allele frequency dynamics. Key tasks include directory setup, parameter configuration, an... | def run_maj_locus_inf_bg_per_replicate(i, parameters, list_files, subpath_slim, z, dz, Nz, workdir, Nstart, Nsim):
workdir_current = workdir + '/simulation_%i'%i
create_directory(workdir_current, False)
a, r, K, Kslim, theta, eta, g1, g2, m1, m2, dt, time_factor = parameters
#n1ainitial, n2ainitial, n1A... |
def ip(self, A, B):
result = np.trace(A@B.transpose())/self.N
return result
def ip_list(self, List_of_Matrices):
result = [[self.ip(i, j) for i in List_of_Matrices]
for j in List_of_Matrices]
return result
def alpha_sqr(self, A, AX, option='sample'):
if option =... | The function `fit_with_projection_method` performs a projection-based approximation of a new matrix `S_new` by combining a baseline matrix `S1` (self.S_sample) and additional matrices in `S_list`. It calculates inner products (`mu`, `M`, `alpha`) to solve for coefficients (`params`) via linear inversion. These coeffici... | def fit_with_projection_method(self, S_list, option='s'):
# We take S0, sample cov as the baseline, we add other matrices as targets
S1 = self.S_sample
mu = [self.ip(S1, self.I)]
mu = mu + [self.ip(x, self.I) for x in S_list]
dS1 = S1 - mu[0]*self.I
# dS2 = S2 - mu2*self.... |
def find_smallest_threshold_for_pd(self, eig_id=np.array([0]), verbose=False):
"""
Notice that here we use linear tau_method to find the minimum threshold level
"""
parameter_range = np.linspace( self.cv_init_value , int(np.floor(1/self.scaling_factor)) + 1, 100)
if verbose:
... | The code's main task is to fit an adaptive correlation model by adjusting the threshold method, estimating parameters via cross-validation, computing a thresholded correlation matrix (R_est), and deriving a scaled covariance matrix (S_est) using sample standard deviations. It returns R_est, S_est, and the optimized par... | def auto_fit(self, threshold_method = None):
if threshold_method is not None: # change self.threshold_method
self.threshold_method = threshold_method
b = self.find_smallest_threshold_for_pd()
params = self.params_by_cv('pd', b)
R_est = self.fit_adaptive_corr_threshold(params... |
def _get_segment_table(reset_table=False):
global _SEQUENCE_TABLE
if not _SEQUENCE_TABLE or reset_table:
try:
_get_ddb().create_table(
AttributeDefinitions=[
{
'AttributeName': 'SegmentId',
'AttributeType': '... | This function inserts a new route segment into a user's route by generating a unique ID for the segment, storing it in a database, updating the route's segment list with the new ID at the specified index, and persisting the updated list in the database. | def insert_route_segment(user_id, route, index, segment):
"""
Add a new segment to the given route
@param user_id: user id of the passed route
@param route: id of the route
@param index: index of the segment in route
@param segment: the segment to insert
"""
new_segment_id = str(uuid.uui... |
def _get_segment_table(reset_table=False):
global _SEQUENCE_TABLE
if not _SEQUENCE_TABLE or reset_table:
try:
_get_ddb().create_table(
AttributeDefinitions=[
{
'AttributeName': 'SegmentId',
'AttributeType': '... | The main task of the code is to replace a specific segment in a user's route by inserting a new segment and removing the old one. It updates the route's segment list in the database, stores the new segment, and deletes the outdated segment from storage. | def update_route_segment(user_id, route, index, segment):
"""
Update a segment in the given route
@param user_id: user id of the passed route
@param route: id of the route
@param index: index of the segment in route
@param segment: the segment to insert
"""
new_segment_id = str(uuid.uuid... |
def get_route_segment_ids(user_id, route):
"""
Get an ordered list of segment ids pertaining to the passed route for the given user.
@param user_id: user id of the passed route
@param route: id of the route
@return: ordered list of segment ids
"""
response = _get_route_table().get_item(
... | The function deletes a specific segment from a user's route by removing the segment at the given index from the route's segment list, deleting the segment from the database, and updating the route's segment list in the route table. It takes a user ID, route ID, and segment index as inputs, retrieves the segment list, r... | def delete_route_segment(user_id, route, index):
"""
Delete a segment from the given route
@param user_id: user id of the passed route
@param route: id of the route
@param index: index of the segment in route
"""
segment_list = get_route_segment_ids(user_id, route)
segment_id_to_remove =... |
def setup_drop_buttons(self, board):
for x in range(len(board[0])):
temp_button = tk.Button(self.drop_canvas, height = BUTTON_HEIGHT, width = BUTTON_WIDTH,
command = partial(self.pressed_drop_button, x), cursor = "hand2")
temp_button.grid(row = 0, colu... | This code initializes a graphical user interface (GUI) for a Connect 4 game using Tkinter. It sets up the main window, turn labels, canvases for drop buttons and the game board, and binds interactions. The GUI components are structured to display the game state, handle player turns, and enable user input through button... | def __init__(self, game):
self.game = game
self.buttons = [[] for i in range(len(self.game.get_board()[0]))]
self.drop_buttons = []
self.main_window = tk.Tk()
self.main_window.title("Connect 4")
self.default_font = font.Font(family = "Helvetica", size = 20, weight = "bold... |
def make_df(reviews_folder_path):
f = open(reviews_folder_path + 'shuffled_reviews.txt')
row = []
for x in f:
grp = re.match(r'(.*)_(.*)\s=\s(.*)', x)
review_no = grp.group(1)
arxivId = str(grp.group(2))
review = str(grp.group(3))
row.append([review_no, arxivId, revie... | The main task of the code is to generate and save cosine and Jaccard similarity plots for specified paper IDs. It processes review data from a folder, converts it into a string-typed DataFrame, then visualizes pairwise distances using two distinct metrics, storing the resulting plots in a designated output directory. | def Plot_Distances(paper_ids, reviews_folder_path, plots_path):
make_df(reviews_folder_path)
df = pd.read_csv(f'{reviews_folder_path}shuffled_reviews.csv')
df = df.astype("string")
cosine_plot(df, paper_ids, plots_path)
jaccard_plot(df, paper_ids, plots_path) |
def db_count(database):
'''
returns a count for the amount of entries in the passed table
'''
conn, cur = db_setup()
query = "SELECT * FROM " + database
cur.execute(query)
db_total = len(cur.fetchall())
return db_total
def top_from_songs():
'''
Gets a list of genres and the corre... | The main task of the code is to check if the "Music" table contains exactly 100 entries. If true, it retrieves top song and album data, formats them as percentage-based entries, and appends the results to a text file ("calc.txt") with structured headings and separators. The output includes "Top 50 songs" and "Top 50 al... | def write_to_file():
'''
Checks to see if Music table has 100 entries. If True, gets list of genres and corresponding
numbers as a list of tuples. Takes the tuples, formats and writes to a text file.
'''
if db_count('Music') == 100:
song_data = top_from_songs()
album_data = top_fr... |
def db_count(database):
'''
returns a count for the amount of entries in the passed table
'''
conn, cur = db_setup()
query = "SELECT * FROM " + database
cur.execute(query)
db_total = len(cur.fetchall())
return db_total
def top_from_songs():
'''
Gets a list of genres and the corre... | The main task of the code is to visualize the distribution of music genres in the iTunes Top 50 songs and albums using pie charts. It extracts genre data from database queries, maps genres to colors via matplotlib's Paired colormap, creates two separate pie charts with percentage labels, adds side legends for genre nam... | def visualize():
'''
Takes the tuples of album data and song data and breaks them into lists. Chooses a
distribution of colors from the Paired colorset from matplotlib colormaps, displays
the pie chart, and adds a legend to the side.
'''
if db_count('Music') == 100:
x_song = []
... |
def db_count(database):
'''
returns a count for the amount of entries in the passed table
'''
conn, cur = db_setup()
query = "SELECT * FROM " + database
cur.execute(query)
db_total = len(cur.fetchall())
return db_total
def top_from_songs():
'''
Gets a list of genres and the corre... | The function checks if the Music table has 100 entries. If true, it retrieves top songs and albums data, then writes them to 'calc.txt' in formatted lines showing percentages and names, appending results for both song and album data. | def write_to_file():
'''
Checks to see if Music table has 100 entries. If True, gets list of genres and corresponding
numbers as a list of tuples. Takes the tuples, formats and writes to a text file.
'''
if db_count('Music') == 100:
song_data = top_from_songs()
album_data = top_fr... |
def db_count(database):
'''
returns a count for the amount of entries in the passed table
'''
conn, cur = db_setup()
query = "SELECT * FROM " + database
cur.execute(query)
db_total = len(cur.fetchall())
return db_total
def top_from_songs():
'''
Gets a list of genres and the corre... | The code generates pie charts visualizing genre distributions for iTunes' top 50 songs and albums. It retrieves data from a database, splits tuples into lists, applies a Paired colormap for colors, creates two separate pie charts with percentages and legends, and titles each chart to distinguish song vs. album genre di... | def visualize():
'''
Takes the tuples of album data and song data and breaks them into lists. Chooses a
distribution of colors from the Paired colorset from matplotlib colormaps, displays
the pie chart, and adds a legend to the side.
'''
if db_count('Music') == 100:
x_song = []
... |
def create_table():
conn,c=set_conn()
c.execute('''CREATE TABLE IF NOT EXISTS movies(id INT PRIMARY KEY, title TEXT, run_time TEXT, genre TEXT,rating REAL)''')
conn.commit()
conn.close()
return True
def access_api():
movies=[]
for url in URLS:
soup=api_bs_setup(url)
res=soup.... | The main task of the code is to execute a sequence of operations: create a database table, access an API to retrieve data, generate a Plotly visualization, and write the results to a file. This workflow combines data storage, external data fetching, visualization, and output persistence in a structured manner. | def main():
create_table()
access_api()
make_plotly_graphic()
write_to_file() |
def db_setup():
'''
Sets up connection to the entertainment database
'''
connection = sqlite3.connect('entertainment.db')
cursor = connection.cursor()
return connection, cursor
def create_table():
'''
Creates the Music table in entertainment database
'''
conn, cur = db_setup()
... | The main task of the code is to initialize a database, create a table, populate it with incremental data, export the data to a file, and generate a visualization. The sequence ensures data setup, storage, and analysis through structured steps. | def main():
db_setup()
create_table()
db_fill_incremented()
write_to_file()
visualize() |
def __intervalConstructor(self, interval):
self.__startHour = interval.getLow()
self.__endHour = interval.getHigh()
def __twelveHourConstructor(self, start, end):
self.__startHour = self.__parse12(start, True)
self.__endHour = self.__parse12(end, False)
def __twentyFourHourConstructor(se... | This code initializes a time interval object by determining whether to use a single interval string or two time strings. It checks if the inputs contain AM/PM indicators ('a'/'p') to apply the 12-hour format constructor or the 24-hour format constructor, ensuring proper time interval setup based on input format. | def __init__(self, *args):
if len(args) == 1:
self.__intervalConstructor(args[0])
else:
start = args[0].lower()
end = args[1].lower()
if ("a" in start or "p" in start) and ("a" in end or "p" in end):
self.__twelveHourConstructor(start, end)... |
def _conv_bn_activation(self, bottom, filters, kernel_size, strides, activation=tf.nn.relu):
conv = tf.layers.conv2d(
inputs=bottom,
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding='same',
data_format=self.data_format
... | This code constructs a DLA (Deeply Aggregated Network) model with multi-scale feature extraction and upsampling. It processes input images through convolutional blocks with batch normalization, generates DLA stages with residual connections, and combines features across scales using upsampling and fusion operations to ... | def build_model(self, images):
with tf.variable_scope('backone'):
conv = self._conv_bn_activation(
bottom=images,
filters=16,
kernel_size=7,
strides=1,
)
conv = self._conv_bn_activation(
bottom=co... |
def get_list_of_authors(self):
soup = utils.make_a_soup(self.home_url)
aside_tag = soup.find('aside', id='authors')
author_li= aside_tag.find('ul').findAll('li')
author_link_dict = dict()
for li in author_li:
a_tag = li.find('a',href=True)
author_link_dic... | The main task of the code is to scrape and organize verses from a website by iterating through author links, creating a 'kalanjiyam' directory, fetching each author's content links, and extracting verses from those links for storage. | def scrape_kalanjiyam(self):
author_links = self.get_list_of_authors()
kalanjiyam_folder = current_path / 'kalanjiyam'
if not Path.is_dir(kalanjiyam_folder):
Path.mkdir(kalanjiyam_folder)
for author, link in author_links.items():
self.content_links = di... |
def get_sub_atom_idx_to_name_dict(traj, PARAM):
"""
return substrate atom index to name dict
(atom idx: 0 indexing)
"""
topology=traj.top
sub_atom_idx_to_name_dict={}
sub_atoms_indices=list(traj.top.atom_indices(':'+PARAM['SUBSTRATE_NAME']+'@O*,N*,C*'))
for a_idx in sub_atoms_indic... | This function identifies amino acid residues near a substrate in MD data by analyzing atomic distances and residue properties. It returns lists of nearby residue indices, names, atom details, and suggested amino acid types with lengths, based on hydrogen bonding potential and distance thresholds. | def loop_sub_near_aa_to_suggest_aa(traj, PARAM, res_idx_to_aa_sub_atom_data_dict):
"""
*finds residues for suggestion based on distance and general properties of
residue/substrate_atom given the filtered MD frame data.
Returns 4 lists:
1. list of residue index of residues found near substr... |
def _update_position(self, order_event: OrderEvent):
_sign = 1 if order_event.side == Side.BUY else -1
self._position += _sign * order_event.last_filled_quantity
logging.info("Net position: {:.3f}".format(self._position))
def _is_complete(self, order_event: OrderEvent):
return (
... | This code handles order execution events by logging them, updating positions, and managing buy/sell orders. Upon completing a buy/sell order, it cancels the opposing order, creates a skewed limit order (adjusting price by ±0.1) to reduce risk, and resets live order tracking. The goal is to dynamically adjust trade posi... | def on_execution(self, order_event: OrderEvent):
logging.info("Received execution: {}".format(order_event))
self._update_position(order_event)
if order_event.side == Side.BUY:
if self._live_buy_order:
self._live_buy_order.last_order_event = order_event
... |
def deltaX(self, keyMapper, allObjects):
# TODO: if key press and unobstructed left or right, go left or right
# Will take STEP of +delta
dx = 0
if keyMapper["A"]:
dx = self._dx * -1
elif keyMapper["D"]:
dx = self._dx
if dx:
new_posi... | The main task of the code is to update the positions of sprites by calculating horizontal (deltaX) and vertical (deltaY) movement deltas based on input key states (keyMapper) and object interactions (allObjects), then applying these deltas to each sprite's position through their respective delta methods. | def update_position(self, allObjects: "list[RenderedObject]", keyMapper: "dict[str, bool]"):
deltaX = self.deltaX(keyMapper, allObjects)
deltaY = self.deltaY(keyMapper, allObjects)
for sprite in self.getSprites():
sprite.spriteDeltaX(deltaX)
sprite.spriteDeltaY(deltaY) |
def calc_mental_state(perspective, context):
""" Given speaker's perspective and the context,
compute a probability distribution over the referents
of how likely the speaker is to speak about each referent
p. 88 Equation 3.1 """
distribution = np.zeros(len(context))
for o in range(len(context)):... | The code generates a signal based on a speaker's mental state derived from context, language, and perspective. It selects a meaning and produces a signal, with pragmatic level determining production rules: level 0 uses a simple selection with noise, while level 1 applies probabilistic selection. Noise introduces occasi... | def produce(system, context):
""" Speaker produces a signal """
language = languages[system[0]]
perspective = perspectives[system[1]]
pragmatic_lvl = pragmatic_levels[system[2]]
mental_state = calc_mental_state(perspective, context)
meaning = sample(mental_state)
""" Production is done ... |
def calc_mental_state(perspective, context):
distribution = np.zeros(len(context))
for o in range(len(context)):
distribution[o] = log(1 - abs(perspective - context[o]))
return utilities.normalize_logprobs(distribution)
def sample(posterior):
return meanings[utilities.log_roulette_wheel(posterio... | The code generates a signal based on a system's language and perspective, calculating a mental state from context, sampling meaning, and selecting a signal via a probabilistic distribution. A small noise factor introduces randomness by occasionally replacing the chosen signal with an alternative. The function returns t... | def produce(system, context):
language = system[0]
perspective = system[1]
mental_state = calc_mental_state(perspective, context)
meaning = sample(mental_state)
# choose the best signal given the pragmatically-derived probability distribution
signal = signals[utilities.log_roulette_wheel(sp... |
def calc_mental_state(perspective, context):
""" Given speaker's perspective and the context,
compute a probability distribution over the referents
of how likely the speaker is to speak about each referent
p. 88 Equation 3.1 """
distribution = np.zeros(len(context))
for o in range(len(context)):... | This function updates the posterior probabilities of each hypothesis (lexicon/perspective pair) by calculating the likelihood of the observed signal under each hypothesis, considering the context and pragmatic level. It computes reference distributions, applies level-specific learning functions (level-1 or level-2), ma... | def update_posterior(posterior, signal, context):
""" Update the posterior probabilities the learner has assigned to
each lexicon/perspective pair based on the observed signal
and context """
new_posterior = np.zeros(len(posterior))
for i in range(len(posterior)): # for each hypothesis
langu... |
def get_neighbours(surfname):
"""return neighbours from surface filename"""
surf=io_mesh.load_mesh_geometry(surfname)
neighbours = get_neighbours_from_tris(surf['faces'])
return neighbours
def ordered_new_neighbours(patch, neighbourhood):
""" for a vertex in a hexagonal patch, find the neighbours no... | The code generates 19-vertex ordered windows for each vertex in a surface mesh, with a central vertex, inner ring of 5 nearest neighbors, and outer ring of 12 more distant neighbors. It arranges these in a specific topology mirroring 2D plane window patterns, returning a matrix where each row contains the ordered indic... | def get_windows(surfname):
"""generate indices of 19 ordered windows for each vertex in surface
Central vertex is at position window[9] i.e. the middle of the window
Either side and moving outwards for 3 steps are the nearest neighbours (5 neighbours have one neighbour repeated twice)
Be... |
def write_gifti(surf_mesh, coords, faces):
coord_array = nb.gifti.GiftiDataArray(data=coords,
intent=nb.nifti1.intent_codes[
'NIFTI_INTENT_POINTSET'])
face_array = nb.gifti.GiftiDataArray(data=faces,
... | This function saves mesh geometry data from a dictionary to a file, selecting the appropriate format based on the filename's extension. It handles Freesurfer (.orig, .pial, etc.), GIFTI (.gii), VTK (.vtk), PLY (.ply), and OBJ (.obj) formats. The function writes coordinates and faces from the dictionary, optionally incl... | def save_mesh_geometry(fname,surf_dict):
# if input is a filename, try to load it with nibabel
if isinstance(fname, str) and isinstance(surf_dict,dict):
if (fname.endswith('orig') or fname.endswith('pial') or
fname.endswith('white') or fname.endswith('sphere') or
fname.en... |
def get_spaces(line: str) -> int:
if m := re.search(r'^(\s+)', line):
return len(m.group(1))
return 0
def make_nodes(path: str, parent: Root | Node, delimiter: str) -> Node:
parts = path.split()
current: Root | Node = parent
for number, elem in enumerate(parts):
child = check_child(e... | The function constructs a hierarchical tree structure from a configuration list, parsing sections based on indentation levels and delimiters. It processes lines to build nodes, manages nested sections, handles special symbols, and applies heuristics for analysis if enabled. The tree includes metadata like version, stub... | def construct_tree(
config: list[str],
*,
delimiter: str = '^',
is_heuristics: bool = False,
is_base_heuristics: bool = False,
is_crop: bool = False,
is_promisc: bool = False,
) -> Optional[Root]:
current: Root | Node = Root(
name='root',
version='',
delimiter=del... |
def make_default_root(delimiter: str) -> Root:
return Root(
name='root',
version='',
delimiter=delimiter,
path='',
children=[],
heuristics=[],
stubs=[],
begin=0,
end=0,
is_accessible=True,
)
def validate_config(data: list[str]) -> b... | This function parses structured text data into a hierarchical tree structure, handling indentation levels, special blocks (like ^C), and applying validation/heuristics based on settings. It constructs nodes, manages nesting via indentation, validates config formats, and returns the root node or None if invalid. | def construct_tree_second(data: list[str], *, settings: Optional[TreeSettings] = None) -> Optional[Root]:
if not settings:
settings = DEFAULT_SETTINGS
root = make_default_root(settings.delimiter)
current_node: Root | Node = root
bom_symbol = '\ufeff'
prev_line = ''
c_block_buf = ''
... |
def create_title(self) -> QtWidgets.QLabel:
'''
Create 'Draw Chaotic Map' title widget.
:return: QLabel title set to 'Draw Chaotic Map'
'''
widget = QtWidgets.QLabel('Draw Chaotic Map')
font = widget.font()
font.setPointSize(30)
widget.setFont(font)
... | The main task of the code is to initialize a GUI window for visualizing chaotic maps. It sets up UI components including a dropdown to select maps, labeled text boxes for parameters (a, b, c, d, x0, y0), sub-text boxes for simulation ranges (xmin, xmax, etc.), and a plot widget. The layout is configured, and an initial... | def __init__(self, *args, **kwargs):
'''
Initialize the main window.
:return: None
'''
super(MainWindow, self).__init__(*args, **kwargs)
self.default_maps = chaotic_maps.default_maps
# Set initial map to TinkerBell Map.
self.selected_map = self.default_ma... |
def matc(M):
evs = np.linalg.eigvals(M).real
Minv = np.linalg.inv(M)
print(np.all(evs > 0),' - positive definite')
print(np.format_float_scientific( max(evs)/min(evs) ),' - eigval ratio')
print('%f'%(np.linalg.norm(M)*np.linalg.norm(Minv)),' - condition (norm C x norm Cinv)')
print('')
def F(s,... | The function `getqs` computes unnormalized quantities (`qs`) and related matrices (Fisher matrix `Fm`, `MB`, `MA`) for a skeleton OQE algorithm using input data `Vis` and weighting `R`. It initializes matrices, calculates the Fisher matrix, derives optimal and inverse matrices, computes `qs` via `q_h`, and returns thes... | def getqs(Vis, R):
"""
Creates required matrices and runs the skeleton OQE over the given set of
data using weighting R, returning unnormalized qs to be normalized by the
pstats function.
"""
st = time.time()
s = len(Vis[0])
matc(R)
Fm = F(s, R) # Fisher matrix
MB = M_opt(Fm)
... |
def __run_query(self):
logger.info("Querying data...")
# if we are querying for specific billing group(s), we need to pass in account_ids
if self.query_parameters.get("billing_groups"):
account_ids = set(map(lambda a: a["id"], self.org_accounts))
self.query_parameters["a... | The code executes a query, manages file paths, downloads results to a CSV, generates summaries and reports, and delivers them if specified, ensuring directory structures are created as needed. | def do(self, existing_file=None):
query_results_output_file_local_path = existing_file
if not query_results_output_file_local_path:
query_execution_id = self.__run_query()
logger.debug(f"query_execution_id = '{query_execution_id}'")
output_file_name = "query_result... |
def load_data():
'''
Function to load data from csv to dataframe
Inputs:
- None
Returns: three pandas dataframes
'''
zagat = pd.read_csv("zagat.csv", names=["resto_name", "city", "address"],
index_col=0)
fodors = pd.read_csv("fodors.csv", names=["resto_name... | The function `find_matches` trains a probabilistic model to identify matches between Zagat and Fodor restaurant datasets, using sample matched and unmatched data. It calculates tuple probabilities, assigns tuples based on thresholds (mu for false positives, lambda_ for false negatives), and applies the model to the ful... | def find_matches(mu, lambda_, block_on_city=False):
'''
Loads the zagat and fodor restaurant data. Train model on
sample unmatch and match datasets. Apply model to all the
zagat and fodor restaurant dataset.
Inputs:
- mu (float): maximum false positive rate
- lambda_ (float): maxim... |
def show_press(press, lastPressed):
global numH, numC, totalH, totalC, lo, hi, lastSelected, test
# lo = valid[0]
# hi = valid[1]
# lastSelected = -1
# ---------------------------------- IF IT IS HUMAN ---------------------------------
# print(local_isAI)
print("it is human\'s move")
... | The code implements a turn-based number selection game where players (human or AI) pick numbers from either end of a list to maximize their score. It reads input from a file, processes levels, and uses a minmax algorithm for AI decisions. The game updates scores and UI elements dynamically, allowing users to interact v... | def game():
global lastPressed, window, lo, hi, NumC, NumH, go
test.clear()
# --------------------------------------- LEVEL -------------------------------------------
while (1):
level = int(input("Choose a level among 1 to 10: "))
# delay(1)
if level >= 1 and level <= 10:
... |
def new_game_state(scores, index):
# Removes the selected score from the list and returns the score
score = scores.pop(index)
return score
def update_scores():
ai_score_label.config(text="AI score: " + str(aiTotalScore))
player1_score_label.config(text="Player 1 score: " + str(humanTotalScore1))
... | This function processes Player 2's turn in a game by updating scores based on selected indices, checking game state, and transitioning to AI's turn if the game continues. It handles input validation, updates UI elements, and determines the winner if the game ends. | def process_player2_turn():
global current_player, humanTotalScore2, humanTotalScore1, aiTotalScore
try:
chosen_index = int(player1_input_entry.get())
chosen_sub_index = int(player1_sub_input_entry.get())
player1_input_entry.delete(0, tk.END)
player1_sub_input_entry.delete(0, tk... |
def update_scores():
# Create separate labels for each player
p1_score_label.config(
text="Player 1: " + str(humanTotalScore1),
bg="#f9ca24",
fg="white",
font=("8514oem", 14, "bold"),
padx=10,
pady=15,
bd=1,
relief="solid"
)
p2_score_label.... | This function processes a player's selection of a subtraction score, updates human and AI scores accordingly, triggers game state updates, plays a sound effect, checks for game over conditions, and switches turns between players or to the AI. | def process_subtraction_selection(index):
global current_player, humanTotalScore1, humanTotalScore2, aiTotalScore, score_selected
if not selectedSub[index] and score_selected == True:
score_selected = False
chosen_sub_index = index
selectedSub[chosen_sub_index] = True
score_sub ... |
def player1_turn():
global current_player
current_player = "Player 1"
player_label.config(text="Current player: " + current_player)
hint_label.destroy()
def player2_turn():
global current_player
current_player = "Player 2"
hint_label.destroy()
player_label.config(text="Current player: " ... | The function `save_current_player` updates the current game player, removes setup buttons, and initiates the corresponding turn logic (Player 1, Player 2, or AI) based on the input `cur_player`. It sets the global `current_player`, triggers turn-specific actions, prints the current player, and generates score and subtr... | def save_current_player(cur_player):
# also check if difficulty is selected
global current_player, difficulty
if difficulty != "":
buttonFirstPlayer.destroy()
buttonSecondPlayer.destroy()
buttonAI.destroy()
select_current_player.destroy()
current_player = cur_player
... |
def _cifar10_preprocess_for_train(image, use_bfloat16, image_size=IMAGE_SIZE,
augment_name=None, randaug_mag=None,
randaug_layer=None):
'''Preprocesses the given image for evaluation.
Args:
image_bytes: `Tensor` representing an image binary of... | This function preprocesses an image tensor for training or evaluation, decoding JPEG bytes if needed. It applies model-specific training augmentations (like RandAugment) when is_training=True, or standard evaluation preprocessing otherwise. The output is a [0,255]-range image tensor, with optional bfloat16 conversion, ... | def preprocess_image(input_tensor,
is_training=False,
use_bfloat16=False,
image_size=IMAGE_SIZE,
is_image_bytes=True,
augment_name=None,
randaug_mag=None,
randaug_layer=None... |
def load_dataset():
data = {}
download_and_extract()
merge_folder = os.path.join(FLAGS.raw_data_dir, MERGE_DATA_FOLDER)
splits = ['train', 'test']
if FLAGS.task_name == 'svhn':
splits += ['extra']
for split in splits:
with tf.gfile.Open(
os.path.join(merge_folder, '{}_images.npy'.format(spli... | The main task of the code is to split and preprocess a dataset into training, development, and optional extra splits based on flags. It shuffles the data, reserves a development set (or uses test data if specified), validates data sizes for the 'svhn' task, and saves the processed data into TFRecords for machine learni... | def main(argv):
data = load_dataset()
np.random.seed(0)
data = shuffle_split(data, 'train')
if 'extra' in data:
data = shuffle_split(data, 'extra')
if FLAGS.task_name == 'svhn':
dev_size = 4000 # 7300
else:
assert False
data['dev'] = {}
if not FLAGS.full_train_data:
data['dev']['images']... |
def load_json(filename):
if tf.gfile.Exists(filename):
counts = None
try:
with tf.gfile.Open(filename) as inf:
counts = json.load(inf)
return (True, counts)
except:
tf.logging.info('having error loading {:s}, not exist'.format(
filename))
return (False, None)
def is_m... | The main task of the code is to process image data by computing probability thresholds, filtering images based on these thresholds, and generating statistics. It checks for pre-existing stats to avoid redundant work, calculates label-to-image mappings, and saves filtered results. The code handles distributed job tasks,... | def main(argv):
stats_dir = os.path.join(FLAGS.output_dir, 'stats')
stats_filename = os.path.join(stats_dir, 'stats_%.5d_%d.json' % (FLAGS.shard_id, FLAGS.task))
if load_json(stats_filename)[0]:
if is_master_job():
read_stats()
tf.logging.info('stats already finished, returning')
return
prelim... |
def standardise_phrase(self, phrase):
# Apostrophes (') should be ignored completely
new_phrase = re.sub("\'", "", phrase)
# Any other sequences of non-letter characters are also ignored,
# but split the name into separate words.
new_phrase = re.sub("\W", " ", new_phrase)
... | The code generates abbreviations by combining the first letter and two selected letters from a standardized, squashed version of the input phrase. It yields dictionaries containing the original phrase, abbreviation, and scores of the selected letters. The process involves standardizing, squashing the phrase, calculatin... | def generate_abbreviations_rows(self, original_phrase):
standardised_phrase = self.standardise_phrase(original_phrase)
squashed_phrase = self.squash_phrase(standardised_phrase)
phrase_scores = list(self.phrase_scores_per_letter(standardised_phrase))
phrase_length = len(squashed_... |
def ingest_file(self, input_filepath):
with open(input_filepath) as f:
for line in f:
yield line.strip()
def input_to_df_rows(self, input_phrases):
for p in input_phrases:
for r in self.generate_abbreviations_rows(p):
yield r
def input_as_dict(self... | The code processes an input file by splitting its data into two parts, converting them into DataFrames, and generating abbreviations through processing. It saves the results as a CSV file named with the input file's base name, then returns a confirmation message indicating the output location. | def run(self, input_filepath):
input_data = self.ingest_file(input_filepath)
input_1, input_2 = tee(input_data)
scores_df = pd.DataFrame(self.input_to_df_rows(input_1))
originals_df = pd.DataFrame(self.input_as_dict(input_2))
results = self.process_dfs(originals_df, s... |
def initialize_screen(stdscr: curses.window) -> Windows:
"""Initializes the screen."""
stdscr.nodelay(True)
curses.curs_set(False)
curses.init_pair(1, curses.COLOR_YELLOW, curses.COLOR_BLACK)
time_window = curses.newwin(3, 10, 0, 0)
time_window_x = time_window.getmaxyx()[1]
error_window = c... | The main task of the code is to initialize a curses-based screen and logger, then run an infinite loop that processes data using the provided receiver class and options. It sets up the user interface, logging system, and enters a continuous processing loop for handling incoming data or events. | def main(stdscr: curses.window, receiver_class, options: Options) -> None:
windows = initialize_screen(stdscr)
initialize_logger(windows)
loop_forever(windows, receiver_class, options) |
def highspeed_pid(hub, robot, cm, speed, start_angle):
motor = Motor('F')
motor.set_degrees_counted(0)
degrees_needed = abs(cm) * 360/17.8
prevError = 0
while abs(motor.get_degrees_counted())<=degrees_needed*0.10:
error = calDiff(hub.motion_sensor.get_yaw_angle(), start_angle)
#print... | The main task of the code is to control a robot's movement sequence, including high-speed navigation, precise turning, and flipper actuation to simulate dynamic motion. It executes a series of PID-controlled movements, directional turns, and flipper actions to guide the robot along a predefined path, potentially mimick... | def dino_run():
highspeed_pid(hub, robot, 129, 70, 0)
abs_turning(hub, robot, 40, 50)
for i in range (2):
flipper.run_for_degrees(60, 20)
flipper.run_for_degrees(-45, 20)
abs_turning(hub, robot, 33, 50)
pid(hub, robot, 2, 30, 33)
flipper.run_for_degrees(60, 60)
abs_turning(hu... |
def dump(hub, robot, flipper, flipperInit):
#abs_turning(hub, robot, 3, 30)
highspeed_pid(hub, robot, 74.25, 80, 3)
flipper.run_for_rotations(0.15, 50)
flipper.run_for_rotations(0.15, -50)
pid(hub, robot, 3.25, -40, 0)
abs_flip_turn(flipper, 90, 50, flipperInit)
pid(hub, robot, 69, -80, 10)
... | The main task of the code is to execute a sequence of robotic movements and flipper operations for unloading (dumping) and transporting (trucking) an object. It involves precise turning, PID-controlled navigation, and flipper adjustments to position and release the object, followed by high-speed movement to complete th... | def dumpAndTruck(hub, robot, flipper, flipperInit, back_flipper, back_flipperInit):
dump(hub, robot, flipper, flipperInit)
flipper.set_stop_action("hold")
abs_turning(hub, robot, -45, 30, 0)
#used to be 29.5
pid(hub, robot, 22, 30, -45)
abs_turning(hub, robot, 0, 30, 0)
abs_flip_turn(flipper... |
def __init__():
hub = PrimeHub()
hub.motion_sensor.reset_yaw_angle()
robot = MotorPair('F', 'B')
robot.set_motor_rotation(17.5, 'cm')
flipper = Motor('D')
flipper.set_stop_action('brake')
back_flipper = Motor('A')
back_flipper.set_stop_action('brake')
back_flipper.set_degrees_coun... | The main task of the code is to execute a series of predefined missions (e.g., Powerplant, TV, Windmill, Dino Run, Platform Run, Reservoir Run) in sequence using robotic components. It initializes hardware, measures transition times between missions, resets systems between runs, and tracks execution durations for perfo... | def mainmenu():
#Create variables
currentTime = time.time()
hub, robot, flipper, back_flipper = __init__()
waitUntilTap(hub)
print("New Run:")
hub, robot, flipper, back_flipper = __init__()
#Run 1 - TV Run - Missions Done: Powerplant, TV, Car, Windmill, Toy Factory
powerplant_and_tv(hu... |
def run_iter(self, session, batch, mode, CharCNN):
"""
This performs a single training iteration (forward pass, loss computation, backprop, parameter update)
Inputs:
session: TensorFlow session
batch: a Batch object
Returns:
loss: The loss (averaged across t... | The main task of the code is to train a question-answering model using TensorFlow, iterating over batches of training data, updating model parameters, tracking loss with exponential smoothing, and periodically evaluating performance on development data. It saves checkpoints, logs training metrics (loss, gradient/parame... | def train(self, session, train_context_path, train_qn_path, train_ans_path, dev_qn_path, dev_context_path, dev_ans_path, spanMode, CharCNN):
"""
Main training loop.
Inputs:
session: TensorFlow session
{train/dev}_{qn/context/ans}_path: paths to {train/dev}.{context/question/a... |
def reset_game_state(self):
self.total_reward = 0
self.episode_length = 0
self.current_score = 0
self.level_progress = [-1]
self.pokemon_found_list = [-1]
self.ash_loc_dict = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
self... | This code resets a PyBoy-based game environment by saving the current state, restarting the emulator after a set number of steps, initializing random seeds, resetting game states, and preparing stacked observations for reinforcement learning. It manages emulator lifecycle, state persistence, and observation handling fo... | def reset(self, seed=None, options=None):
save_file_object = open("ROMs/save_state_agent_{}".format(self.agent_id), "wb")
self.pyboy.save_state(save_file_object)
if self.pyboy_counter == 10000:
self.pyboy.stop()
del self.pyboy
self.pyboy_counter = 0
... |
def get_goal(self):
total_lvls = self.current_score
enemy_lvl = self.previous_enemy_lvl
map_steps = self.get_map_steps(self.get_map_id())
new_pkm_fnd = self.pyboy.get_memory_value(0xcfd9)
num_poke_bll = self.pyboy.get_memory_value(0xd31e)
# Goal decision tree
# F... | This method processes a given action by executing it in the environment, updating the state, calculating rewards, and checking termination conditions. It skips multiple frames, updates observations, tracks episode progress, and returns the next observation, reward, done flag, truncation status, and additional info for ... | def step(self, action):
total_reward = 0
done = False
info = {}
for _ in range(self.frame_skip):
if not done:
self.get_goal()
self.execute_action(action)
self.update_frame_stack()
observation = self.get_stacked_o... |
def get_license_list(git_token):
licenseNames = []
licenses_url = f"https://api.github.com/licenses"
headers = {"Authorization": f"token {git_token}"}
licenseList = requests.get(licenses_url, headers=headers)
if(licenseList.status_code == 200):
licenseList = licenseList.json()
licens... | The main task of the code is to determine the compatibility score of a GitHub repository's license by comparing it to a list of available licenses. It retrieves the license list, identifies the repository's license, and calculates a score based on the match. | def license_func(owner, repo, token):
license_list = get_license_list(token)
license_name = github_license(owner, repo, token, license_list).lower()
license_list = ", ".join(license_list).lower()
return license_score(license_name, license_list) |
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return f"{s} {size_name[i]}"
def process_csi_and_detect_breath(csi_file_path):
# ... | The code provides an interactive visualization interface for sensor data from a specific node, allowing users to explore WiFi CSI data, IRA, mmWave, depth camera, RGB video, thermal imaging, UWB, ToF, and heart rate data. It enables directory/file selection, data loading, and dynamic plotting of heatmaps, time-series, ... | def render_node_visualizations(node_dir):
st.header(f"Visualizations for Node: {node_dir}")
# Wifi visualization
# Step 1: Select a Directory
exp_dirs = glob.glob(os.path.join(node_dir, "wifi/exp-*"))
exp_dirs.sort(key=lambda x: os.path.getmtime(x), reverse=True) # Sort by modification time, newest... |
def random_order(ugraph):
"""
takes a graph and returns a list of the nodes in the graph in some random order.
"""
attack_list = list(ugraph.keys())
random.shuffle(attack_list)
return attack_list
def targeted_order(ugraph):
"""
Computes a node of the maximum degree in ugraph. If multiple... | The main task of the code is to generate a single line plot comparing the resilience of three graphs (Network, ER, UPA) under different attack strategies (random, targeted, fast targeted). It plots the size of the largest connected component against the number of removed nodes, using three curves for each graph type. T... | def build_plot(ugraph1, ugraph2, ugraph3, flag):
"""
Plot the results as three curves combined in a single standard plot (not log/log). Use a line plot for each curve.
The horizontal axis for your single plot be the the number of nodes removed (ranging from zero to the number of
nodes in the graph) whil... |
def _print_gravity_message(message):
global _is_gai
if _is_gai:
print("[gravityAI]: " + message, flush=True)
_print_debug_message(message)
def getInputFile():
return getInputCSV()
def getOutputFile():
return getOutputCSV() | The code sets up a WebSocket server or executes a handler based on a port. It validates the handler, starts a server on localhost if a port is specified, or runs the handler directly otherwise. It handles exceptions, manages an event loop, and ensures the handler processes input/output files. | def wait_for_requests(handler):
global _request_handler
global _port
_request_handler = handler
if (not _check_request_handler):
sys.stderr.write(
"Handler is invalid. Expected a function that accepts two arguments (inputpath, outputPath).")
sys.exit(2)
return
i... |
def parse_files(location):
"""
Iterates through the Data directory and gathers the strokes from all of the xml files.
:param location: String, contains the root directory of the xml files.
"""
loc = copy.copy(location)
content = os.listdir(loc)
# Iteration into the deepest directory layer t... | The main task of the code is to process data by parsing files from a specified directory, loading marked stroke information from a text file, generating statistics from cleaned stroke data, and saving the resulting statistics to a file. The workflow involves analyzing input data, handling potential errors, and storing ... | def main():
parse_files('/media/patrik/1EDB65B8599DD93E/Data/Erika/TestData')
load_marked_strokes('hstrokes.txt')
save_statistics('stat', np.array(clear_faulty_data(create_stroke_statistics()))) |
def set_target_throttle(self, target_throttle_):
if target_throttle_ > self.actual_throttle + self.max_delta_throttle:
self.actual_throttle = self.actual_throttle + self.max_delta_throttle
elif target_throttle_ < self.actual_throttle - self.max_delta_throttle:
self.actual_throttl... | This timer callback function manages safety counter limits, adjusts vehicle throttle/steering control, monitors vibration data (calculating averages and publishing values above 0.15), checks DAC statuses for heartbeat signaling, and handles errors by disabling a relay. It maintains a vibration history, publishes sensor... | def timer_callback(self):
try:
self.safety_counter += 1
if self.safety_counter > self.max_safety_counter:
self.target_throttle = 0
self.set_target_throttle(self.target_throttle)
self.set_target_steering(self.target_steering)
#self.get_t... |
def rand_rho_purification(dim1, dim2):
"""
Create a random purified density matrix for a bipartite system.
Args:
dim1, dim2 (int): The dimensions of the two subsystems.
Returns:
torch.Tensor: The random purified density matrix.
"""
dim = dim1 * dim2
psi = basis_element(dim ** 2... | The function `rand_rho` generates a random bipartite density matrix using purification. It first creates a random pure state density matrix (`rho_pure`) via `rand_rho_purification`. If no Kraus operators are provided, it generates default ones for partial tracing. It then applies the partial trace operation on `rho_pur... | def rand_rho(dim1, dim2, kraus=None):
"""
Generate a random density matrix for a bipartite system using purification.
Args:
dim1, dim2 (int): The dimensions of the two subsystems.
kraus (list[torch.Tensor], optional): The Kraus operators for the partial trace.
Returns:
torch.Tensor: T... |
def get_zone_state(self, zoneNumber):
data = {}
# Store response in variable
zoneState = requests.post(f"http://192.168.{WSNUM}.2/rest/services/Z{zoneNumber}", json=data)
# convert variable to dict using json library
zoneState = json.loads(zoneState.content)
return zoneSt... | The main task of the code is to manage zone 3 and zone 5 states, coordinate pallet transfers between zones, and control robot/drawing operations based on zone occupancy and mobile/robot status. It checks conditions to trigger zone 2 handling, initiate drawing, or transfer pallets from zone 3 to 5 when zones are empty a... | def z3_handler(self):
"""
This function handles everything around zone 2
"""
zone3state = self.get_zone_state(3)
zone5state = self.get_zone_state(5)
print("--------------------------------------------------------------------------------------------")
print(f"Z3_Ha... |
def get_zone_state(self, zoneNumber):
data = {}
# Store response in variable
zoneState = requests.post(f"http://192.168.{WSNUM}.2/rest/services/Z{zoneNumber}", json=data)
# convert variable to dict using json library
zoneState = json.loads(zoneState.content)
return zoneSt... | The main task of the code is to manage pallet transfers into Zone 5 based on adjacent zone states and robot status. It checks Zone 5's emptiness, then decides to transfer pallets from Zone 4 (if robot is active) or Zone 3 (if robot is inactive) to Zone 5, printing status updates and triggering transfer actions accordin... | def z5_handler(self):
"""
This function handles everything around zone 2
"""
zone5state = self.get_zone_state(5)
zone4state = self.get_zone_state(4)
zone3state = self.get_zone_state(3)
print("----------------------------------------------------------------------... |
def gridStructure(self):
mygrid = QGridLayout()
loadwid, self.layload = layinWidget("V")
sqltabs, self.innerlay = layinWidget("V")
maintab = QTabWidget()
maintab.setMaximumWidth(270)
maintab.addTab(loadwid, "Load Data")
maintab.addTab(sqltabs, "View Data")
... | The code defines a `VisualTab` method to create and configure a GUI window for a Formula 1 database. It sets the window title, icon, size, position, and object name, then initializes layout structures, SQL variables, main tabs, and a side web tab before displaying the window. | def VisualTab(self):
self.setWindowTitle("Formula1 Database")
self.setWindowIcon(QIcon("images/f1-logo.png"))
self.setMaximumSize(975, 435)
self.move(100, 100)
self.setObjectName("RedWid")
self.gridStructure()
self.sqlVariables()
self.setMainTab()
... |
def create_grid_nodes(self):
self.grid_nodes = [None] * self.grid_height
for i in range(self.grid_height):
self.grid_nodes[i] = [None] * self.grid_width
for i in range(self.grid_height):
for j in range(self.grid_width):
self.grid_nodes[i][j] = Node((i,j),... | The main task of the code is to navigate an agent toward a destination using pathfinding algorithms (A*), with clustering and ratio calculations to prioritize targets. It initializes grid nodes, clusters diamonds, computes scores, and selects the highest ratio cluster. If a path is found, it returns the next directiona... | def do_turn(self) -> Action:
if len(self.direction) == 0:
self.path = []
self.grid_nodes = []
self.diamonds = []
self.closedList = []
self.openList = []
self.cluster_centers = []
self.clusters_scores = []
se... |
def all_same_class(data):
for row in data:
if row[-1] != data[0][-1]:
return False
return data[0][-1]
def split_attribute(cur_data, cur_attributes, attributes, classes):
split_subsets = []
max_entropy = -1 * float("inf")
best_feature = -1
best_threshold = None
for attrib... | This function generates a decision tree node by selecting the best feature to split the data, determining the threshold, and recursively creating child branches for each subset. It returns a dictionary representing the node, including the feature, threshold, distinct classes in each split, and child nodes, stopping whe... | def generate_branches(data, remaining_features, features, classes):
if all_same_class(data):
return {}
elif len(remaining_features) == 0:
return {}
else:
(best, best_threshold, subset) = split_attribute(data, remaining_features, features, classes)
remaining_f = remaining_fe... |
def evaluate_test_error(self):
"""
:return:
"""
error = 0.0
for i, entry in enumerate(self.tensor.test_entries):
predict = self.predict_entry(entry)
correct = self.tensor.test_vals[i]
if self.likelihood_type == "normal":
error +... | The main task of the code is to perform iterative round-robin updates on the columns of hidden matrices in a factorization model. It cycles through each dimension's columns, updating their natural parameters and hyperparameters sequentially. The process runs for a specified number of iterations, reporting training/test... | def factorize(self):
"""
factorize
:return: None
Doing round robin updates for each column of the
hidden matrices
"""
update_column_pointer = [0] * self.order
start = time.time()
# while self.check_stop_cond():
for iteration in range(self.i... |
def get_limb_length(j: int, distance_matrix: np.ndarray) -> Tuple[int, int, int]:
limb_length = float('inf')
for i in range(len(distance_matrix)):
if i != j:
for k in range(i+1, len(distance_matrix)):
if k != j:
d = (
distance_matri... | The main task of the code is to construct a phylogenetic tree from a distance matrix using an additive method. It recursively builds the tree by identifying limb lengths, adding internal nodes, and updating an adjacency list to represent the tree structure with edge lengths. The function returns the adjacency list and ... | def additive_phylogeny(distance_matrix: np.ndarray, num_leaves: int) -> Tuple[Dict[int, List[Tuple[int, int]]], int]:
if len(distance_matrix) == 2:
adjacency_list = {}
adjacency_list[0] = [(1, distance_matrix[0, 1])]
adjacency_list[1] = [(0, distance_matrix[1, 0])]
return adjacency_l... |
def get_random_motifs(k: int, t: int, n: int, DNA_matrix: np.ndarray) -> np.ndarray:
motifs = np.zeros((t, k), dtype=int)
for i in range(t):
idx = random.randint(0, n-k)
motifs[i] = DNA_matrix[i, idx:idx+k].copy()
return motifs
def get_count_matrix(motifs: np.ndarray, k: int) -> np.ndarray:
... | The function performs randomized motif search to identify the optimal set of k-length motifs in a DNA matrix. It initializes with random motifs, iteratively computes a profile matrix with pseudocounts, finds the most probable k-mers, and updates the best motifs if the score improves. The process halts when no further i... | def randomized_motif_search(k: int, t: int, n: int, DNA_matrix: np.ndarray) -> np.ndarray:
motifs = get_random_motifs(k, t, n, DNA_matrix)
best_motifs = motifs.copy()
while True:
count_matrix = get_count_matrix(motifs, k)
count_matrix += np.full((4, k), 1)
profile_matrix = count_matr... |
def total_distance(s: np.ndarray, DNA_matrix: np.ndarray) -> int:
distance = 0
for DNA in DNA_matrix:
distance += minimum_hamming_distance(s, DNA)
return distance
def bypass(k_mer: np.ndarray, depth: int, total_depth: int, num_children: int) -> Tuple[np.ndarray, int]:
for i in range(depth, 0, -1... | The function performs a branch-and-bound search to find the k-mer median string in a DNA matrix, minimizing the total Hamming distance to all sequences. It explores possible k-mers recursively, pruning paths where the optimistic distance exceeds the current best. When a complete k-mer is evaluated, it updates the media... | def branch_and_bound_median_search(k: int, t: int, n: int, DNA_matrix: int) -> str:
k_mer = np.full(k, 1)
median_string = k_mer.copy()
best_distance = float('inf')
depth = 1
while depth > 0:
if depth < k:
prefix = k_mer[:depth]
optimistic_distance = total_distance(pre... |
def update_force(self) -> None:
for body in self.bodies:
total_force_x: int = 0
total_force_y: int = 0
for other_body in self.bodies:
if other_body == body:
continue
force_x, force_y = self.calculate_force(body, other_body... | The main task of the code is to simulate the physical movement of an object by sequentially updating its force, acceleration, velocity, and position. This stepwise process calculates the object's new state based on physical laws, ensuring accurate motion simulation in a dynamic environment. | def run_simulation(self) -> None:
self.update_force()
self.update_accerlation()
self.update_velocity()
self.update_position() |
def load_config():
config = configparser.ConfigParser()
try:
cfile = config.read(CONFIG_FILE)
except configparser.MissingSectionHeaderError:
raise ConfigurationException(MALFORMED_CONFIG_FILE)
except Exception:
raise ConfigurationException(UNKNOWNN_CONFIG_FILE)
config... | The function converts a Google Keep note into a Markdown file, replacing checkboxes with markdown syntax, downloading attached media, and saving the note with metadata. It handles directory creation, skips or renames existing files based on flags, and writes content with timestamps and links. | def keep_save_md_file(keepapi, gnote, note_labels, note_date, overwrite, skip_existing):
try:
md_text = gnote.text.replace(u"\u2610", '- [ ]').replace(u"\u2611", ' - [x]')
outpath = load_config().get("output_path").rstrip("/")
mediapath = load_config().get("media_path").rstrip("/")
if... |
def keep_init():
keepapi = gkeepapi.Keep()
return keepapi
def ui_login(keepapi, defaults, keyring_reset, master_token):
try:
userid = defaults.get("google_userid").strip().lower()
if userid == USERID_EMPTY:
userid = click.prompt('Enter your Google account username', type=str... | The main task of the code is to initialize a Keep API connection, handle user login, and execute a query with parameters like overwrite/skip flags, search terms, and other options. It checks for incompatible flags, processes input, and manages errors, ensuring proper API interaction for a Markdown tool. | def main(r, o, a, p, s, c, search_term, master_token):
try:
click.echo("\r\nWelcome to Keep it Markdown or KIM!\r\n")
if o and s:
print ("Overwrite and Skip flags are not compatible together -- please use one or the other...")
exit()
kapi = keep_init()
ui_login(kapi, ui_welc... |
def search_results(search_term):
results = search_client.search(search_term)
return results
def print_table(idx, result, search_term):
col1, col2 = st.columns([1, 1])
header_desc = f"Result #{idx} ---from page {result['page_number']}----table {result['table_number']}"
st.header(header_desc)
with... | This Streamlit app extracts and annotates tables based on a search term, saves annotated images, summarizes extracted data, and displays results via an image carousel. It processes search results, handles table HTML, generates annotated images, and presents summaries and visualizations for user interaction. | def app():
st.header("Extract Tables and answer questions")
search_term = st.text_input("Search term", "")
st.header(search_term)
if search_term:
results = search_results(search_term)
st.write("searching and annotating...")
all_image_paths = []
all_results = []
... |
def _reward_function(self, reward, delay_factor=True):
factor = 1.
if reward <= 0:
reward = 0.
if delay_factor:
factor = 1./(self.total_step * self._max_train_step_percent -
(self.current_step - self._start_step))
return factor * math.log1... | This code processes an action in a simulated trading environment by normalizing it, updating the portfolio state, checking termination conditions (bankruptcy or max steps), calculating rewards, and returning the next observation, reward, done flag, and metadata. It ensures valid actions, handles environment reset on te... | def step(self, action):
# action = (action + 1.0)/2.0
if np.sum(action) != 0:
action = action/np.sum(action)
else:
action = np.zeros(self.n+1)
action[self.n] = 1.0
self._action = action
done = False
if self.current_step >= self.max_ste... |
def get_union_done(polymesh_name,center_choice,r1,r2,num,case_num):
print("generate defect, step1")
areasum1,center,r= try_union_once(polymesh_name,center_choice,r1,r2,num,case_num)
print("area sum:",areasum1)
polymesh = read_triangle_mesh(polymesh_name)
vertex = np.asarray(polymesh.vertices)
tr... | The main task of the code is to generate a defective point cloud with spherical regions by modifying a mesh, sampling points on the union of the mesh and spheres, adding noise, and saving the result. It calculates defect positions, applies Poisson disk sampling, introduces noise, and returns defect parameters for furth... | def generate_defect(polymesh_name, polypcd,path_sample_pcd_save, pcd_pts,r1,r2,num,case_num):
## Start to make sphere defect
polymesh = read_triangle_mesh(polymesh_name)
center_choice = np.asarray(polypcd.points).tolist()
print(len(center_choice))
areasum1,center,r=get_union_done(polymesh_name,cente... |
def read_cache(name, options):
if not cache_enabled: return False
if '/' in name:
name = name.split('/')[1]
if 'clear' in options:
try:
os.remove( f'{cache_location}/{name}' )
except OSError as e:
pass
try:
if (datetime.today() - datetime.fromti... | The function `check_versions` processes a list of package names to retrieve their version details. It checks a cache first; if available and not cleared, it uses cached data. If not, it determines the source (GitHub or EOFLife) based on the name format, fetches version, date, and link, then saves the new data to the ca... | def check_versions(names, options):
versions = []
for name in names:
cache_data = read_cache(name ,options)
original_name = name
if name in db.supported:
name = db.supported[name]
if cache_data and 'clear' not in options:
versions.append(cache... |
def check_arguments(arguments):
arguments.pop(0)
args = []
names = []
for arg in arguments:
if arg.startswith('-'): args.append(arg)
else: names.append(arg)
if len(names) < 1 : names = default_names
return(args, names)
def process_args(args, names):
valid_args = ['-p',... | The main task of the code is to process command-line arguments, determine software versions based on specified names and options, and either save the results as an HTML file or print them directly, depending on the provided flags like 'html' or 'print html' | def main():
args, names = check_arguments(sys.argv)
options = process_args(args, names)
versions = check_versions(names, options)
if 'html' in options or 'print html' in options:
save_html(versions, html_file, options)
else:
print_version(versions, options) |
def parse_story(input_filename):
doc = xml.dom.minidom.parse(input_filename) # parse xml file
reps = doc.getElementsByTagName('rep') # get all <rep> tags in xml
for rep in reps: # iterate over <rep>'s
rep_id = rep.getAttribute('id') # get id attribute of respective <rep>
# get raw text ... | The code processes input files to generate a dataset for semantic role labeling (SRL) by parsing XML stories, filtering out incorrect sentences from specific files (story5, 6, 8, 13.sty), and compiling parsed data (sentences, POS tags, animacies, semroles, sentence trees) into a structured dictionary. The dictionary is... | def execute_creation(input_files):
pbar = ProgressBar() # initialize a progress bar
data_dict = []
for filename in pbar(input_files): # iterate over input files
input_filename = input_dir + filename
sentences_list, sentences_off_list, animacies_list, pos_list, semroles_strings, semroles_o... |
def BreadthFirstSearch(self, start, goal):
# Update the costs associated with the neighbouring node relative to the distance between the start node and the goal node
distance = self.Heuristic(start, goal, False)
# If the Manhattan distance between the start and goal nodes is equal to (adjacent)... | This function determines the pathfinding algorithm based on the 'AIType' attribute and executes the corresponding search method (e.g., BFS, DFS, A* with various heuristics, Dijkstra, etc.) to compute a path from 'start' to 'target', assigning the result to 'self.path'. It supports both unidirectional and bidirectional ... | def PathfindUsingSetAI(self):
# Set Path Using Set AI Type
if self.AIType == "BFS":
self.path = self.BreadthFirstSearch(self.start, self.target)
elif self.AIType == "DFS":
self.path = self.DepthFirstSearch(self.start, self.target)
elif self.AIType == "AStar":
... |
def start_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
# If Number Key 1 Pressed run Regular PacMan Game
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
self... | This code manages a game loop with state transitions (start, playing, game over). It processes events, updates game logic, and renders screens based on the current state. During 'playing', it tracks elapsed time using timestamps when coins are present, ensuring consistent updates. The loop runs while 'running' is True,... | def run(self):
while self.running:
if self.state == 'start': # If on Start Screen
self.start_events()
self.start_update()
self.start_draw()
elif self.state == 'playing': # If on Game Screen
self.time_current = timeit.default... |
def set_target(self):
if self.personality == "speedy" or self.personality == "slow":
return self.app.player.grid_pos
else: # If Random or Scared
if self.app.player.grid_pos[0] > COLS//2 and self.app.player.grid_pos[1] > ROWS//2:
return vec(1, 1)
if sel... | The code updates an object's position by moving it toward a target. It adjusts pixel coordinates based on direction and speed, then converts these to grid coordinates for the game's grid system. This ensures the object's movement is synchronized with the grid, allowing accurate positioning and interaction within the ga... | def update(self):
self.target = self.set_target()
if self.target != self.grid_pos:
self.pix_pos += self.direction * self.speed
if self.time_to_move():
self.move()
# Setting grid position in reference to pix position
self.grid_pos[0] = (self.pix_po... |
def SetDir(self, DirX, DirY):
# Cap DirX
if (DirX > 1):
DirX = 1
elif (DirX < -1):
DirX = -1
# Cap DirY
if (DirY > 1):
DirY = 1
elif (DirY < -1):
DirY = -1
# Set Direction
self.direction = vec(DirX, DirY)
d... | The main task of the code is to log current test results, reset timers, and prepare for the next test iteration or AI type. It stops PacMan movement, writes results to a file, updates counters, and repositions PacMan to a new starting point while repopulating coins. If tests remain, it configures the next test setup; i... | def InitNextTest(self):
# Stop PacMan Moving
self.SetDir(0, 0)
# Output Current Test Results to File
f = open(self.OutputFile, "a")
f.write("\n{0}, [{1},{2}], {3}, {4}".format(self.TestItCounter, int(self.starting_pos[0]), int(
self.starting_pos[1]), self.NodesTraver... |
def time_to_move(self):
# If Positioned Exactly Within a Collumn
if int(self.pix_pos.x+TOP_BOTTOM_BUFFER//2) % self.app.cell_width == 0:
# If Moving Right, Left or Nowhere
if self.direction == vec(1, 0) or self.direction == vec(-1, 0) or self.direction == vec(0, 0):
... | The code updates Pac-Man's movement toward a target, adjusts direction when reaching path nodes, tracks traversed nodes, and uses BFS to find coins. If no coins remain, it resets the target and initiates a new test; otherwise, it pathfinds to the next coin using a specified AI method. | def SearchPacManUpd(self):
# Move to Target
if self.target != self.grid_pos: # If Not At Current Target
# Move
self.pix_pos += self.direction * self.speed
# If Finished Moving to Next Node in Path
if self.time_to_move():
# Remove Now Curr... |
def is_iterable(obj: 'Any') -> 'bool':
"""verify if an object is iterable
Examples:
>>> is_iterable('string')
True
>>> is_iterable(1)
False
Args:
obj: Object to verify
Returns:
True if obj is iterable, False otherwise
"""
try:
return ... | The `include_all` method merges names from an iterable into the `__all__` list, ensuring the input is an iterable. It raises a `TypeError` if the argument is not iterable, then calls `_merge` to combine the names and `_check_reference` for validation. The goal is to dynamically extend the `__all__` list with provided n... | def include_all(self, iterable: 'Iterable'):
"""Merge the names contained in an iterable to the __all__ list
Examples:
>>> star = Star()
>>> star.include_all(['Example1', 'example2'])
>>> __all__
['Example1', 'example2']
Args:
iterab... |
def build_pr_data_row(self, pr: Dict, repo_name: str) -> Dict:
"""Assemble all pieces of data into a dictionary for a PR row."""
try:
comments_str = self.fetch_comments(pr["comments_url"])
commits_info = self.fetch_commits(pr["commits_url"])
commits_count = len(commit... | The function processes a single pull request (PR) by constructing a data structure from the PR and repository name, inserting the data into a database if valid, and separately storing the PR's body text into a MongoDB collection using the PR's ID. | def process_single_pr(self, pr, repo_name):
"""Process and store data for a single PR."""
pr_data = self.build_pr_data_row(pr, repo_name)
if pr_data:
self.insert_pr_data(pr_data)
self.insert_pr_body_mongodb(pr_data["pr_id"], pr_data["pr_body"]) |
def get_pull_requests(self, owner: str, repo_name: str) -> List[Dict]:
"""Fetch all pull requests for a given repository."""
prs_url = f"{self.base_url}/repos/{owner}/{repo_name}/pulls?state=all&per_page={self.per_page}" # pylint: disable=line-too-long
return self.get_all_paginated_items(prs_ur... | The function creates a pandas DataFrame containing repository metadata and pull request (PR) data. It processes either a specific repository or all repositories, fetching PRs for each and converting them into structured rows. These rows are aggregated into a DataFrame, which is returned as the result. | def create_dataframe_with_prs(self) -> pd.DataFrame:
"""Create a DataFrame from the repository metadata and pull requests, for either all repos or a specific one.""" # pylint: disable=line-too-long
rows = []
if self.repo:
# If a specific repo is provided, use it directly
... |
def create_dataframe_with_prs(self) -> pd.DataFrame:
"""Create a DataFrame from the repository metadata and pull requests, for either all repos or a specific one.""" # pylint: disable=line-too-long
rows = []
if self.repo:
# If a specific repo is provided, use it directly
... | The main task of the code is to fetch pull request (PR) data, store metadata in a SQL database, and save PR body content in MongoDB. It iterates through a DataFrame of PRs, inserts metadata into SQL using `insert_pr_data`, and stores bodies in MongoDB via `insert_pr_body_mongodb`. The function logs success or errors, h... | def create_and_store_pr_data_all(self):
"""Fetches pull request data, stores metadata in SQL, and body content in MongoDB."""
try:
df_prs = (
self.create_dataframe_with_prs()
) # Assuming this returns a DataFrame
if not df_prs.empty:
f... |
def fly1(self):
for line in self.directions:
self.flyRule1(line)
self.trajectoryX.append(self.x)
self.trajectoryY.append(self.y)
def plot(self,name):
fig, ax = plt.subplots()
ax.plot(self.trajectoryX, self.trajectoryY)
ax.grid()
fig.savefig(f"{... | The main task of the code is to compute and return the Manhattan distance after calling the fly1() method and plotting a graph labeled 'star1'. | def star1(self):
self.fly1()
self.plot('star1')
return self.manhattanDistance() |
def getSeat2(self, x,y):
if x < 0 or y < 0:
return None
try:
res = self.input[y][x]
return res
except IndexError as err:
return None
def hasNoOccupiedSeatsAround2(self, x ,y):
resArr = []
dirs = [[-1, 0], [0, -1], [-1,-1], [1,0], ... | This code applies seating rules to update a grid. It copies the input grid, checks each seat's neighbors, and changes 'L' (empty) to '#' (occupied) if no occupied seats are nearby, or '#' to 'L' if overcrowded. The updated grid replaces the original input and is returned. | def applyRules2(self):
result = copy.deepcopy(self.input)
for y in range(len(result)): # rows
for x in range(len(result[y])): # seats
#print(x, y)
seat = self.getSeat2(x, y)
if self.hasNoOccupiedSeatsAround2(x, y) and seat == 'L':
... |
def _check_for_creds(self):
"""Confirm the presence of credentials"""
if not self._api_key:
raise Exception("An API key is required to get dbt Cloud jobs.")
if not self.account_id:
raise Exception("An account_id is required to get dbt Cloud jobs.")
def build_mapping_job_... | This function updates or creates a custom environment variable in dbt Cloud by sending a POST request to the appropriate API endpoint. It handles job ID mapping when using a YAML identifier, constructs the correct URL based on whether an existing env_var_id is provided, and returns the updated environment variable payl... | def update_env_var(
self,
custom_env_var: CustomEnvironmentVariable,
project_id: int,
job_id: int,
env_var_id: int,
yml_job_identifier: str = None,
) -> Optional[CustomEnvironmentVariablePayload]:
"""Update env vars job overwrite in dbt Cloud."""
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.