dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def read_txt(fname):
with open(fname, 'r') as fileReader:
data = fileReader.read().splitlines()
return data
def convert_df_dict():
vic_path = "/media/nimashiri/DATA/vsprojects/ICSE23/data/vuldata.csv"
data = pd.read_csv(vic_path, sep=",")
x = {}
for index, rows in data.iterrows():
... | The main task of the code is to analyze code repositories for vulnerabilities using static analysis tools (tidy, clang, infer) by comparing modified files in commits against known vulnerability patterns. It processes JSON data from specified directories, clones repositories if needed, checks for valid commits, and logs... | def main():
vic_path = "/media/nimashiri/DATA/vsprojects/ICSE23/data/vic_vfs"
full_check = True
comp = read_txt('/media/nimashiri/DATA/vsprojects/ICSE23/data/valid_commits.txt')
label_dict = convert_df_dict()
_id = 0
for tool in ['tidy', 'clang', 'infer']:
for mapping_ in ["diff... |
def get_all_db():
time.sleep(1)
out = requests.get(url1).json()
out = pd.DataFrame(out)
blank_index = [''] * len(out)
out.index = blank_index
#out = out.drop('id', axis=1)
return out
def update_item():
out = get_all_db()
out_dic , name_dic = out_dict()
st.text('Change details of... | The main task of the code is to provide an inventory management interface for food items, allowing users to view existing data, update former items, delete entries, or add entirely new food items through Streamlit checkboxes and functions. | def add_inventory():
out = get_all_db()
data = st.dataframe(out)
st.text('\n\n')
st.text('Check in what you would like to do')
if st.checkbox('Update former food items'):
with st.spinner('Loading...'):
update_item()
st.text('\n\n')
if st.checkbox('Delete former food ... |
def home():
st.write('''Hello there, welcome to Pyladies confectionery, \
this is what we have available in our store,\
Kindly check what is availabe and order from us...''')
out = get_all_db()
#automatic delete
for i, j in zip(out.quantity_available, out.id):
if i <= 0:
... | The code defines a Streamlit app with a sidebar menu allowing users to navigate between 'HOME', 'ORDER', and 'INVENTORY' sections. Depending on the selected option, it loads corresponding functions (`home()`, `add_order()`, `add_inventory()`) with loading spinners. The main task is to create a multi-page Streamlit inte... | def main():
add_selectbox = st.sidebar.selectbox(
'what would you like to do?',
('HOME','ORDER', 'INVENTORY',))
if add_selectbox == 'HOME':
#st.subheader('HOME')
with st.spinner('Loading...'):
home()
elif add_selectbox == 'ORDER':
st.subheader('Order')
... |
def DisableAlarm():
global nAlarmCount
global bAlarmActive
global rfDevice
bAlarmActive = False
GPIO.output(ALERT,False)
nAlarmCount = 0
# Reset RF device to Receive
if rfDevice is not None:
if rfDevice.tx_enabled:
rfDevice.disable_tx()
rfDevice ... | The main task of the code is to manage a sensor monitoring system with GPIO hardware interaction, including heartbeat signaling, user input handling via a toggle switch, real-time sensor data updates (body/max sensors, temperature, humidity, gas sensors), LCD display updates, and alarm activation logic based on sensor ... | def main():
global lastupdatetime
global lasthbtime
global bHeartBeat
global nDisplay
global bToggle
global bDiagMode
global bAlarmActive
global rfDevice
#setup an exit handler when
signal.signal(signal.SIGINT, exithandler)
signal.signal(signal.SIGTERM, exithandler)
... |
def set_up_gpu(args):
os.environ['CUDA_VISIBLE_DEVICES'] = args.device_idx
args.num_gpu = len(args.device_idx.split(","))
def create_experiment_export_folder(args):
experiment_dir, experiment_description = args.experiment_dir, args.experiment_description
if not os.path.exists(experiment_dir):
os... | The main task of the code is to configure GPU settings, create an experiment output directory, save training configuration as JSON, print non-None arguments, and return the export folder path for experiment tracking and reproducibility. | def setup_train(args):
set_up_gpu(args)
export_root = create_experiment_export_folder(args)
export_experiments_config_as_json(args, export_root)
pp.pprint({k: v for k, v in vars(args).items() if v is not None}, width=1)
return export_root |
def draw_menu():
screen.blit(scaled_background_image_1, (0, 0))
title_font = pygame.font.Font('resources/assets/atomix-font.otf', 80)
title_text = title_font.render("Atomix", True, WHITE)
title_rect = title_text.get_rect(center=(WINDOW_WIDTH // 2, 100))
screen.blit(title_text, title_rect)
comp... | The code presents a menu for selecting game modes (computer, human, or how-to-play) and algorithm types (uniformed/heuristic) using Pygame. It captures mouse clicks to determine the selected mode and algorithm, returning the chosen mode and algorithm function. If "how to play" is selected, it displays instructions and ... | def menu():
while True:
mode = Mode.NONE
algorithm = None
computer_rect, human_rect, how_to_play_rect = draw_menu()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygam... |
def list_ticket_fields(file):
schema = {
"type": "object",
"required": ["ticketFields", "config"]
}
# read in JSON file and extract data needed. Throw errors if ill-fortmated
with open(file) as json_file:
try:
data = json.load(json_file)
jsonschema.validat... | The main task of the code is to process configuration files to validate their JSON structure, extract survey data, generate objects for each survey, identify mismatched responses, update last run dates in config files, and output incorrect data pairs to a CSV file. | def main():
# specify path for where to find config files
config_files_path = '/ErrorHandling/ConfigFiles'
config_file_list = []
# get all files in the specified directory, if it exists
try:
next(os.walk(config_files_path))
for root, dirs, files in os.walk(config_files_path):
... |
def db_creator():
models.Base.metadata.create_all(bind=engine)
def movies_csv_to_db(db):
df = pd.read_csv('data/my_db/movies.csv', sep='\t', on_bad_lines='skip')
df = df.replace(['\\N'], None)
index_movie = crud.get_last_movie_id(db=db)
for i, row in df.iterrows():
genres_list = row['genre... | The main task of the code is to import data from multiple CSV files into a database by calling specific functions for each dataset (movies, actors, users, ratings, likes), using a database session created by `SessionLocal()` after initializing the database with `db_creator()`.) | def csv_to_db():
db_creator()
db = SessionLocal()
movies_csv_to_db(db)
actors_csv_to_db(db)
users_csv_to_db(db)
users_ratings_csv_to_db(db)
users_likes_csv_to_db(db)
actors_movies_csv_to_db(db) |
def visualize_pts(pts, fig=None, bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0),
show_intensity=False, size=(600, 600), draw_origin=True):
if not isinstance(pts, np.ndarray):
pts = pts.cpu().numpy()
if fig is None:
fig = mlab.figure(figure=None, bgcolor=bgcolor, fgcolor=fgcol... | The main task of the code is to visualize 3D point cloud data alongside ground truth and predicted bounding boxes, converting inputs to NumPy arrays if necessary. It draws point clouds, applies a grid range, renders ground truth boxes in blue, and visualizes reference boxes with label-specific colors and scores. The fu... | def draw_scenes(points, gt_boxes=None, ref_boxes=None, ref_scores=None, ref_labels=None):
if not isinstance(points, np.ndarray):
points = points.cpu().numpy()
if ref_boxes is not None and not isinstance(ref_boxes, np.ndarray):
ref_boxes = ref_boxes.cpu().numpy()
if gt_boxes is not None and n... |
def perform_streamfield_operation(self, operation, source, target):
"""
Performs a StreamField `operation` given the `source` and `target` pages.
If something goes wrong, we will take note of the error and carry on.
Args:
operation (function): The StreamField operation to b... | This code performs a data migration from SubServicePage to SubPropositionPage, transferring content, updating links to prevent 404 errors, avoiding title/slug conflicts, and generating reports. It checks if the migration has already run, unpublishes live pages, creates new pages with preserved data, handles StreamField... | def handle(self, *args, **options):
"""
Approach:
- First, check if the migration has already been run. If it has, exit,
providing instructions on how to undo the migration.
- Grab all the fields we need from each SubServicePage, so that we can
create SubPropositionPages... |
def find_route(self, finish_node):
current_node = finish_node
path_list = []
while current_node.parent is not None:
path_list.append(current_node)
current_node = current_node.parent
return path_list + [current_node]
def in_list(self, node_object: Node, nodes_list:... | This code implements the A* algorithm to find the shortest path from a start node to a goal node. It maintains open and closed node lists, iteratively selects the node with the lowest cost, explores neighbors, and returns the path and iteration count once the goal is reached. | def a_star(self):
self.open_nodes.append(self.start)
counter = 0
while len(self.open_nodes) > 0:
counter += 1
self.open_nodes.sort()
current_node = self.open_nodes.pop(0)
self.closed_nodes.append(current_node)
if current_node.position ... |
def mungeFuncName(name):
name = name.replace(" ", "_")
name = name.replace("(", "")
name = name.replace(")", "")
name = name.replace(",", "")
return name
def retrieveData(id, args=None):
if args != None:
id = id + "_" + str(args)
id = mungeFuncName(id)
files_found = glob.glob(f"d... | The main task of the code is to retrieve data by first checking a cached version using a munged function name derived from the input function and arguments. If the cached data is not found, it falls back to generating the data via a secondary function. The process involves formatting the function name, incorporating ar... | def retrieveSpecificData(func, args=None):
func_name = str(func.__name__)[4:]
request_result = None
if args != None:
func_name = func_name + "_" + str(args)
func_name = mungeFuncName(func_name)
request_result = retrieveData(func_name)
if request_result == None:
return getSpecific... |
def retrieveData(id, args=None):
if args != None:
id = id + "_" + str(args)
id = mungeFuncName(id)
files_found = glob.glob(f"data/data_{id}_*")
try:
most_recent_file = max(files_found, key=os.path.getctime)
except ValueError as err:
# no files found
logging.warning(er... | The main task of the code is to retrieve structured data (e.g., global ticker, divisions, teams, simulation data) and convert it into standardized facts for processing. It generates temporal facts, maps team/division hierarchies, extracts player rosters, and records game data across seasons. The code stores these facts... | def makeFacts():
global_ticker = retrieveData("global_ticker")
all_divisions = retrieveData("all_divisions")
offseason_setup = retrieveData("offseason_setup")
offseason_recap = retrieveData("offseason_recap")
all_teams = retrieveData("all_teams")
simulation_data = retrieveData("simulation_data")... |
def load_vars():
# preluam variabilele
d = load_sections()
var = d["Vars"]
vars_list = []
S = 'a' # S e variabila de start, initializata cu 'a', valoare imposibila
# daca nu exista variabile
if not var:
raise RuntimeError("Nu exista variabile.")
for element in var:
spli... | The main task of the code is to generate a string using a context-free grammar by iteratively replacing variables with randomly chosen production rules, starting from a designated initial symbol. The process continues until no variables remain or the string length reaches 10 characters, producing a terminal string comp... | def generate_lang():
# preluam simbolurile, variabilele si regulile
v = load_vars()
vars_list = v[1]
s = v[0]
symbols = load_sigma()
rules = load_rules()
# pornim de la variabila de start
crt_str = [s]
exists = True
first_var = s
while exists is True and len(crt_str) < 10:
... |
def maximal(term,grid,n,j,k):# finds the biggest possible legal region containing the given term, the log of size of region and also the indices of elements in the region O(n*2^l) as it checks for all 2^l possible terms individually and uses elements inside function which takes proportional to n time
maximum=[term,... | This function computes the maximally expanded regions for each variable in `func_TRUE` by combining it with `func_DC`, using a `maximal` expansion process. It iterates over each element in `func_TRUE`, applies region expansion, collects results, and removes duplicates to return a list of unique, maximally expanded regi... | def comb_function_expansion(func_TRUE, func_DC):# finds the list of maximally expanded region for each varriable O(n^2*2^l)as it runs maximal n times
grid=func_TRUE+func_DC
n=len(func_TRUE)
final=[]
for i in range(n):
region=maximal(convert(func_TRUE[i]),grid,0,[i],n)
final.append(region... |
def comb_function_expansion(func_TRUE, func_DC):# finds the list of maximally expanded region for each varriable O(n^2*2^l)as it runs maximal n times
grid=func_TRUE+func_DC
n=len(func_TRUE)
final=[]
for i in range(n):
region=maximal(convert(func_TRUE[i]),grid,0,[i],n)
final.append(region... | The code's main task is to reduce a set of regions by removing those entirely contained within others. It uses a counting mechanism to track overlaps, iteratively checking if a region's elements are not uniquely contributing (count ≤ 1). If so, it removes the region from the result and adjusts counts. The output is the... | def opt_function_reduce(func_TRUE,func_DC):# deletes the regions which are contained inside other regions O(n^2*2^l) as it runs comb_function_expansion once and the other expression amount to O(l*n^2)
l=comb_function_expansion(func_TRUE, func_DC)
lis=[]
n=len(func_TRUE)
c=[0]*n
ans=[]
for i in r... |
def intraday_transform(data_df):
'''Used to create the final intraday dataframe dataset.'''
data_df['Volume'] = min_max_normalize(data_df['Volume'], 0, 5)
data_df = vol_tide(data_df)
return data_df
def daily_transform(data_df, **kwargs):
'''Adds 'Directional_Vol' and 'Vol_Adv_Dec' columns to the dat... | The function `transform_data` processes financial data (Open, High, Low, Close, Volume, Adj Close) by converting date/time columns and applying period-specific transformations. For "intraday" data, it ensures proper datetime formatting and applies intraday logic. For "daily" data, it converts dates, applies daily trans... | def transform_data(data_df, period='daily', lower_limit=-0.005, upper_limit=0.005, **kwargs):
'''Expects to receive a pandas dataframe of the base equities data.
The base equities data should only contain the following columns:
Open, High, Low, Close, Volume, Adj Close
Args:
period(str): should ... |
def transform_data(data_df, period='daily', lower_limit=-0.005, upper_limit=0.005, **kwargs):
'''Expects to receive a pandas dataframe of the base equities data.
The base equities data should only contain the following columns:
Open, High, Low, Close, Volume, Adj Close
Args:
period(str): should ... | The main task of the code is to preprocess and transform intraday and daily financial data for modeling. It normalizes volume data, aligns intraday data with daily data using group-by operations, generates target variables, filters relevant columns, and prepares a cleaned dataset with specified features for analysis or... | def get_test_data(intra_data, daily_data, columns):
intra_data = transform_data(intra_data, period='intraday', columns=columns)
eod_value = intra_data.groupby([intra_data.Datetime.dt.date])['Dir_to_Vol'].sum()
daily_data['Volume'] = min_max_normalize(daily_data['Volume'], 0, 5)
daily_data = transform_da... |
def getShapeFileForDC(data_path, returnDataFrame=False):
with fiona.open(data_path + "/cb_2018_us_state_500k/cb_2018_us_state_500k.shp") as c:
for record in c:
if record.get('properties').get('STATEFP') == '11':
#print("\n --> Found DC: " + str(record.get('properties')) + "\n")... | The main task of the code is to generate a ranking dataset by processing geographic boundary data and crime statistics. It retrieves DC boundary coordinates, fetches crime data, and computes rankings based on spatial intervals. If specified, the results are saved as a CSV file. The function returns the generated rankin... | def makeRankingData(data_path, out_path, metersInterval, debug=False):
# Gives list of latitudes and longitudes for DC boundary
# of type 'polygon'.
DC_shape_file = getShapeFileForDC(data_path)
crimeData = getCrimeData(data_path)
rankingData = getRankingData(
pointList = DC_shape_file,... |
def _apply_mypy_mapped_attr(
cls: ClassDef,
api: SemanticAnalyzerPluginInterface,
item: Union[NameExpr, StrExpr],
cls_metadata: DeclClassApplied,
):
if isinstance(item, NameExpr):
name = item.name
elif isinstance(item, StrExpr):
name = item.value
else:
return
for... | This function extracts mapping information from assignment statements in declarative classes, handling special attributes like __tablename__ and __abstract__, inferring Python types from type annotations or RHS expressions, and updating metadata with mapped attribute names and their inferred types for ORM mapping. | def _scan_declarative_assignment_stmt(
cls: ClassDef,
api: SemanticAnalyzerPluginInterface,
stmt: AssignmentStmt,
cls_metadata: DeclClassApplied,
):
"""Extract mapping information from an assignment statement in a
declarative class.
"""
lvalue = stmt.lvalues[0]
if not isinstance(lva... |
def get_driver(headless: bool = True) -> WebDriver:
options = Options()
options.headless = headless
driver = webdriver.Firefox(options=options)
return driver
def go_to_login(driver: WebDriver) -> None:
driver.get(mousehunt_url('login.php'))
def login(driver: WebDriver, username: str, password: str) ... | The code automates a login process using a browser driver, performs a 5-second delay, and executes a post-login task (handle_horn). It includes error handling to log exceptions, close the driver, and re-raise errors if login or execution fails. | def run(username, password):
sleep(5)
try:
driver = get_driver()
logging.info("Driver created")
go_to_login(driver)
logging.info("Attempting to log in")
login(driver, username, password)
handle_horn(driver)
except Exception as exp:
print_exc()
... |
def validCombinations(self):
pos = self.availablePositions()
mes = self.measured()
placed = self.placed()
combs = [['p', p] for p in pos]
for i in placed:
if i not in mes:
combs.append(['m', i])
for j in placed:
if j... | The code simulates a turn-based game between two players (p1 and p2) over a specified number of rounds. In each round, players take turns selecting actions from valid combinations, updating the game state, and checking for a win. If a player wins, rewards are assigned, and all components (players, game state) are reset... | def play(self, rounds=100):
for i in range(rounds):
if i%1000 == 0:
print("Rounds {}".format(i))
while not self.isEnd:
avl_combs = self.validCombinations()
p1_action, pos = self.p1.chooseAction(avl_combs, self.board)
self.up... |
def adiVect(a,b):
ans = []
for i in range(len(a)):
ans = ans + [comp.suma(a[i],b[i])]
return ans
def inverVect(a):
ans = []
for i in range(len(a)):
escalar = (-1,0)
ans = ans + [comp.producto(escalar,a[i])]
return ans
def normaVec(a):
return (prodIntVec(a,a)[0])**(1/2... | The code computes the normalized distance vector between input vectors a and the inverse of b by first calculating the element-wise difference between a and the inverse of b, then normalizing the resulting vector. | def distVect(a,b):
ans = [[(adiVect(a,inverVect(b))[i])] for i in range (len(a)) ]
return normaVec(ans) |
def load_map(self):
conf_dic = self.input_map
self.x_size = conf_dic["height"]
self.y_size = conf_dic["width"]
self.fog_map = conf_dic["fog_map"]
for i in range(self.agents_cnt):
self.agents_list[i].x = conf_dic[f"player{i+1}_coordinate"][0]
self.agents_li... | The code's main task is to reset the environment's state by reloading the map, updating the board, adding gold, and generating an initial observation for the agent. It prepares the environment for a new episode by initializing spatial elements and returning the observation along with placeholder `None` values for rewar... | def reset(self):
# TODO :adjust this due to agent class
# commented section random positioning of agents
# X=sample(range(self.x_size),4)
# Y=sample(range(self.y_size),4)
# #problem with sample funciton
# for index,agent in enumerate(self.agents_list):
# agent... |
def coord_transform(self, x, y, dx, dy):
# return new coordination after moving in the board by from
return x + dx, y + dy
def check_coord_valid(self, x, y):
return 0 <= x < self.x_size and 0 <= y < self.y_size
def hit_agent(self, attacker: agent, defender: agent):
attck_effc = min(self.... | The function simulates a linear attack in a specified direction (up/down/left/right) from the agent's position. It iterates through cells along the attack path, updating the attack board and checking for valid coordinates or walls. If an opposing agent is encountered, it triggers a collision via hit_agent(). The attack... | def linear_attack(self, agent, action):
X, Y = agent.x, agent.y
if action == LINEAR_ATTACK_DOWN:
dx, dy = act_dict[MOVE_DOWN]
for i in range(1, self.linear_attack_range + 1):
x, y = self.coord_transform(X, Y, dx * i, dy * i)
if (not self.check_coo... |
def move(self, action, agent):
# getting new coordinations
new_x, new_y = self.coord_transform(
agent.x, agent.y, *act_dict[action])
# check the validation of action
if self.check_coord_valid(new_x, new_y) and self.check_coords_empty(new_x, new_y):
# updating age... | This function processes an agent's action by routing it to corresponding methods: setting 'STAY' action, handling movement, upgrades (defense/attack), and attack types (linear/ranged). It directs the agent's behavior based on the action value, with early returns for upgrade actions. | def run_action(self, action, agent):
if action == STAY:
agent.action = 0
# call the corresponding function for each action
if action <= MOVE_LEFT:
self.move(action, agent)
elif action == UPGRADE_DEFENCE:
self.upgrade_defence(agent)
return
... |
def agents_random_order(self, action):
agents_order = list(range(self.agents_cnt))
#agents_order=[(self.agents_list[i].wallet,i) for i in range(self.agent_cnt)]
shuffle(agents_order)
# giving higher priority to agents with less gold
priority_list = [3, 3, 3, 3, 3, 1, 1, 2, 2, 2, ... | The code processes agent actions in a turn-based game, updates the game board, handles movement and attacks, repeats unsuccessful moves, manages gold, decrements rounds, and returns observations/info when rounds end. It ensures agents act in order, resolves collisions, and determines the winner upon game completion. | def step(self, action):
done = False
# if rounds is zero at start of step
# ignore actions
# if self.rounds <= 0:
# done = True
# self.winner = self.decide_winner()
# observation = self.generate_observation()
# info = self.generate_info()
... |
def compute_output_delta(self, out):
'''
TODO: Current implementation applies activation function across all layers..
But in keras implementation, some layers use different activations
'''
delta_output = (self.y - out) * (self.__activation_derivative(out))
self.deltaOu... | The code performs a backward pass in a neural network to compute gradients via backpropagation. It calculates error deltas for the output layer and two hidden layers, enabling weight updates during training to minimize prediction errors. | def backward_pass(self, out):
# pass our inputs through our neural network
self.compute_output_delta(out)
self.compute_hidden_layer2_delta()
self.compute_hidden_layer1_delta() |
def extractSkin(image):
# Taking a copy of the image
img = image.copy()
# Converting from BGR Colours Space to HSV
img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
# Defining HSV Threadholds
lower_threshold = np.array([0, 48, 80], dtype=np.uint8)
upper_threshold = np.array([20, 255, 255], dtype=np.uint8)
... | The code processes an input image (array or file/URL) by resizing, displaying it, applying a skin mask to isolate skin regions, and extracting dominant colors from the masked area. It visualizes the original image, skin-masked result, and dominant colors via a color bar, then returns the dominant color data. The primar... | def skinextractor(imageinput):
if isinstance(imageinput, np.ndarray): #testing if numpy image
image = imutils.resize(imageinput,width=250)
elif isinstance(imageinput, str): # if it's a string
if imageinput[0:6] == 'https:': #if url
image = imutils.url_to_image(imageinput)
... |
def facialrecognition(imageinput):
# Read the fileurl and return the faces
if isinstance(imageinput, np.ndarray): #testing if numpy image
image = imutils.resize(imageinput,width=250)
elif isinstance(imageinput, str): # if it's a string
print("I got here")
if imageinput[0:6] == 'https:': ... | The function identifies primary and secondary visual characteristics of a face image. It calculates hue (warm/cool), saturation (clear/soft), and value (dark/light) scores using facial analysis. The primary characteristic is the highest-scoring trait, while the secondary is either saturation or hue, depending on the pr... | def get_primary_and_secondary_characteristics(
imageinput
) -> Tuple[str, str]:
# takes in an imageinput
print("GETTING FACE")
face = facialrecognition(imageinput)
print("GETTING HUE")
huescore, hue = newwarmorcool(face)
print("GETTING SAT")
satscore, sat = newclearorsoft(face)
... |
def get_tables_in_db(conn:SnowflakeConnection, database:str, table_name:str) -> list:
'''
Function to get tables from the db
Parameters:
conn: Connection Object
database: The database for which the tables need to be listed
table_name: name of tables which needs to be compared
'''
if con... | The function orchestrates data insertion into a Snowflake database by either using `INSERT INTO` (if the target table exists) or `COPY INTO` (if the table doesn't exist). It checks table existence via `get_tables_in_db`, prepares data as a CSV file, and executes the appropriate command. After insertion, it creates a te... | def orchestrate(conn:SnowflakeConnection,df:DataFrame,table_name:str,database:str,csv_filename:str, csv_file_path:str,data_stage:str) -> list:
'''
Function that takes in a datafram as an input to orchestrate the Copy Into or Insert Into based on the presence or absence of the table in the target database
... |
def user_move(board):
user_input = ""
display(board)
while True:
user_input = input("select the numbers where you want to place 'X'..\n")
if not user_input.isdecimal():
print("The input entered is not valid...\n")
else :
user_input = int(user_input)
... | The code implements a tic-tac-toe game where a user and computer alternate turns. The user makes moves, while the computer selects optimal positions using a board copy. The board updates after each move, checks for a winner, and ends when all moves are exhausted or a winner is determined. The function returns the game ... | def game_begin():
moves_left = 9
board = [str(i) for i in range(9)]
winner = 0
global userTurn
userTurn = True
while (moves_left and winner == 0) :
if(userTurn):
user_move(board)
else :
temp = board.copy()
index =computer_move(temp,moves_left)
... |
def move_row_left(row):
n = len(row)
squeezed_row = squeez(row)
for i in range(0, n-1):
if squeezed_row[i] == squeezed_row[i+1]:
squeezed_row[i] = 2*squeezed_row[i]
squeezed_row[i+1] = 0
return squeez(squeezed_row)
def move_row_right(row):
alt_row = [x for x in row]
... | This function moves elements in a grid in the specified direction (left, right, up, down) by shifting and merging values, returning the updated grid. For left/right, rows are processed directly; for up/down, the grid is transposed, rows are processed, then transposed back to restore orientation. | def move_grid(grid, d):
new_grid = []
if d == 'left':
for l in grid:
new_grid.append(move_row_left(l))
if d == 'right':
for l in grid:
new_grid.append(move_row_right(l))
if d == 'up':
for l in transpose(grid):
new_grid.append(move_row_left(l))
... |
def init_game(n=4):
grid = create_grid(n)
grid = grid_add_new_tile(grid)
grid = grid_add_new_tile(grid)
return grid
def render_grid(grid):
n = len(grid)
for i in range(n):
for j in range(n):
if grid[i][j] == ' ':
grid[i][j] = 0
def grid_to_string(grid):
m ... | The main task of the code is to simulate a random game of 2048, where the program automatically selects random valid moves, updates the grid, adds new tiles, and prints the grid state until the game ends. It checks if the player won or lost and outputs the result. | def random_play():
grid = init_game()
render_grid(grid)
print(grid_to_string(grid))
while (not is_game_over(grid)):
mv = rd.choice(mvt_possible(grid))
grid = move_grid(grid, mv)
grid = grid_add_new_tile(grid)
print(grid_to_string(grid))
if is_game_won(grid):
... |
def init_game(n=4):
grid = create_grid(n)
grid = grid_add_new_tile(grid)
grid = grid_add_new_tile(grid)
return grid
def render_grid(grid):
n = len(grid)
for i in range(n):
for j in range(n):
if grid[i][j] == ' ':
grid[i][j] = 0
def grid_to_string(grid):
m ... | The code implements a game loop where a player controls grid movement (left, right, up, down) to manipulate tiles, adds new tiles after each move, and displays the grid state until the game ends. It maps keyboard inputs to directions, updates the grid, and prints the current grid configuration after each move. | def game_play():
n = int(read_size_grid())
grid = init_game(n)
render_grid(grid)
print(grid_to_string(grid))
while (not is_game_over(grid)):
mv = read_player_command()
if mv == 'g':
mv = 'left'
elif mv == 'd':
mv = 'right'
elif mv == 'h':
... |
def get_specimin_env_var():
'''
Check and returns the path of the Specimin program if defined
Retruns:
Path of the local Specimin program
'''
specimin_env_value = os.environ.get(specimin_env_var)
return specimin_env_value
def clone_specimin(path_to_clone, url):
'''
Clone the lat... | The main task of the code is to process JSON test data by evaluating each issue, generating reports, and tracking statuses. It checks the OS, sets up Specimin, parses arguments, runs evaluations, logs results, and outputs JSON status files and a summary table. The script handles jar mode, debug targets, and ensures com... | def main():
'''
Main method of the script. It iterates over the json data and perform minimization for each cases.
'''
op_sys = platform.system()
if op_sys != linux_system_identifier and op_sys != macos_system_identifier:
print(f"{op_sys} no supported")
sys.exit(1)
os.makedir... |
def bounce_obj(self, obj):
lower_x, upper_x, lower_y, upper_y, obj_pos, obj_half_wid = get_obj_dims(obj)
for detector in self.detectors:
x, y = detector.pos()
# check if detector is within the object's region
if lower_x < x < upper_x and lower_y < y < upper_y:
... | This function checks if the current object collides with any visible bricks in a specified vertical range. If a collision occurs, it triggers a bounce, hides the brick, updates collision state, increments destroyed bricks count, adjusts speed, and returns True. Otherwise, it returns False. | def is_collision_bricks(self, wall: Wall):
y = self.pos()[1]
if wall.y_min - 50 <= y <= wall.y_max + 50:
bricks = wall.bricks
close_bricks = [brick for brick in bricks if self.distance(brick.pos()) < 100 and brick.isvisible()]
for brick in close_bricks:
... |
def is_shop_admin(user, shop):
return user.is_authenticated and shop.admin_group in user.smorteruser.groups.all()
def get_shop_current_cat(shop, query):
cats = get_shop_categories(shop)
return get_deep_dict(cats, query["category"] if "category" in query else [])
def set_shop_admins(shop, admins):
if sho... | This function provides an admin interface for managing a shop, allowing authenticated admins to update shop details via a form. It processes GET/POST requests, validates form data, updates shop information, and renders an admin dashboard template with category navigation, form context, and user data for shop management... | def admin_shop(request, id, tab, item_id=None, *args, **kwargs):
shop = get_object_or_404(Shop, id=id)
if is_shop_admin(request.user, shop):
query = dict(request.GET.lists())
current = get_shop_current_cat(shop, query)
bread = [["".join([f'category={sus}&' for sus in current["path"][:i+1... |
def build_parser():
parser = ArgumentParser()
parser.add_argument('--checkpoint', type=str,
dest='checkpoint_dir',
help='dir or .ckpt file to load checkpoint from',
metavar='CHECKPOINT', required=True)
parser.add_argument('--background... | The main task of the code is to process multiple images by applying a stylization algorithm using specified foreground and background models. It parses command-line arguments, prepares input/output file paths, and invokes the stylize function with parameters like checkpoints, device settings, automatic segmentation, an... | def main():
parser = build_parser()
opts = parser.parse_args()
check_opts(opts)
files = list_files(opts.in_path)
full_in = [os.path.join(opts.in_path,x) for x in files]
full_out = [os.path.join(opts.out_path,x) for x in files]
# multiple dimensions allowed
stylize(in_path=full_in,
... |
def split_rgb(image):
red = None
green = None
blue = None
(blue, green, red) = cv2.split(image)
return red, green, blue
def gauss_pyramid(image, levels):
output = []
output.append(image)
tmp = image
for i in range(0,levels):
tmp = ireduce(tmp)
output.append(tmp)
return output
def lapl_pyrami... | The code blends two images using a mask through multi-scale (pyramid) blending. It reads input images, resizes them, splits RGB channels, constructs Gaussian and Laplacian pyramids for each channel, applies mask-based blending at each pyramid level, collapses the pyramids, clamps pixel values, and saves the final blend... | def image_blend(imageA, imageB, mask, output):
depth = 2
image1 = cv2.imread(imageA)
h = np.size(image1, 0)
w = np.size(image1, 1)
image2 = cv2.imread(imageB)
image2 = cv2.resize(image2, (w, h))
mask = cv2.imread(mask)
mask = cv2.resize(mask, (w, h))
r1= None
g1= None
b1= None
r2= None
g2= None
b2= N... |
def searchNodesByBase(parents_node, search_base_name):
"""This function is used to search all nodes that have Base name only in current parents"""
#Define local variables here
l_parents_node = parents_node
l_srch_base_name = search_base_name
l_base_name_list = []
#Sear all child nodes have giv... | The function recursively extracts data from ARXML containers and sub-containers, creating EcucContainerObj instances to store container metadata, parameters, and nested sub-container hierarchies. It traverses ECUC-PARAM-CONF-CONTAINER-DEF nodes, populates container objects with parameter counts and sub-container lists,... | def getDataFromContainers(container_node, container_object):
"""This function is used to get data from container and its sub-containers in arxml file"""
#Define local variables here
l_container_node = container_node
l_container_object = container_object
l_ecu_container_node = "ECUC-PARAM-CONF-CONTA... |
def node(data):
blank=np.array([])
for i in range(data.shape[1]-1):
blank=np.append(blank,gini_gain(data,i))
g_max=np.max(blank)
arg=np.argwhere(blank==g_max)
return g_max,int(arg[0])
def majority_vote(data):
t=data
un=np.unique(t)
if len(un)==2:
c1=c2=0
for j in ... | This code recursively constructs a decision tree by splitting data into left and right subtrees. At each node, it either assigns a majority vote prediction (if at max depth or pure node) or continues splitting. The tree is built depth-first, with nodes storing predictions and child nodes for further splits. | def recurse(data,n):
#print(n)
index = node(data)[1]
root = decisiontree(index)
if len(data)!=0:
if n==nmax:
predict= majority_vote(data[:,-1])
root.predict = predict
#print(root.predict,'pred')
else:
# n=n+1
if node(data)[0]... |
def _command(self,value):
self.command[0] = 0
self.command[0] |= (value >> 1)
self.command[1] = ((value & 1) << 7)
self.CS.value(0)
self.spi.write(self.command)
self.CS.value(1)
utime.sleep_ms(1)
def on(self, cursor=False, blink=False):
if cursor == False ... | This code initializes an SPI-based display module by configuring pins for communication, setting up SPI parameters based on the selected clock pin, and sending initialization commands to configure the display settings, enable it, clear the screen, and set cursor movement behavior. | def __init__(self,sck,tx,cs):
self.column = 0
self.row = 0
self.data = bytearray(2)
self.command = bytearray(2)
_tx = machine.Pin(tx)
_sck = machine.Pin(sck)
self.CS = machine.Pin(cs, machine.Pin.OUT)
... |
def shouldBid(self):
# If anyone does not have a bid set, we should bid.
for name in self.boardstate['players']:
if self.boardstate['players'][name]['bid'] is None:
return True
return False
def send_all_hide_hands(self):
for name in self.boardstate['players']:... | This code manages a card game's flow by dealing hands, sorting cards, setting trump cards, and transitioning between bidding, playing, and finishing phases. It updates the game state, waits for user input, and handles trick resolution and game progression, ensuring players receive correct card distributions and actions... | def do_next_action(self):
'''
activity (bid, play)
next_to_act (int, id)
hand_num (int)
trump card (Card?)
led card (Card?) # for validation only
players: {
name: {
id (int)
score (int)
bid (int?)
... |
def __streamwrite(self):
"""
__streamwrite
write frame to gstreamer
"""
if not self.Settings.is_streamwrite_colored():
self.wrt_frame = cv2.cvtColor(self.wrt_frame,
cv2.COLOR_BGR2GRAY)
self.__wrt_gst.write(self.wr... | The code's main task is to write outgoing frames, capture incoming frames, and perform preprocessing (skippable via the skip_preprocess parameter), returning the preprocessed result. | def update(self, skip_preprocess: bool):
"""
update
write outgoing frame, get incoming frame and run preprocessing
"""
self.__streamwrite()
self.__streamcap()
return self.__do_preprocess(skip_preprocess) |
def click(self, locator, timeout=None, params=None, key=None):
"""
Click web element
:param locator: locator tuple (ex: locator=(By.ID, 'some_id')) or WebElement instance
:param timeout: (optional) num. of seconds to wait for element
:param params: (optional) locator parameters i... | This function selects an option from a dropdown widget by matching the text of the option. It clicks the dropdown to open it, locates options using provided locators, checks each option's text against the target text, and clicks the matching option. Parameters include locators for the dropdown and options, the target t... | def select_from_drop_down_by_text(self, drop_down_locator, option_locator, option_text, params=None):
"""
Select option from drop down widget using text.
:param drop_down_locator: locator tuple (if any, params needs to be in place) or WebElement instance
:param option_locator: locator tu... |
def control_computational_domain(self):
if "x1" not in self.domain_param.keys():
self.domain_param['x1'] = self.domain_param['X1']
self.domain_param['y1'] = self.domain_param['Y1']
self.domain_param['z1'] = self.domain_param['Z1']
self.domain_param['x2'] = self.do... | The main task of this code is to initialize a computational domain with specified parameters and obstacles. It sets up domain boundaries, processes obstacle placements, calculates domain properties, and determines grid indices for simulation or analysis. The methods called handle controlling the domain, computing its s... | def __init__(self, domain_param, obstacles):
self.domain_param = domain_param
self.obstacles = []
self.domain_boundary_cells = {}
self.control_computational_domain()
self.calculate_domain()
self.calculate_obstacles(obstacles)
self.calculate_indices() |
def SetGame(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mouse_x, mouse_y = pygame.... | The main task of the code is to manage the main menu interface in a Pygame application. It continuously checks for user input events, such as quitting the game (K_1) or exiting (K_2), and triggers game setup or exit actions accordingly. The screen is cleared, the main menu is rendered, and the display is updated in eac... | def mainMenu(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
sel... |
def SetGame(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mouse_x, mouse_y = pygame.... | The main task of the code is to manage a game's main menu loop, handling user input for menu navigation and game initiation. It listens for keyboard events (K_1 to start a game, K_2 to exit), updates the game state, checks for a winner, and renders the main menu interface on a white screen. The loop continuously proces... | def mainMenu(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
sel... |
def setup_wrapper():
flight_id = setup_flight()
booking = {}
booking['passengers'] = [setup_passenger(None) for x in range(3)]
booking = setup_booking(booking, flight_id, get_user(AGENT))
return jsonify({'flight_id':flight_id, 'booking': booking})
def find_flight(id):
flight = db_session.query... | This test verifies that a flight's reserved seats are correctly updated when a booking is added, by asserting the reserved_seats count matches the number of passengers in the booking. It uses setup/teardown to isolate the test, ensuring data consistency. | def test_add_seats(self):
with app.app_context():
test_data = setup_wrapper().json
flight_id = test_data['flight_id']
booking = test_data['booking']
flight = find_flight(flight_id)
self.assertEqual(flight['reserved_seats'], len(booking['passengers']... |
def setup_wrapper():
flight_id = setup_flight()
booking = {}
booking['passengers'] = [setup_passenger(None) for x in range(3)]
booking = setup_booking(booking, flight_id, get_user(AGENT))
return jsonify({'flight_id':flight_id, 'booking': booking})
def find_flight(id):
flight = db_session.query... | This test verifies that removing a booking correctly resets the reserved seats count for a flight to zero. It sets up test data, removes the booking, checks if the flight's reserved_seats is 0, then cleans up the flight data. The main task is to ensure booking removal properly updates flight seat reservations. | def test_remove_seats_by_booking(self):
with app.app_context():
test_data = setup_wrapper().json
flight_id = test_data['flight_id']
booking = test_data['booking']
teardown_booking(booking['id'])
flight = find_flight(flight_id)
self.assert... |
def setup_wrapper():
flight_id = setup_flight()
booking = {}
booking['passengers'] = [setup_passenger(None) for x in range(3)]
booking = setup_booking(booking, flight_id, get_user(AGENT))
return jsonify({'flight_id':flight_id, 'booking': booking})
def find_flight(id):
flight = db_session.query... | This test function verifies that removing passengers from a flight booking correctly decrements the flight's reserved seats count. It initializes test data, iterates through each passenger, checks that the reserved seats match expectations before removal, then decrements the count and tears down each passenger. Finally... | def test_remove_seats_by_passenger(self):
with app.app_context():
test_data = setup_wrapper().json
flight_id = test_data['flight_id']
booking = test_data['booking']
reserved_seats = len(booking['passengers'])
for passenger in booking['passengers']:
... |
def setup_wrapper():
flight_id = setup_flight()
booking = {}
booking['passengers'] = [setup_passenger(None) for x in range(3)]
booking = setup_booking(booking, flight_id, get_user(AGENT))
return jsonify({'flight_id':flight_id, 'booking': booking})
def find_flight(id):
flight = db_session.query... | This test case verifies that deactivating a booking correctly updates the flight's reserved seats to zero. It sets up test data, marks a booking as inactive via the booking service, checks that the flight's reserved seats are reset to 0, then cleans up by removing the booking and flight data. | def test_seats_deactivate_booking(self):
with app.app_context():
test_data = setup_wrapper().json
flight_id = test_data['flight_id']
booking = test_data['booking']
booking['is_active'] = False
BOOKING_SERVICE.set_is_active(booking)
flight... |
def setup_wrapper():
flight_id = setup_flight()
booking = {}
booking['passengers'] = [setup_passenger(None) for x in range(3)]
booking = setup_booking(booking, flight_id, get_user(AGENT))
return jsonify({'flight_id':flight_id, 'booking': booking})
def find_flight(id):
flight = db_session.query... | This test verifies that activating a booking correctly updates the flight's reserved seats. It toggles the booking's active status, checks if reserved seats match passenger count, then cleans up data. | def test_seats_activate_booking(self):
with app.app_context():
test_data = setup_wrapper().json
flight_id = test_data['flight_id']
booking = test_data['booking']
booking['is_active'] = False
BOOKING_SERVICE.set_is_active(booking)
booking['... |
def setup_wrapper():
flight_id = setup_flight()
booking = {}
booking['passengers'] = [setup_passenger(None) for x in range(3)]
booking = setup_booking(booking, flight_id, get_user(AGENT))
return jsonify({'flight_id':flight_id, 'booking': booking})
def setup_flight():
flight = {'route_id': get_... | This test verifies that updating a flight booking correctly adjusts reserved seats: when a booking is moved from one flight to another, the original flight's reserved seats reset to 0, and the new flight's reserved seats match the number of passengers in the booking. | def test_seats_change_flight(self):
with app.app_context():
test_data = setup_wrapper().json
flight_id_1 = test_data['flight_id']
booking = test_data['booking']
flight_id_2 = setup_flight()
flight_bookings = {'booking_id': booking['id'], 'flight_id':... |
def setup_wrapper():
flight_id = setup_flight()
booking = {}
booking['passengers'] = [setup_passenger(None) for x in range(3)]
booking = setup_booking(booking, flight_id, get_user(AGENT))
return jsonify({'flight_id':flight_id, 'booking': booking})
def find_flight(id):
flight = db_session.query... | This test verifies that adding a passenger to a booking correctly increments the reserved seat count on a flight. It sets up test data, links a passenger to a booking, updates the booking, checks if the flight's reserved_seats is 1, then cleans up by removing the flight and booking. | def test_seats_add_passenger(self):
with app.app_context():
test_data = setup_wrapper().json
flight_id = test_data['flight_id']
booking = test_data['booking']
passenger = setup_passenger(None)
passenger['booking_id'] = booking['id']
... |
def setup_wrapper():
flight_id = setup_flight()
booking = {}
booking['passengers'] = [setup_passenger(None) for x in range(3)]
booking = setup_booking(booking, flight_id, get_user(AGENT))
return jsonify({'flight_id':flight_id, 'booking': booking})
def find_flight(id):
flight = db_session.query... | This test method verifies that adding multiple passengers to a flight booking correctly updates the reserved seat count. It sets up test data, creates 10 passengers, adds them via the booking service, checks if the flight's reserved seats match the total passengers (existing + new), then cleans up the test data. | def test_seats_add_passenger_bulk(self):
with app.app_context():
test_data = setup_wrapper().json
flight_id = test_data['flight_id']
booking = test_data['booking']
passengers = [setup_passenger(booking['id']) for x in range(10)]
... |
def load_airtable_config(path):
airtable_config = configparser.ConfigParser()
airtable_config.read(path)
return airtable_config
def connect_to_base(airtable_config):
api = Api(airtable_config['DEFAULT']['api_key'])
return api.get_base(airtable_config['DEFAULT']['base_id'])
def get_flow_run_log_reco... | The main task of the code is to transfer and summarize flow run data from an Airtable "flow-run-log" table to a specified output table. It connects to Airtable using provided credentials, retrieves log records, processes each unprocessed entry to extract flow/task statistics, constructs summary data, and updates the ou... | def add_flow_run_summary(airtable_config_path: str,
output_table_name: str):
airtable_config = load_airtable_config(airtable_config_path)
base = connect_to_base(airtable_config)
flow_run_summary = base.get_table(output_table_name)
flow_run_log = base.get_table("flow-run-log")
... |
def find_code_files(path):
"""Find all of the code files under a path"""
code_files = []
for dirpath, _, files in os.walk(path):
dbg("Entering: %s" % dirpath)
for filename in files:
if filename.endswith(".m") or filename.endswith(".lua"):
dbg(" Found file: %s/%s"... | The code processes code files (`.m`/`.lua`) from specified directories by extracting and organizing docstrings into structured module data. It builds a hierarchical module tree, sorts module items and submodules alphabetically, and returns a sorted list of processed modules with their submodules. | def do_processing(directories):
"""Run all processing steps for one or more directories"""
raw_docstrings = []
codefiles = []
processed_docstrings = []
module_tree = {}
for directory in directories:
codefiles += find_code_files(directory)
if len(codefiles) == 0:
err("No .m/.... |
def dbg(msg):
"""Print a debug message"""
if DEBUG:
print("DEBUG: %s" % msg)
def err(msg):
"""Print an error message"""
print("ERROR: %s" % msg)
sys.exit(1)
def do_processing(directories):
"""Run all processing steps for one or more directories"""
raw_docstrings = []
codefiles = ... | This code parses command-line arguments to generate documentation in various formats (JSON, SQL, HTML, Markdown) from specified directories. It validates inputs, processes documentation data, and writes outputs to designated directories based on user-specified flags. At least one output format and one directory must be... | def main():
"""Main entrypoint"""
global DEBUG
global ARGUMENTS
parser = argparse.ArgumentParser()
commands = parser.add_argument_group("Commands")
commands.add_argument("-v", "--validate", action="store_true",
dest="validate", default=False,
... |
def go_to_center(self):
""" Sends all connected Dynamixels to their center position as specified in the calibration.
Args:
none
Returns:
none
"""
for id in self.dxls.keys():
self.update_goal(id, self.dxls[id].center_pos)
... | The main task of the code is to move a robot to an initial position by loading pre-saved trajectory data from a pickle file. It centers the robot, initializes a flag, loads the trajectory data, maps the initial position, and sends a goal command to start navigation. The function prepares the robot for subsequent moveme... | def go_to_initial_position(self, file_location="actual_trajectories_2v2", file_name="N_2v2_1.1_1.1_1.1_1.1.pkl"):
#try:
self.go_to_center()
sleep(2)
self.flag = True
pickle_length = self.load_pickle(file_location, file_name)
self.map_pickle(0)
self.send_goal()
... |
def break_ICA(array):
ica = FastICA(n_components=12, whiten="unit-variance")
S_ = ica.fit_transform(array.T) # Reconstruct signals
A_ = ica.mixing_ # Get estimated mixing matrix
return S_,A_
def predict_artefact_class(model,data_i):
#normalise the data_i array
#t1=time.time()
mu_i=np.mean(... | The code processes EEG data in sliding windows, updating arrays with new segments, applying ICA decomposition, predicting artifacts using a model, and dynamically updating plots. It shifts data buffers, replaces old segments with new EEG data, and triggers predictions every two iterations, looping until all data is pro... | def loop():
global l,u,c,EEG1,label_EEG1,ica_EEG1
#fig,ax=plt.subplots(6,2,figsize=(20,20))
while True:
updated_array[:,:fs*seconds-int(interval*fs)]=updated_array[:,int(interval*fs):]
updated_array[:,fs*seconds-int(interval*fs):]=EEG[:,l:u]
labels_array[:,:fs*seconds-int(interval*fs... |
def check_for_download(self, data_type):
"""
Check if something has been downloaded and, if not, get it.
:param data_type: What data to check for. Can be: train_labels, train_features, test_labels, test_features,
database, and/or 'classifications'.
"""
if not isinsta... | The main task of the code is to load and preprocess the ICL dataset by combining unprocessed feature-sets (from multiple sources like `.mat` files) with corresponding labels (from `.pkl` or a database), matching them based on identifiers, handling duplicates, cleaning data (removing inf/NaN values), and saving the proc... | def load_data(self):
"""
Load the ICL dataset in an unprocessed form.
Follows the settings provided during initializations
:return: Dictionary of unprocessed but matched feature-sets and labels.
"""
start = time()
# organize info
if self.transform in (Non... |
def check_for_download(self, data_type):
"""
Check if something has been downloaded and, if not, get it.
:param data_type: What data to check for. Can be: train_labels, train_features, test_labels, test_features,
database, and/or 'classifications'.
"""
if not isinsta... | The main task of the code is to load and preprocess the ICL test dataset by reading features from .mat files and labels from .pkl files, matching them via instance IDs, removing invalid data, and normalizing selected features (e.g., topo, psd, dipole) if enabled. It returns processed features, labels, and channel-speci... | def load_test_data(self, process_features=True):
"""
Load the ICL test dataset used in the publication.
Follows the settings provided during initializations.
:param process_features: Whether to preprocess/normalize features.
:return: (features, labels, channel_features)
"... |
def load_data(self):
"""
Load the ICL dataset in an unprocessed form.
Follows the settings provided during initializations
:return: Dictionary of unprocessed but matched feature-sets and labels.
"""
start = time()
# organize info
if self.transform in (Non... | The function `load_semi_supervised` loads and processes a semi-supervised ICL dataset, splitting it into labeled and unlabeled subsets for training, validation, and testing. It normalizes features (e.g., topo, PSD, autocorr) based on specified parameters, shuffles data, and separates labeled/ unlabeled samples. The out... | def load_semi_supervised(self):
"""
Load the ICL dataset where only a fraction of data points are labeled.
Follows the settings provided during initializations
:return: (train set unlabeled, train set labeled, sample test set (unlabeled), validation set (labeled),
output labe... |
def run_image_method(self, prompt, rec_id=False, method=False):
openai_cli = self.get_openai()
method = method or self.method
if self.env.context.get('openai_test'):
number_of_result = 1
else:
number_of_result = self.n or 1
if method == 'create':
... | The main task of the code is to generate images using a prompt retrieved from `rec_id`, handle potential API errors, and create result entries either from base64-encoded image data or URLs. It returns a list of result IDs or a single result based on the response format, ensuring proper error handling and data processin... | def create_image(self, rec_id, method=False):
prompt = self.get_prompt(rec_id)
try:
res = self.run_image_method(prompt, rec_id, method)
except openai.APIError as err:
raise UserError(err.message)
if isinstance(res, bytes):
return self.create_result(re... |
def check_git():
if not which("git"):
error("git command was not found")
if not os.path.exists(".git"):
error("This folder doesn't seem to be the root of a git project.")
def read_config():
global VALID_TYPES
try:
with open(CONFIG_FILE) as file:
for line in file:
... | The main task of the code is to automate a Git workflow for version control. It checks Git status, reads configuration, parses version info, and processes command-line arguments. The script then switches to a main branch, pulls updates, creates a new branch based on type/name, pushes changes, and finalizes the process.... | def main():
check_git()
read_config()
parse_version()
TYPE, NAME, MAIN = parse_arguments()
run_switch_branch(MAIN)
run_pull_main(MAIN)
run_create_main(TYPE, NAME, MAIN)
run_push_branch(TYPE, NAME)
finishes_process() |
def unpack_client_ordered_packet(self):
# unpack data from client
packet, clientAddress = self.serverSocket.recvfrom(1024)
data_len, code, entity = struct.unpack("!IHH", packet[:8])
packet_id = struct.unpack("!I", packet[8:12])[0]
data = packet[12:12+data_len-4].decode()
... | This code listens for UDP packets, processes a specified number of incoming data packets by checking protocol compliance and sending acknowledgments, then generates and transmits a response packet containing random TCP port and code values to the client. | def listen_udp_data(self, repeat):
self.serverSocket.settimeout(Server.timeout)
i = 0
while i < repeat:
data_len, code, entity, data, clientAddress, packet_id = self.unpack_client_ordered_packet()
# check for protocol deviations
self.check_default_deviations(d... |
def _get_first_zaehlpunkt(self) -> (str, str):
zps = self.zaehlpunkte()[0]
customerId = zps["geschaeftspartner"]
zp = zps["zaehlpunkte"][0]["zaehlpunktnummer"]
return customerId, zp
def _dt_string(datetime_string):
return datetime_string.strftime(const.API_DATE_FORMAT)[:-3] + "Z"... | This function retrieves energy consumption data for a customer's smart meter between specified dates, using a given resolution (hourly or 15-minute). It constructs an API request to fetch raw usage data from 'messdaten/CUSTOMER_ID/ZAEHLPUNKT/verbrauch', handling default parameters like date_to and zaehlpunkt. The resul... | def verbrauch(
self,
customer_id: str,
zaehlpunkt: str,
date_from: datetime,
date_to: datetime = None,
resolution: const.Resolution = const.Resolution.HOUR
):
"""Returns energy usage.
This can be used to query the daily consumption for a long period of... |
def _get_first_zaehlpunkt(self) -> (str, str):
zps = self.zaehlpunkte()[0]
customerId = zps["geschaeftspartner"]
zp = zps["zaehlpunkte"][0]["zaehlpunktnummer"]
return customerId, zp
def _dt_string(datetime_string):
return datetime_string.strftime(const.API_DATE_FORMAT)[:-3] + "Z"... | The function retrieves events from a specific smart meter between `date_from` and `date_to` (defaulting to current date if unspecified). If no `zaehlpunkt` (meter ID) is provided, it uses the first meter in the user's profile. It constructs an API query with the specified dates and meter ID, then calls the 'user/ereign... | def ereignisse(
self, date_from: datetime, date_to: datetime = None, zaehlpunkt=None
):
"""Returns events between date_from and date_to of a specific smart meter.
Args:
date_from (datetime.datetime): Starting date for request
date_to (datetime.datetime, optional): End... |
def handle_authentication(self, api: PyiCloudService):
# Two-factor authentication
if api.requires_2fa:
# Request authentication code
code = self.mainWindow.pop_up_2fa() # the code stops here until popup is closed
# If popup was closed without input
... | The code's main task is to authenticate with iCloud using provided credentials, handle authentication challenges, download photos within a date range, and package them into a ZIP file named with date timestamps. It creates a ZIP archive, processes photos via `process_photos`, executes post-import tasks, and logs comple... | def load_photos(self):
# Establish connection to iCloud
try:
api = PyiCloudService(self.appleId, self.pwd, cookie_directory='./log')
except PyiCloudFailedLoginException as e:
log.error(f'Authentication failed: {str(e)}')
return False
# Handle authent... |
def grow(self):
if pygame.mouse.get_pressed()[0] == 1 and self.growing:
self.radius += 0.5
else:
self.growing = False
print(self.radius)
def set_vels(self, planets):
if not self.growing:
for planet in planets:
if planet.id != self.i... | This code updates an object's position and velocity based on planetary interactions, handles growth logic, and renders a white circle at its current position using Pygame. The method is part of a game entity that tracks movement, rendering, and growth states. | def update(self, planets):
if self.growing:
self.grow()
self.set_vels(planets)
self.update_pos()
#print(self.vel, self.pos)
pygame.draw.circle(self.screen, (255,255,255), self.pos, self.radius)
if self.id == 1:
print(self.pos) |
def Jv(T, freq):
return ((h*freq)/k) * (1 / (np.exp((h*freq)/(k*T)) - 1))
def opt_depth(freq, Ntot, T, T_list, log_Q, rest_freq, FWHM, vlsr, Aij, gu, Eup):
""" Compute the Optical Depth """
component1 = (c**2/(8*np.pi*(freq + vel_shift(vlsr, rest_freq))**2))
component2 = (Ntot/Q(T, T_list, log_Q))
... | This function computes the brightness temperature using the radiative transfer equation, incorporating optical depth (tau), cosmic microwave background (J_cmb), background temperature (back_T), and beam dilution (bdf). It calculates the net radiation by subtracting J_cmb and back_T from the Planck function (J) and adju... | def brightness_temp(freq, Ntot, T, FWHM, vlsr, param):
""" Compute the Radiative Transfer Equation with output as Brightness Temperature """
T_list, log_Q, rest_freq, Aij, gu, Eup, back_T, source_size, bmax, bmin = param
J = Jv(T, rest_freq)
J_cmb = Jv(2.726, rest_freq)
tau = opt_depth(freq, Ntot, ... |
def add_round_key(s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
return s
def bytes2matrix(text):
return [list(text[i : i + 4]) for i in range(0, len(text), 4)]
def mix_columns(s):
for i in range(4):
mix_single_column(s[i])
return s
def shift_rows(s):
... | This function encrypts a 16-byte block using AES encryption. It applies the initial round key addition, followed by nine rounds of substitution, shifting, mixing, and key addition operations using preloaded key matrices. The final round omits the mix_columns step. The result is returned as byte data after matrix conver... | def _encrypt_block(self, block):
assert len(block) == 16
block_state = add_round_key(bytes2matrix(block), self._key_matrices[0])
for i in range(1, 10):
add_round_key(
mix_columns(shift_rows(sub_bytes(block_state))), self._key_matrices[i]
)
add_roun... |
def compare(self, service_name: str, service_snapshot: DocumentSnapshot):
"""Return `True` if local and remote service are the same. If not return `False`."""
remote_version = self._get_remote_version(service_snapshot)
local_version = self._get_local_version(service_name)
if local_versio... | The main task of the code is to synchronize local services with Firebase by comparing each local service against Firebase records. It updates or removes services based on comparison results, handles invalid services, and ensures consistency between local and remote data. If a service exists in Firebase but differs, it ... | def read_local_services(self):
"""Read the local services and compare them with the ones in firebase.
Read all the services on the `base_path`.
For each service, if the service is on firebase, compare the services.
Depending on the result of the comparison update the service or do nothi... |
def read_links(filename):
links_array = []
with open(links_parser.optimized_path(f"{links_parser.files_folder}/{filename}"), 'r') as inputfile:
for line in inputfile:
links_array.append(line)
return links_array
def initialize_driver():
file_array = []
with open(links_parser.opti... | The code automates testing of URLs from a file by initializing a web driver, iterating through each link, and checking their validity. It handles timeouts and exceptions, tracking errors and outcomes. Finally, it prints a summary of successful tests, failures, undefined links, and exceptions with percentage breakdowns. | def start_tests():
global errors_links
all_links = read_links('filtered_links.txt')
driver = initialize_driver()
driver.set_page_load_timeout(20)
# driver = 123
for index, link in enumerate(all_links):
if link[-1] == "\n":
link = link[:-1]
try:
check_lin... |
def check_directory_existing_and_create(directory):
directory = optimized_path(directory)
if os.path.exists(directory):
shutil.rmtree(directory) # Clear folder
os.makedirs(directory)
def set_target_domain():
global target_domain
rows = open(optimized_path('prefBrowser.txt'), 'r').readlines... | The code crawls a target website using multithreading to extract internal and external links, stores them in text files, and performs cleanup. It combines links from the main domain and a specific subpath, processes them in parallel, and outputs statistics on the number of URLs crawled. Temporary files are created, dup... | def parse():
global target_domain
start_time = datetime.now()
print(f"Pool count: {THREADS_COUNT}")
check_directory_existing_and_create(files_folder)
domain_to_parse = set_target_domain()
print(domain_to_parse)
# save the external links to a file
with open(optimized_path(f"{files_folde... |
def synchronize(self):
# synchronize simulator's states to actual states
pp.set_joint_positions(self._pb_robot, self._joint_indices, self._actual_joint_state)
def get_end_states(self, position, orien):
# use IK to compute end joint state according to end effector position
gripper_index =... | The function `move_to_pose_goal` plans and executes a motion for a robotic arm to reach a specified end-effector pose. It uses PyBullet for motion planning, computes joint states for the target pose, and generates a trajectory. The trajectory is sent to the robot's controller, which executes it. The function waits for ... | def move_to_pose_goal(self,
end_pose: PoseStamped,
max_plan_time=10.0,
execution_timeout=15.0,
tolerance=0.1,
orientation_constraint=None):
"""
Moves the end-effector to an e... |
def display_inputImage(self, cv2Image):
height, width, channel = cv2Image.shape
bytesPerLine = 3 * width
qImg = QImage(cv2Image.data, width, height, bytesPerLine, QImage.Format_BGR888)
self.preview = QPixmap.fromImage(qImg)
self.preview = self.preview.scaled(self.ui.inputImageGra... | This function handles file path input to display either a video's middle frame or an image in a GUI. It clears previous results, checks the file path, and processes the input based on predefined index settings. For videos, it reads frames, extracts a middle frame, and displays it along with a histogram. For images, it ... | def on_filePathLineEdit_editingFinished(self):
# dir = QDir()
# dir.setPath(self.ui.filePathLineEdit.text())
# if dir.exists():
# print("the path exists")
if self.ui.filePathLineEdit.text():
self.ui.resultTable.clearContents()
self.ui.resultTable.setRowCount(0... |
def get_user_detail(phone_number):
# get item based on primary key of member id
response = table.query(
IndexName='PhoneNumber-index',
KeyConditionExpression=Key('PhoneNumber').eq(phone_number))
newlist = sorted(response['Items'], key=itemgetter('F03'),reverse = True)
newlist = newlist[0]
... | The Lambda function processes incoming events to send transactional SMS messages. It iterates through endpoints, extracts user details, generates messages, sends them via Pinpoint, and logs details in DynamoDB, including message ID, time, and type. The function returns a 200 status upon completion. | def lambda_handler(event, context):
print("event",event)
for key in list(event['Endpoints'].keys()):
print(key)
# print(event['Endpoints'][key]['Address'])
UserId = event["Endpoints"][key]["User"]["UserId"]
# get originat number
origination_number = event["Endpoints"][key... |
def event_loop(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# if enter was pressed switch to game mode and call transition
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
... | The code's main task is to update game elements and render the display. It processes events, updates animations, objects, and timers, then draws the background sky, game level, grid lines, object previews, and UI menu on the display surface, ensuring the game state is visually represented in real-time. | def run(self, dt):
self.event_loop()
# updating
self.animation_update(dt)
self.canvas_objects.update(dt)
self.object_timer.update()
# drawing
self.display_surface.fill('grey')
# display sky first as this is in the background
self.display_sky(dt)
... |
def get_runs_and_names(experiment, n_steps, prompt = "morgana2", fp32_baseline = True, directory = "images", check_for = 0, experiment_flags = None,
baseline = True, adjusted = False, embedding = False, no_flex = False, first = False, flex = False,
shift1 = False, expexp ... | The code processes experimental results by iterating over prompts, experiments, and steps to compute SSIM/MSE metrics, validating directories, and compiling results into structured dataframes. It handles dry runs, p-value comparisons, and merging results for consolidated analysis, returning styled dataframes for visual... | def get_results(experiments = ["M4E3","M3E4"], steps = [400,800], prompts = "morgana2", images_per_run = 64, directory = "images" ,experiment_flags = "ablation",
dry = False, quiet = False, fp32_baseline = True, plus = -1, with_margin = False,
pvals = [], customs = [], merge = False, f... |
def init_data():
connection = psycopg2.connect(user='postgres', password='cts-0000', host='127.0.0.1', port='5432', database='oid')
root_dir = os.path.abspath(os.path.dirname(__file__))
cursor = connection.cursor()
cursor.execute("select * from datasetbbox250") ... | The function processes and prepares object detection data by initializing input data, generating a ground truth roidb (region of interest database), filtering it, ranking entries by ratio, and determining the maximum number of ground truth boxes. It returns labels, class counts, processed roidb, ratio metrics, and the ... | def ret_oid_data():
img_names, imgbbox, img_size, labels, num_classes, keyed_parent, keyed_child, classdict = init_data()
gt_roidb = gt_oid_roidb(img_names, imgbbox, img_size, keyed_parent, keyed_child, classdict)
gt_roidb = filter_roidb(gt_roidb)
ratio_list, ratio_index = rank_roidb_ratio(gt_roidb)
... |
def get_trace(
self,
sweep: int
):
# Read trace from abf
trace = utils.read_sweep(
abf=self.abf,
sweep=sweep,
channel=0
)
# Sample trace if required
if self.sampling_rate:
trace = utils.sample_series(trace, self.... | This function calculates the half-width duration of the first action potential (AP) in a given sweep. It identifies the midpoint between the AP's peak amplitude and threshold, then determines the time interval between when the signal crosses this midpoint upward (start) and downward (end), returning the duration as hal... | def find_half_width(
self,
sweep
):
trace = self.get_trace(sweep)
rate = self.get_rate(sweep)
ap_threshold = self.find_ap_threshold(sweep)
aps = self.find_ap(sweep)
# Difference between the first action potential
# maplitude and threshold
half_... |
def is_hindered(self, n1, n2) -> bool:
"""
Determines if binding two species would be sterically hindered.
:param n1: node 1 (species 1)
:param n2: node 2 (species 2)
:return:
"""
node_set1 = set(n1[1]['struct'].nodes())
node_set2 = set(n2[1]['struct'].nod... | The code constructs a reaction network by iteratively expanding nodes through interactions, checking hindrance, and generating new nodes via match_maker. It adds default observables for monomers and final structures, ensuring the network's completeness. | def resolve_tree(self):
"""
Build the full reaction network from whatever initial info was given
:param is_one_step:
:return:
"""
new_nodes = list(self.network.nodes(data=True))
while len(new_nodes) > 0:
node = new_nodes.pop(0)
for anode in... |
def strip_everything_in_lst(lst):
for i in range(len(lst)):
if type(lst[i]) != float:
lst[i] = lst[i].strip()
return lst
def get_country_info(path="data/target country.xlsx"):
df = pd.read_excel(path)
target_country_name, target_country_code, target_country_type = get_country_name(df... | This function cleans and filters rows in a DataFrame based on specified target countries or codes. It checks if the country column contains codes (3 characters) or names, then appends matching rows to a new DataFrame. Missing countries trigger warnings and placeholder entries. Finally, it removes unused columns from th... | def clean_data_by_rows(df, sheet_name):
r_df = pd.DataFrame()
country_title = df.columns.ravel().tolist()[0]
country_in_df = strip_everything_in_lst(df[country_title].tolist())
target_country, target_code, _ = get_country_info()
# Check it is country name or country code
if len(country_in_df[1])... |
def change_label(self):
self.banter.setText(self.temp_string)
self.banter.setStyleSheet(
f"""
background-color: rgba(0, 0, 0, 0);
color: {self.temp_color};
"""
)
def add_score(self, p, x, y):
if p == 1:
self.player1[x+1] += 1
... | This code handles mouse clicks to place a game piece in a grid-based board. When the left mouse button is pressed, it identifies the clicked column, finds the lowest empty row, updates the board with the current player's piece (1 for red), triggers UI updates, increments the score, switches turns, and disables initial ... | def mousePressEvent(self, event):
if self.start == 1:
self.temp_color = 'rgba(0, 0, 0, 0)'
self.change_label()
if event.button() == Qt.LeftButton:
x = event.pos().x()
y = event.pos().y()
# Check which circle was clicked
for col in ... |
def _print(self, args):
if not args:
super().error(ErrorType.SYNTAX_ERROR,"Invalid print call syntax", self.ip) #no
out = []
for arg in args:
val_type = self._get_value(arg)
out.append(str(val_type.value()))
super().output(''.join(out))
def _advance_to_next_statement(self):
# for n... | This code handles built-in function calls in an interpreter. It checks for a function name, executes print/input/strtoint functions by calling private methods, pops the environment scope, advances the instruction pointer, or handles user-defined functions by setting return addresses. The TODO notes a need for cleaner s... | def _funccall(self, args):
if not args:
super().error(ErrorType.SYNTAX_ERROR,"Missing function name to call", self.ip) #!
# TODO: after built-in functions (print, input, etc) are run, the env_manager
# pops the most recent scope manually since the IP doesn't run into any
# returns in the code... |
def _compute_indentation(self, program):
self.indents = [len(line) - len(line.lstrip(' ')) for line in program]
def _find_first_instruction(self, funcname, args=[]):
func_info = self.func_manager.get_function_info(funcname)
if func_info == None:
super().error(ErrorType.NAME_ERROR,f"Unable to locate {f... | This code executes a program by initializing components like environment and function managers, tokenizing input, and processing each line in a loop to handle variables, functions, and control flow until termination. | def run(self, program):
'''
Run a program, provided in an array of strings, one string per line of source code.
'''
self.program = program
self.env_manager = EnvironmentManager() # used to track variables/scope
self._compute_indentation(program) # determine indentation of every line
self.to... |
def SimpleBooleanQuery(self, query: str):
# Preprocess and convert the tokens to their respective IDs
__tokens_to_id = self.TokensToId(
self.PreprocessQuery(query), self.GetTokenDictionary(self.id_token_dict_path))
__positional_indexes = self.GetPositionalIndex(__tokens_to_id)
... | The code defines a method `ResolveQuery` that selects and executes different query resolution strategies based on the input `option` parameter. If `option` is 0, it uses a simple boolean query; if 1, a complex boolean query; and if 2, a proximity query. The method acts as a dispatcher, routing the query to the appropri... | def ResolveQuery(self, query: str, option: int):
if option == 0:
return self.SimpleBooleanQuery(query)
elif option == 1:
return self.ComplexBooleanQuery(query)
elif option == 2:
return self.ProximityQuery(query) |
def _get_indices(self, est, samples):
""" Tree based learning algorithms only """
indices_ar = []
dec_paths = est.decision_path(samples)
for i in range(0, len(samples)):
indices_ar.append(dec_paths.indices[dec_paths.indptr[i] : dec_paths.indptr[i + 1]])
return np.arr... | This function processes individual trees in an ensemble model (e.g., random forest) by iterating over samples, analyzing tree structure via indices, and performing operations on each sample. It tracks processing time and operations for diagnostics, enabling progress tracking and performance analysis during tree-based l... | def _process_est_tree(
self,
tree_num,
est,
samples,
feature_used_list_all_trees,
last_feature_used_list_all_trees,
show_progress_after_each=-1,
show_diagnostics_flag=False,
):
""" Tree based learning algorithms only """
startTree = in... |
def preprocess_data(filename, train_size, split_seed, feature_names, label_name=['Class']):
"""Encapsulating all the work done insofar.
Taking as input the filename, the relative
size of the training set, the seed for the
random reshuffling and the names we are willing to give to the columns... | The main task of the code is to compare the performance of three classifiers—Logistic Regression, K-nearest Neighbors (KNN), and Naive Bayes—on a dataset from 'TP1-data.csv'. It preprocesses data, trains each model with cross-validation, evaluates their confusion matrices, and applies Mc Nemar's test to statistically c... | def main():
filename= 'TP1-data.csv'
feature_names= ['Variance', 'Skewness', 'Curtosis', 'Entropy']
train_size= 2./3.
split_seed= 10182017
kfolds= 5
cv_seed= 52222
logistic_iterations= 20
knn_max= 40
max_h= 1
kernel = 'gaussian'
# Load and preprocess data
X_train, X_... |
def open_Chrome(self):
subprocess.Popen("chrome.shortcut",shell=True)
time.sleep(5)
pyautogui.hotkey('alt', 'space', 'x')
def open_website(self):
time.sleep(10)
pyautogui.write("https://olympus.greatlearning.in/dashboard")
time.sleep(1)
pyautogui.press('enter')
... | The code automates a browser session to join a Zoom meeting via Chrome. It opens Chrome, navigates to a website, interacts with elements (clicks, scrolls), joins a session, waits for 120 seconds, and exits Zoom. Exception handling ensures error logging. | def do(self):
try:
self.open_Chrome()
self.open_website()
self.ongoing_click()
self.scroll()
self.join_session_click()
self.checking_zoom()
time.sleep(120)
self.closing_zoom()
except Exception:
se... |
def canvasSetup(self):
self.master = tkinter.Tk()
self.master.title('Tic-Tac-Toe: Edward Chang. Name/ I.P./ Port')
self.master.geometry('700x500')
def uiVar(self):
self.r11 = tkinter.StringVar()
self.r12 = tkinter.StringVar()
self.r13 = tkinter.StringVar()
self.r2... | This code initializes a game server's UI components, setting up a board, server socket, and various interface elements like buttons, labels, and status displays. It prepares the graphical interface and server-related variables, then launches the UI to manage game interactions and client-server communication. | def __init__(self):
self.serverSocket = None
self.clientQuit = False
self.board = gameboard.BoardClass()
self.canvasSetup()
self.uiVar()
self.createButtons()
self.statLabel()
self.serverInfo()
self.miscButtons()
self.runUI() |
def recent_ema_crossovers(company_symbol, company_data, age=7, short_ema=10, long_ema=50):
result = ema_crossovers(company_data, short_ema, long_ema)
result['company'] = company_symbol
recent_results = result[result['date'] > (datetime.now() - timedelta(age)).date()].copy()
recent_results['type'] = 'em... | The main task of the code is to scan financial markets for companies based on specified technical indicators (e.g., EMA crossovers, volume peaks, RSI thresholds, Bollinger Bands). It processes each company's stock data, filters signals using the indicators, aggregates results, removes duplicates, and returns a consolid... | def market_scan(indicators):
companies = CompanyModel.get_company_list()
flags = pd.DataFrame(columns=['company', 'date', 'info','info_label', 'type', 'filter'])
age = 7
result = pd.DataFrame(columns=['company', 'date', 'info', 'info_label', 'type'])
for company in companies:
company_data = ... |
def get_creds():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
"""
if not os.path.exists(CRED_DIR):
os.makedirs(CRED_DIR)
store = oauth2client.file.Storage(CR... | The main task of the code is to authenticate with Gmail API, retrieve messages matching a user query, process (likely delete) them, and count the total number of deleted messages. It uses credentials for authorization, fetches messages in batches, processes each batch, and reports the cumulative count of deleted messag... | def main(args):
"""Main entry point"""
credentials = get_creds()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
tally = 0
for messages in get_messages(service, USER_ID, args.query):
if not messages:
print('Recieved no new me... |
def train_dataloader(self):
transform = transforms.Compose([
transforms.Resize((self.args.frame_H, self.args.frame_W)),
transforms.ToTensor()
])
dataset = Dataset_Dance(root=self.args.DR, transform=transform, mode='train', video_len=self.train_vi_len, \
... | This code trains a model over multiple epochs using teacher forcing and KL annealing. It iterates through training data, computes loss, updates progress bars with metrics, validates periodically, adjusts learning rates, and saves checkpoints. The process includes dynamic teacher forcing control, KL divergence annealing... | def training_stage(self):
for i in range(self.args.num_epoch):
train_loader = self.train_dataloader()
adapt_TeacherForcing = True if random.random() < self.tfr else False
for (img, label) in (pbar := tqdm(train_loader, ncols=120)):
img = img.to(se... |
def _update_linesize(self):
try:
readline_proc = subprocess.run(['llvm-mutate', '-I'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
input=self._srcEnc,
... | This code initializes an object to handle source code edits for compilation, setting attributes like GPU configuration (mgpu) and architecture (mattr). It processes provided edits, decodes them, and updates the source code accordingly. If no edits are given, it initializes default structures. The class likely supports ... | def __init__(self, srcEnc, mgpu, edits=None, mattr="+ptx70"):
# default compilation argument to Nvidia pascal architecture.
self.mgpu = mgpu
self.mattr = mattr
self._srcEnc = srcEnc
self._lineSize = 0
if edits is None:
self._edits = []
self._serial... |
def parseInput(file):
with open(file, "r") as inputFile:
floor = []
for _, line in enumerate(inputFile):
# add a buffer edge to avoid boundary issues
floorLine = [9]
floorLine.extend([int(x) for x in line.strip()])
floorLine.extend([9])
f... | The main task of the code is to process input data from two files, validate solutions for Part 1 and Part 2 using test cases, compute results for the actual input, and print the final answers. It parses input files, runs assertions against expected test outputs, and outputs the computed solutions for both parts of a pr... | def main():
testFloor = parseInput("./day09/test.txt")
inputFloor = parseInput("./day09/input.txt")
assert(part1(testFloor)==15)
result1 = part1(inputFloor)
print(f"Part 1 solution: {result1}")
assert(part2(testFloor)==1134)
result2 = part2(inputFloor)
print(f"Part 2 solution: {resu... |
def edit_game(self, game_treeview):
selected_item = game_treeview.selection()
if selected_item:
item_values = game_treeview.item(selected_item, "values")
selected_game_id = item_values[0]
selected_game = self.collection_manager.get_item_by_id(selected_game_id, self.t... | The main task of the code is to create a GUI tab for managing game data, displaying it in a scrollable table with columns like ID, Name, Date, etc. It includes CRUD operations (Add/Edit/Delete/Show All), a search feature, and proper layout using Tkinter's ttk widgets. | def create_game_tab(self):
self.table_name = 'games'
key = 'recent'
self.game_frame = ttk.LabelFrame(self.game_tab, text=f"{self.recent_all_labels[key]} Games")
self.game_frame.pack(fill="both", expand=True, padx=10, pady=10)
# Using Treeview to display games as a table
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.