dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def getnearmarket(self,longi, lati):
markDistqry = mydb.cursor()
market_name = []
dist = []
markDistqry.execute("select * from markets")
n=0
for row in markDistqry:
#print(row)
market_name.append(row[0])
M_lati = float(row... | This function registers a crop using a seed packet (UNC) by updating its status, associating it with a mobile number, recording sown date, location, yield date, and nearest market. It checks database availability, validates the UNC, updates records, and displays registration confirmation with crop details. | def on_pushButton_CropRegister_clicked(self,mobileno,unc):
#unc = self.GetRandomUNC()
# uncString = str(unc)
crop = ""
acers = 0
#unc = 103
#mobileno = self.GetMObileNo()
SownDate = QDate.currentDate()
#SownDate = datetime.date.today()
... |
def get_previous_weeks(cur, tablename, collect_date):
"""Gets all weeks previous (including current) collection date if any
Arguments:
cur (cursor object): a Psycopg cursor object.
tablename (string): name of any of the three relations:
hospital_info, hospital_data, ... | The function `get_covid_change` ranks U.S. states or hospitals by the change in COVID-19 cases between a specified date and the prior week. It retrieves data from a database, calculates weekly case differences, and returns a sorted table of top `nshow` entries. If no data exists for the specified date, it returns `Fals... | def get_covid_change(conn, collect_date, nshow, property):
"""Rank the states/hospitals by the number of cases since the last week
Arguments:
conn (connection object): a Psycopg connection object.
collect_date (datetime.date): collection date of interest
nshow (int): number of observati... |
def clone(self, name, ow=False, update=False):
"""
Clone a remote directory into the store.
:param name: Name of repository
:param ow: OverWrite, bool, if True will remove any existing directory in the location.
:return: (string): Path to cloned repository
"""
if ... | The code builds a SkilletCollection instance by cloning a git repository if necessary, then processes its directory structure to organize snippets into type-specific stacks. It expects predefined folder hierarchies, extracts metadata, and populates the collection with snippets grouped by their 'type' metadata, ensuring... | def build(self):
"""
Build the Skillet object using the git repository.
Must be called after clone.
:return: SkilletCollection instance
"""
if not self.Repo:
self.clone(self.name)
# The following section is all hard coded pointers to important stuff... |
def Darknet(size=None, act_fn='leaky', name=None, batch_size=None):
cnt=0
x = inputs = Input(shape=[size, size, 3], batch_size=batch_size, name=name+'_input')
x = DarknetConv(x, filters=32, size=3, act_fn=act_fn, name=name+'_'+str(cnt))
cnt+=1
x = DarknetBlock(x, filters=64, blocks=1, act_fn=act_fn,... | The code defines a YOLOv3 object detection model, constructing a neural network with Darknet backbone, multi-scale feature extraction, and YOLO-specific output layers. It handles mixed precision training, adjusts anchors for input size, and applies non-max suppression (NMS) for final detection outputs. The model return... | def YoloV3(size=None, channels=3, anchors=yolo_anchors,
masks=yolo_anchor_masks, classes=80, training=False,
mixed_precision='float32', batch_size=None):
if mixed_precision=='float16':
policy = tf_mixed_precision.Policy('mixed_'+mixed_precision)
tf_mixed_precision.set_pol... |
def portfolio(start, end, df, mydict):
cnames = st.sidebar.multiselect("Select Company By Name", (df['Name']), default=(df['Name'][0]))
assets = []
nop = st.sidebar.number_input("Select No Of Portfolio's", min_value=50, max_value=25000)
if (cnames == None):
st.error("Select Atleast One Company")... | The code creates a Streamlit app displaying Indian stock market info (BSE/NSE) and allows users to select analysis methods: Portfolio Optimization, Future Price Prediction, Company Overview, or Trading Strategies, using data from an Excel file. It handles date inputs, validates them, and executes corresponding function... | def main():
#df=load_workbook('ticker.xlsx')
df = pd.read_excel('ticker.xlsx',engine='openpyxl')
st.header('Indian Stock Market')
st.subheader('The BSE and NSE')
st.write("Most of the trading in the Indian stock market takes place on its two stock exchanges: "
"the Bombay Stock Exchang... |
def get_highlightable_coordinates():
coordinates = [[524,802],[667,790],[1023,941],[758,962]] # for highlighting the crosswalk
return np.array(coordinates)
def parse_xml(xml_file):
final_arr=[]
tree= ET.parse(xml_file)
root = tree.getroot()
for object in root.findall('object'):
arr=[]
... | The main task of the code is to detect and track pedestrians in image sequences, analyze their movement patterns (e.g., crossing roads/crosswalks), generate visualizations, and store trajectory data in a SQLite database. It processes XML-labeled images, tracks individuals across frames using re-identification, classifi... | def main(interval = -1, date = None, plot = False, initial=True):
image_list=[] # Array the hold the new images created from this script
date_arr=[]
new_file_path = ""
# Made everything global because it needs to be imported in plot_object_detection so we can keep data across hours/whole day
globa... |
def net_c_dyn(self, x1, x2, t):
c = self.forward_pass(tf.concat([x1, x2, t], 1),
self.layers_c,
self.weights_c,
self.biases_c)
return c
def net_v1(self, x1, x2):
beta = self.scale_X
k = self.net_k(x1, x2)
h = self.net_h(x1, x2)
v1 = -k*tf.gradients(h, x1)[0] * beta[0]
return ... | This code computes the difference between the left-hand side (LHS) and right-hand side (RHS) of a partial differential equation (PDE) involving a dynamic coefficient field. It calculates gradients of a neural network output `c` with respect to spatial variables `x1`, `x2`, and time `t`, combines them with velocity term... | def net_AD_dyn(self, x1, x2, t):
Dw = self.Dw
tau = self.tau
aL = self.aL
aT = self.aT
phi = self.phi
# beta = self.scale_X
beta = self.scale_Xt
# k = self.net_k(x1, x2)
# h = self.net_h(x1, x2)
c = self.net_c_dyn(x1, x2, t)
v1 = self.net_v1(x1, x2)
v2 = self.net_v2(x1, x2)
dc_x1 = ... |
def calculate_averages(data):
"""
Calculates monthly and yearly averages
Returns a tupple of 2d lists of monthly and yearly averages in form of [[DateObject, price], etc]
:param data: [["date", "adj_close", "volume"],...]
:return: (monthly_averages, yearly_averages)
"""
# data = [["date", "a... | The code fetches stock data from a user-provided URL or default source, calculates monthly and yearly average values, visualizes the results using matplotlib, and displays the top 6 best and worst performing months/years based on the computed averages. | def main():
DEFAULT_URL = "http://193.1.33.31:88/pa1/GOOGL.csv"
query = input("Insert company name or link to csv file or leave blank for default ")
if query == "":
query = DEFAULT_URL
monthly_average, yearly_average = calculate_averages(get_and_parse_stock(query))
plot_data(monthly_average... |
def parse_users_to_string(is_change: bool, user_type: str) -> str:
"""
Parse assignees or reviewers to a string of usernames
:param is_change: bool: has user list updated
:param user_type: str: reviewer or assignee
:return: A string of users: @username, @username
"""
current = []
try:
... | This function generates Slack message blocks for a new merge request (MR) notification. It constructs sections with MR status, branches, project details, and assignees/reviewers using input data, formatting the message to include user info, links, and formatted metadata for Slack display. | def parse_request_to_nm_blocks(data: Dict, slack_id: str, mr_is_ready: bool) -> []:
""""
Generate Blocks for the new MR message
:param mr_is_ready: Draft was marked as ready
:param slack_id: str: Slack user id
:param data: Dict: request data
:return Slack message blocks for a new MR message
... |
def send_alert():
ifttt_key = os.getenv("IFTTT_KEY")
if ifttt_key:
url = f"https://maker.ifttt.com/trigger/reminder/with/key/{ifttt_key}?value1=X&value2=F8started"
cmd = ["curl", "--silent", "-X", "POST", url]
run_cmd(cmd)
else:
log_print("IFTTT_KEY not present, not sending a... | The function attempts to access a boot device menu by repeatedly sending the F8 key (common for boot selection) over 5 tries, with delays between attempts. It logs each key press, sends the key via byte sequence, releases keys, and pauses to allow the system to process input, likely for systems requiring manual boot me... | def get_into_boot_device_menu_selection():
send_alert()
count = 5
for i in range(0, count):
log_print(f"Sending key F8")
send_bytes(NULL_CHAR*2+chr(KEYB_F8)+NULL_CHAR*5)
releaseKeys()
time.sleep(1) |
def get_into_boot_device_menu_selection():
send_alert()
count = 5
for i in range(0, count):
log_print(f"Sending key F8")
send_bytes(NULL_CHAR*2+chr(KEYB_F8)+NULL_CHAR*5)
releaseKeys()
time.sleep(1)
def typeEnter():
send_bytes(NULL_CHAR*2+chr(40)+NULL_CHAR*5)
release... | The main task of the code is to execute a boot sequence by navigating into the boot device menu selection and pressing the Enter key to proceed. It handles potential errors during this process, logging any UserError exceptions. The function aims to automate selecting a boot option, though some steps like delaying or us... | def do_boot_sequence_with_keys():
try:
#log_print("Sleeping 2 secs")
#time.sleep(2)
get_into_boot_device_menu_selection()
# Possible move selection down with arrow keys. Not now though.
typeEnter()
except UserError as err:
log_print(f"Error: {err}") |
def log_print(text):
# Get the current time
now = datetime.now()
# Format the timestamp without milliseconds
formatted_timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
# Print the formatted timestamp
print(formatted_timestamp + " " + text)
def wait_until_pc_boots(last_boot_time_epoch):
log_pr... | The main task of the code is to repeatedly wait for a PC to boot, execute a boot sequence with specific key presses, and loop until manually aborted. It logs timestamps and status updates, with a 5-second delay between boot attempts to allow BIOS menu interaction. | def main():
last_epoc_time = 0
while True:
nowtime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_print("")
log_print(f"Waiting for PC to boot... Time is {nowtime}")
result, last_epoc_time = wait_until_pc_boots(last_epoc_time)
if result == USER_ABORT:
lo... |
def reset(self):
done = th.ones(self.num_env, dtype=bool, device=self.device)
prv_obs = self.env.reset()
core_state = self.state_encoder.initial_state(
batch_size=self.num_env)
core_state = tuple(s.to(self.device) for s in core_state)
self._save_values(
do... | The code trains a model for `num_steps` iterations, logging metrics like loss and reward using TensorBoard. It performs learning steps, tracks gradients, and saves checkpoints periodically. The main task is to iteratively train the model, monitor progress, and store intermediate results for analysis or resuming trainin... | def learn(self,
num_steps: int = 1000,
log_dir: str = './log',
save_steps: int = 100):
"""Learn for `num_steps` iterations.
NOTE(ycho): actual number of env-steps
= num_steps X num_interactions X num_envs.
"""
self.reset()
writer... |
def get_text_from_file(filename):
with open(filename, encoding='UTF-8', mode='r') as f:
text = f.read()
return text
def get_sorted_res(query, input_sav_file, input_csv_file):
# process the query
query_term_frequency_dict = dict(Counter(get_words_from_text(query)))
file = open(input_sav_fi... | (The code calculates the Mean Average Precision (MAP) by comparing system-generated retrieval results against gold-standard relevance scores. It reads query results from a file, groups them by query ID, processes each query's text to obtain retrieved results, computes Average Precision (AP) for each query, and returns ... | def calculate_MAP(input_query_path,input_query_res_file,input_sav_file,input_csv_file):
AP_list = []
with open(input_query_res_file, 'r', encoding='UTF-8') as f:
lines = f.read().splitlines()
j = '1'
res_gold = []
res_gold_list = []
for i in lines:
temp = i.split()
i... |
def check_defined(reference, reference_name):
if not reference:
raise Exception('Error: ', reference_name, 'is not defined')
return reference
def get_configuration_item(invoking_event):
check_defined(invoking_event, 'invoking_event')
if is_oversized_changed_notification(invoking_event['messageTy... | This code processes an AWS Config event to check resource compliance. It extracts event data, determines applicability, invokes a compliance check, constructs evaluation results, and reports them to AWS Config via the put_evaluations API, returning the compliance status. | def handler_wrapper(event, context):
check_defined(event, 'event')
invoking_event = json.loads(event['invokingEvent'])
rule_parameters = {}
if 'ruleParameters' in event:
rule_parameters = json.loads(event['ruleParameters'])
configuration_item = get_configuration_item(... |
def channel_gH_bar(user_loc, ris_loc):
"""
Return:
gH_bar: (ris_dim_flat, )
"""
gH_bar_power = np.zeros(ris_dims)
for hori_id in range(ris_dims[0]):
for vert_id in range(ris_dims[1]):
gH_bar_power[hori_id, vert_id] = np.pi * (hori_id*(user_loc[1]-ris_loc[1])
... | The function `deriv_ris_coeff` computes the derivative of a coefficient (likely related to channel gain or signal propagation) with respect to a user's location. It combines channel response terms, distance-dependent attenuation, logarithmic factors, and a summation involving the coefficient array to derive a gradient.... | def deriv_ris_coeff(user_loc, ris_loc, coeff, slot):
"""Derivation to one of coefficient w.r.t a user"""
term = channel_gH_bar(user_loc, ris_loc)*channel_f_bar(ris_loc)
res = slot / (np.log(2)*log_real_part(user_loc, ris_loc, coeff)) *\
const2*ris_bs_dist(ris_loc)**(-gamma_f)*user_ris_dist(user_loc,... |
def channel_gH_bar(user_loc, ris_loc):
"""
Return:
gH_bar: (ris_dim_flat, )
"""
gH_bar_power = np.zeros(ris_dims)
for hori_id in range(ris_dims[0]):
for vert_id in range(ris_dims[1]):
gH_bar_power[hori_id, vert_id] = np.pi * (hori_id*(user_loc[1]-ris_loc[1])
... | This function computes the derivative of the squared magnitude of a complex term involving channel responses and coefficients. It calculates intermediate terms using channel functions and their derivatives, combines them to derive a result, and returns the real parts of the computed derivative in a 3-element array. | def abs2_deriv(user_loc, ris_loc, coeff):
g_f_deriv = (channel_gH_bar(user_loc, ris_loc)*channel_f_bar(ris_loc)*1j)[np.newaxis, :] *\
(delta_f_deriv(ris_loc) + delta_g_deriv(user_loc, ris_loc))
term = np.sum(channel_gH_bar(user_loc, ris_loc)*
channel_f_bar(ris_loc)*coeff) ## sca... |
def cap_ub(ris_loc, user_slots, ris_coeff):
"""Capacity upper bound.
Args:
user_slots: (nums, )
ris_coeff: (nums, ris_dim_flat)
"""
acc = 0
for user_id, user_loc in enumerate(user_locs):
acc += user_slots[user_id] * \
np.log2(log_real_part(user_loc, ris_loc, ris_... | The code implements a cyclic coordinate descent algorithm with adaptive step sizes to optimize the positioning of a Reconfigurable Intelligent Surface (RIS), user slot allocations, and RIS reflection coefficients. The goal is to maximize the upper bound of communication capacity by iteratively updating each parameter u... | def cyclic_descent(adaptive=True):
"""Coordinate descent algoritm by adaptive steps.
Return:
ris_loc, user_slots, ris_coeff
"""
lr, tole, smooth = 1, 10**(-2), 10**(-8)
ris_loc = ris_center + np.array([0, rect_length/2, rect_width/2])
user_slots = np.ones(user_locs.shape[0])/user_locs.... |
def get_current_cast_per_day(day_statuses, keep_drop=None):
if keep_drop:
current_cast_per_day = {day: sum([len([(piece_name, piece_status, piece_rank) for piece_name, piece_status, piece_rank in status if piece_status == 'cast' and keep_drop[piece_name] == 'keep']) != 0
... | The function adjusts the 'keep_drop' dictionary to ensure a dancer's casting adheres to maximum day and dance constraints. It evaluates current casting validity, drops excess casts based on rank metrics, and finalizes waitlist entries, returning the optimized 'keep_drop' with valid constraints. | def keep_drop_finalize(current_pref, day_statuses, keep_drop):
# get cast_per_day using the default keep_drop (i.e. same time dropped)
current_cast_per_day = get_current_cast_per_day(day_statuses=day_statuses, keep_drop=keep_drop)
if max(current_cast_per_day.values()) == 0:
return keep_drop
# f... |
def keep_drop_default(current_pref, dancer_statuses, metadata):
keep_drop = {piece: 'keep' for piece in current_pref['prefs'] if dancer_statuses[piece]['status'] in ['cast', 'waitlist']}
day_statuses = {'Sunday': [[], [], []], 'Monday': [[], [], []], 'Tuesday': [[], [], []], 'Wednesday': [[], [], []], 'Thursda... | The function `get_keep_drop` determines dancer retention/drop decisions in two modes: first, a "finalize" mode using default and finalization logic, then a "standard" mode that applies either a single-dance or iterative algorithm based on `max_dances` preference. It returns results for both modes, including timing for ... | def get_keep_drop(current_pref, dancer_statuses, metadata):
# first run in finalize mode
final_keep_drop, day_statuses = keep_drop_default(current_pref=current_pref, dancer_statuses=dancer_statuses, metadata=metadata)
final_keep_drop = keep_drop_finalize(current_pref=current_pref, day_statuses=day_statuses,... |
def files_exist(files):
return all([osp.exists(f) for f in files])
def makedirs(path):
try:
os.makedirs(osp.expanduser(osp.normpath(path)))
except OSError as e:
if e.errno != errno.EEXIST and osp.isdir(path):
raise e
def download(self):
path = download_url('{}/{}.zip'.for... | This method checks if required files already exist at `self.raw_paths`; if not, it creates the directory `self.raw_dir` and initiates a download process via `self.download()`, ensuring files are only downloaded when necessary. | def _download(self):
if files_exist(self.raw_paths):
return
makedirs(self.raw_dir)
self.download() |
def make_folds(data_group):
all_folds = [(data_group + '_A', data_group + '_B', data_group + '_C'),
(data_group + '_A', data_group + '_C', data_group + '_B'),
(data_group + '_B', data_group + '_A', data_group + '_C'),
(data_group + '_B', data_group + '_C', data_gro... | The main task of the code is to perform cross-validation on a dataset using a specified classifier, evaluate its performance across multiple folds, and aggregate metrics like UAR, WAR, recall, precision, and confusion matrices. It processes each fold, runs experiments, updates results, and calculates average performanc... | def run_main_function(data_group, results, ALL_dics, num_class, classifier, N_functionals, all_results):
all_folds = make_folds(data_group)
UAR = 0
WAR = 0
rec_ANT = 0
rec_HOM = 0
rec_CON = 0
rec_MIX = 0
pre_ANT = 0
pre_HOM = 0
pre_CON = 0
pre_MIX = 0
conf_matrix ... |
def get_random_split(features, split):
random.seed(split)
print('SPLITTING IN 3-FOLDS')
composers = features['composer'].unique().tolist()
print(composers)
random.shuffle(composers)
print(composers)
A = composers[0:10]
B = composers[10:20]
C = composers[20:30]
return A, B, C
def ... | The function sets up and executes machine learning experiments using a specified classifier (SVM/MLP) on functional data, partitioning features and running splits. It processes data groups, computes results, averages outcomes, and saves outputs in CSV files. The task involves configuring experiments, managing directori... | def set_up(classifier, num_class, list_excluded2, num_feat):
"""
num_class = 3 (ANT, CON, HOM); 2 (CON, HOM); 4 (CON, HOM)
classifier = 'SVM', 'MLP'
"""
data_group = ['all_flat']
splits = [41, 2, 25, 28]
all_results = {'all_flat': {}, 'canto': {}, 'alto': {}, 'quinto': {}, 'tenor': {},... |
def make_folds():
all_folds = [('_A', '_B', '_C'),
('_A', '_C', '_B'),
('_B', '_A', '_C'),
('_B', '_C', '_A'),
('_C', '_B', '_A'),
('_C', '_A', '_B')]
return all_folds
def make_folds_MLP(data_group):
all_folds = [(data_grou... | The main task of the code is to perform cross-validation on a classification model using given features and a classifier. It partitions data into folds, trains the classifier on each fold, evaluates performance metrics (UAR, WAR, recall, precision, confusion matrix), averages results across folds, and returns aggregate... | def run_main_function(results, dic_features, num_class, classifier, all_results, part_name, A, B, C, ALL_dics_MLP, N_functionals, num_feat):
all_folds = make_folds()
all_folds_MLP = make_folds_MLP('all_flat')
UAR = 0
WAR = 0
rec_ANT = 0
rec_HOM = 0
rec_CON = 0
rec_MIX = 0
... |
def make_folds():
all_folds = [('_A', '_B', '_C'),
('_A', '_C', '_B'),
('_B', '_A', '_C'),
('_B', '_C', '_A'),
('_C', '_B', '_A'),
('_C', '_A', '_B')]
return all_folds
def partitioning_LLDs(num_class, features, A, B, C, index):... | The main task of the code is to perform cross-validation by iterating through folds, evaluating a classifier's performance on partitioned features (A, B, C), and aggregating metrics like UAR, WAR, recall, precision, and confusion matrices across six folds. Results are averaged, stored, and printed for analysis. | def run_main_function(results, dic_features, num_class, classifier, all_results, part_name, A, B, C, num_feat):
all_folds = make_folds()
UAR = 0
WAR = 0
rec_ANT = 0
rec_HOM = 0
rec_CON = 0
rec_MIX = 0
pre_ANT = 0
pre_HOM = 0
pre_CON = 0
pre_MIX = 0
conf_matrix =... |
def get_random_split(split, my_dir):
random.seed(split)
print('SPLITTING IN 3-FOLDS')
path = my_dir + '/corpus'
composers = []
for krn_file in glob.glob(os.path.join(path, '*.krn')):
file_name = os.path.basename(krn_file[0:-4])
composer, other = file_name.split('_', 1)
... | The function conducts experiments by iterating over data splits, selecting features based on the specified number (9 or 11), partitioning functional data, running classification tasks with a given classifier, and aggregating results. It saves the outcomes to a CSV file for analysis, focusing on feature-based classifica... | def experiments_per_part(splits, num_class, dic_features, all_results, my_dir, classifier, part_name, num_feat, features_functionals):
for split in splits:
print('Running experiments with split: ', split)
A, B, C = get_random_split(split, my_dir)
results = []
if num_feat == 9:
... |
def get_random_split(split, my_dir):
random.seed(split)
print('SPLITTING IN 3-FOLDS')
path = my_dir + '/corpus'
composers = []
for krn_file in glob.glob(os.path.join(path, '*.krn')):
file_name = os.path.basename(krn_file[0:-4])
composer, other = file_name.split('_', 1)
... | The function `experiments_per_part` runs multiple experiments using different data splits, a specified classifier, and feature configurations. For each split, it retrieves data subsets, processes them with `run_main_function`, collects results, and saves them. It aggregates all results into a DataFrame, calculates the ... | def experiments_per_part(splits, num_class, dic_features, all_results, my_dir, classifier, part_name, num_feat):
for split in splits:
print('Running experiments with split: ', split)
A, B, C = get_random_split(split, my_dir)
results = []
results, all_results = run_main_function(resul... |
def __update_local_view(self):
self.local_settings = self.__get_settings()
def build_example(self):
"""
Exanple of project and result entries
"""
project, result = get_template()
project['name'] = 'test1'
project['files'] = ["poc.c", "poc.ver", "readme.md"]
# date field generated with:... | This code initializes a MongoDB client, connects to a specified database, and checks if the database is initialized. If not, it initializes the database, updates a local view, builds example data, and adds prompt examples. The primary task is setting up MongoDB connectivity and ensuring the database is properly initial... | def __init__(self, mongo_ip="mongo", mongo_port=27017):
global client
client = MongoClient("{}:{}".format(mongo_ip, mongo_port))
#
object.__init__(self)
self.client = client
self.db = self.client[db_capa]
if not WrapMongo.is_init_db():
WrapMongo.init_db()
self.__update_local_view... |
def update_score(self):
score_board = []
for user, points in self.channel_layer.user_score_dict.items():
username = "Error"
for u in self.channel_layer.users:
if u["id"] == user:
username = u['username']
score_board.append(
... | This function identifies a user by matching input text with a token, adds them to a pub session, initializes scoring data, updates game state, and triggers messages. If no token matches, it disconnects. | def handle_identify(self, text):
self.stopped = False
for token in Token.objects.all():
if str(token) == text:
pub = Pub.objects.get(id=self.room_name)
if len([member.username for member in pub.members.all()]) == 0 or not hasattr(self.channel_layer,
... |
def send_chat_message(self, text):
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'message': text,
}
)
def handle_identify(self, text):
self.stopped = False
for token in Tok... | This method processes WebSocket messages by parsing incoming JSON data, routing actions based on message type (e.g., sending chat messages, handling identification, processing guesses when allowed, and updating pause status). It ensures game state constraints are respected before executing actions, maintaining interact... | def receive(self, text_data):
# Receive message from WebSocket
text_data_json = json.loads(text_data)
text = text_data_json['message']
type = text_data_json['type']
if type == "message":
self.send_chat_message(text)
elif type == "identify":
self.ha... |
def maxpool(self, x, kernel_size):
p = np.floor((kernel_size - 1) / 2).astype(np.int32)
p_x = tf.pad(x, [[0, 0], [p, p], [p, p], [0, 0]])
return slim.max_pool2d(p_x, kernel_size)
def resblock(self, x, num_layers, num_blocks):
out = x
for i in range(num_blocks - 1):
ou... | This code constructs a ResNet-50-based encoder-decoder model for depth estimation and semantic segmentation. The encoder extracts hierarchical features via convolutional and residual blocks, while the decoder upsamples features using skip connections to generate multi-scale displacement maps (disp1-disp4). A separate s... | def build_resnet50(self):
# set convenience functions
conv = self.conv
if self.params.use_deconv:
upconv = self.deconv
else:
upconv = self.upconv
with tf.variable_scope('encoder'):
conv1 = conv(self.model_input, 64, 7, 2) # H/2 - 64D
... |
def scale_pyramid(self, img, num_scales):
scaled_imgs = [img]
s = tf.shape(img)
h = s[1]
w = s[2]
for i in range(num_scales - 1):
ratio = 2 ** (i + 1)
nh = h // ratio
nw = w // ratio
scaled_imgs.append(tf.image.resize_area(img, [nh,... | This code constructs a neural network model for stereo or monocular tasks by building encoder architectures (VGG or ResNet50) with pyramid-scaled inputs, handling variable reuse, and configuring input concatenation based on stereo mode. | def build_model(self):
with slim.arg_scope([slim.conv2d, slim.conv2d_transpose], activation_fn=tf.nn.elu):
with tf.variable_scope('model', reuse=self.reuse_variables):
self.left_pyramid = self.scale_pyramid(self.left, 4)
if self.mode == 'train':
s... |
def build_model(self):
with slim.arg_scope([slim.conv2d, slim.conv2d_transpose], activation_fn=tf.nn.elu):
with tf.variable_scope('model', reuse=self.reuse_variables):
self.left_pyramid = self.scale_pyramid(self.left, 4)
if self.mode == 'train':
s... | This code initializes a model for semantic segmentation, setting up parameters, building the neural network architecture, defining outputs, losses, and summaries. It handles both training and testing modes, with separate loss and summary construction during training. The model uses segmented and one-hot encoded labels,... | def __init__(self, params, mode, left, right, segmented, segmented_one_hot, reuse_variables=None, model_index=0):
self.params = params
self.mode = mode
self.left = left
self.right = right
self.segmented = segmented
self.segmented_one_hot = segmented_one_hot
self.N... |
def __get_coords(self, joint_states: numpy.ndarray) -> numpy.ndarray:
if len(joint_states) != 3:
print(f'Expected 3 values for joint states, but got {len(joint_states)} values instead')
return numpy.array([0.0, 0.0, 0.0])
res = self._fk.calculate('world', 'grip_end_point', joint... | The code calculates a reward for a robotic arm's movement based on distance changes between previous and current coordinates, normalized to a 0–10 scale. It adjusts rewards for reaching targets (bonus), approaching joint limits (penalty), or collisions (penalty). Additional components include exponential reward scaling... | def compute_reward(self, joint_states: numpy.ndarray, arm_state: ArmState) -> Tuple[float, Dict]:
assert len(joint_states) == 3, f'Expected 3 values for joint states, but got {len(joint_states)} values instead'
coords_get_result = self.__get_coords(joint_states)
assert len(coords_get_result) == ... |
def get_quantity(self, instrument):
"""Returns the current quantity held for instrument"""
# Get instrument type
if str(type(instrument))[-7:-2] == 'Stock':
instrument_type = 'Stock'
elif str(type(instrument))[-7:-2] == 'Option':
instrument_type = 'Option'
... | This function processes trading signals for each instrument to manage positions. It checks current holdings, evaluates entry/exit conditions, and adjusts positions by going long, short, or flat based on predefined signals. | def on_data(self):
"""Process signals for new bar"""
# Loop through instruments
for instrument in self.instruments:
# Get current qty
qty = self.get_quantity(instrument)
self.log('Current qty for {}: {}'.format(instrument.symbol, qty))
# Process ... |
def get_atr_multiple(self, instrument, indicators, multiplier=0.5):
"""Sets absolute value of SL equal to 1/2 ATR"""
indicators = self.get_indicators(instrument)
volatility = indicators['atr'][(indicators.axes[0].stop - 1)]
sl_size = self.adjust_for_price_increments(instrument,
... | The function `go_short` places a short trade order using strategy indicators, adjusting for price increments and ATR-based stop-loss. It handles exit-all orders, compound orders with entry/stop/exit, or standalone short entries with protective stops, returning a list of orders with specified conditions and references. | def go_short(self, instrument, indicators, *args, **kwargs):
"""Place short order according to strategy with an offset from LTL"""
offset = kwargs.get('offset', 0)
last_fill_price = kwargs.get('last_fill_price', None)
is_exit_all = kwargs.get('is_exit_all', False)
is_compound_ord... |
def get_atr_multiple(self, instrument, indicators, multiplier=0.5):
"""Sets absolute value of SL equal to 1/2 ATR"""
indicators = self.get_indicators(instrument)
volatility = indicators['atr'][(indicators.axes[0].stop - 1)]
sl_size = self.adjust_for_price_increments(instrument,
... | The main task of the code is to generate long trading orders (entry, stop-loss, and exit) based on technical indicators and customizable parameters like offset, stop-loss size, and compound order logic. It calculates price conditions using ATR multiples, adjusts for price increments, and places linked orders with speci... | def go_long(self, instrument, indicators, *args, **kwargs):
"""Return long order according to strategy with an offset from LTH"""
offset = kwargs.get('offset', 0)
last_fill_price = kwargs.get('last_fill_price', None)
sl_size = kwargs.get('sl_size',
self.get_a... |
def get_atr_multiple(self, instrument, indicators, multiplier=0.5):
"""Sets absolute value of SL equal to 1/2 ATR"""
indicators = self.get_indicators(instrument)
volatility = indicators['atr'][(indicators.axes[0].stop - 1)]
sl_size = self.adjust_for_price_increments(instrument,
... | The function `go_short` places a series of short sell orders with stop-loss and exit conditions based on long-term low (LTH) and dynamic control levels (DCL/DCU) indicators. It calculates stop-loss size using ATR multiples, adjusts entry/exit prices for market increments, and creates a chain of linked orders (entry, st... | def go_short(self, instrument, indicators, *args, **kwargs):
"""Place short order according to strategy with an offset from LTH"""
offset = kwargs.get('offset', 0)
sl_size = kwargs.get('sl_size',
self.get_atr_multiple(instrument, indicators))
total_quantity =... |
def get_atr_multiple(self, instrument, indicators, multiplier=0.5):
"""Sets absolute value of SL equal to 1/2 ATR"""
indicators = self.get_indicators(instrument)
volatility = indicators['atr'][(indicators.axes[0].stop - 1)]
sl_size = self.adjust_for_price_increments(instrument,
... | The code places a long market order with multiple protective stop-loss and exit orders, using technical indicators to determine entry levels, stop-loss sizes, and exit conditions. It creates a chain of dependent orders (A, B, C) with parent-child relationships, adjusting for price increments and ATR-based offsets to ma... | def go_long(self, instrument, indicators, *args, **kwargs):
"""Place long order according to strategy with an offset from LTH"""
offset = kwargs.get('offset', 0)
sl_size = kwargs.get('sl_size',
self.get_atr_multiple(instrument, indicators))
total_quantity = k... |
def set_sl_size(self, instrument, indicators):
"""Sets absolute value of SL equal to 2x ATR"""
indicators = self.get_indicators(instrument)
volatility = indicators['atr'][(indicators.axes[0].stop - 1)]
sl_size = self.adjust_for_price_increments(instrument, 2 * volatility)
# self.... | The function places long and short initial entry orders for a trading strategy, using dynamic stop-loss and exit conditions derived from indicators. It calculates position sizes, adjusts price levels, creates bracket orders with stop-loss limits, and groups them into an OCA (One Cancels All) order to ensure mutual excl... | def place_initial_entry_orders(self, instrument, indicators):
"""Long initial entry"""
sl_size = self.set_sl_size(instrument, indicators)
total_quantity = self.set_position_size(instrument,
indicators,
... |
def set_sl_size(self, instrument, indicators):
"""Sets absolute value of SL equal to 2x ATR"""
indicators = self.get_indicators(instrument)
volatility = indicators['atr'][(indicators.axes[0].stop - 1)]
sl_size = self.adjust_for_price_increments(instrument, 2 * volatility)
# self.... | This function places a long compound order with a stop-loss, calculating order size and price conditions based on provided indicators. It creates a bracket order (market order + stop-loss) and executes it via the IB API, using the parent order's average fill price to determine the stop-loss level and order quantity. | def place_compound_long_order(self, instrument, indicators, parent):
"""Place a single long compound order"""
sl_size = self.set_sl_size(instrument, indicators)
total_quantity = self.set_position_size(instrument,
indicators,
... |
def get_trading_hours(self):
"""Get today's trading hours for algo's instruments"""
open_time = None
close_time = None
# Get todays date in YYYYMMDD format
today = datetime.datetime.today().strftime('%Y%m%d')
# Loop through instruments
for instrument in self.ins... | The code runs a live trading algorithm by monitoring market hours, updating intraday data bars for instruments at specified intervals, processing trading signals, checking for exit conditions, and managing positions. It maintains real-time dataframes, triggers actions on new bars, and exits trades near market close. | def run(self):
"""Run logic for live trading"""
# Get today's trading hours
self.get_trading_hours()
# Wait until the markets open
#open_hr = int(self.exchange_open[:2])
#open_min = int(self.exchange_open[-2:])
#self.log('Waiting until the market opens ({}:{})...... |
def get_atr_multiple(self, instrument, indicators, multiplier=0.5):
"""Sets absolute value of SL equal to 1/2 ATR"""
indicators = self.get_indicators(instrument)
volatility = indicators['atr'][(indicators.axes[0].stop - 1)]
sl_size = self.adjust_for_price_increments(instrument,
... | The main task of the code is to place initial long and short entry orders for a given trading instrument via IBKR, using calculated stop-loss parameters and position sizes. It creates OCA (One Cancels All) orders to ensure only one trade is executed, then submits both long and short orders simultaneously, canceling the... | def place_initial_entry_orders(self, instrument, indicators):
"""Places initial long & short order entries with IBKR for instrument"""
# Trade parameters:
sl_size = self.get_atr_multiple(instrument, indicators)
total_quantity = self.set_position_size(instrument,
... |
def get_atr_multiple(self, instrument, indicators, multiplier=0.5):
"""Sets absolute value of SL equal to 1/2 ATR"""
indicators = self.get_indicators(instrument)
volatility = indicators['atr'][(indicators.axes[0].stop - 1)]
sl_size = self.adjust_for_price_increments(instrument,
... | The main task of the code is to place initial long and short entry orders for a given trading instrument using ATR-based stop-loss parameters. It calculates position size, logs order attempts, and employs an OCA (One Cancels All) group to ensure only one order (long or short) is executed. Orders are placed sequentially... | def place_initial_entry_orders(self, instrument, indicators):
"""Initial entry"""
sl_size = self.get_atr_multiple(instrument, indicators)
total_quantity = self.set_position_size(instrument,
indicators,
... |
def log(self, msg=""):
"""Add log to output file"""
self.logger.info(msg)
print(msg)
def get_indicators(self, instrument):
bars = self.ib.reqHistoricalData(contract=instrument,
endDateTime='',
durationStr='... | The code executes a trading strategy by iterating through financial instruments, assessing current positions, and placing initial or compound long/short orders based on position count and direction, while logging progress and positions for each instrument. | def run(self):
"""Run logic for today's trading"""
self.log()
start_time = datetime.datetime.now(tz=pytz.timezone('Asia/Shanghai'))
self.log('Beginning to run trading algorithm at {} HKT'
.format(start_time))
for instrument in self.instruments:
indica... |
def log(self, msg=""):
"""Add log to output file"""
self.logger.info(msg)
print(msg)
def get_indicators(self, instrument):
bars = self.ib.reqHistoricalData(contract=instrument,
endDateTime='',
durationStr='... | The main task of the code is to execute a trading algorithm that dynamically places compound long/short orders based on open order counts and market indicators. It iterates through instruments, checks open orders, and adjusts positions by incrementally increasing order multipliers up to 4, either adding long or short e... | def run(self):
"""Run logic for today's trading"""
self.log()
start_time = datetime.datetime.now(tz=pytz.timezone('Asia/Shanghai'))
self.log('Beginning to run trading algorithm at {} HKT'
.format(start_time))
for instrument in self.instruments:
indic... |
def configuration_to_strains_fn(params: Dict[str, Array], q: Array) -> Array:
"""
Map the generalized coordinates to the strains in the virtual backbone
Args:
params: Dictionary of robot parameters
q: generalized coordinates of shape (n_q, )
Returns:
x... | The function computes the Cartesian pose [x, y, orientation] of a point along a virtual backbone robot's structure, given generalized coordinates and segment parameters. It maps coordinates to strains, adjusts for singularities, identifies the segment containing the point, and applies segment-specific kinematic calcula... | def forward_kinematics_virtual_backbone_fn(
params: Dict[str, Array], q: Array, s: Array, eps: float = global_eps
) -> Array:
"""
Evaluate the forward kinematics the virtual backbone
Args:
params: Dictionary of robot parameters
q: generalized coordinates of sh... |
def configuration_to_strains_fn(params: Dict[str, Array], q: Array) -> Array:
"""
Map the generalized coordinates to the strains in the virtual backbone
Args:
params: Dictionary of robot parameters
q: generalized coordinates of shape (n_q, )
Returns:
x... | The main task of the code is to compute the Cartesian position and orientation of a point along a physical rod's centerline using forward kinematics. It maps generalized coordinates to rod strains, identifies the rod segment containing the point, and calculates the 3D pose [x, y, θ] via parametric functions, avoiding s... | def forward_kinematics_rod_fn(
params: Dict[str, Array],
q: Array,
s: Array,
rod_idx: Array,
eps: float = global_eps,
) -> Array:
"""
Evaluate the forward kinematics of the physical rods
Args:
params: Dictionary of robot parameters
... |
def configuration_to_strains_fn(params: Dict[str, Array], q: Array) -> Array:
"""
Map the generalized coordinates to the strains in the virtual backbone
Args:
params: Dictionary of robot parameters
q: generalized coordinates of shape (n_q, )
Returns:
x... | The function computes the Cartesian pose [position and orientation] of a platform's center of gravity (CoG) using forward kinematics. It maps generalized joint coordinates to strain parameters, applies a small epsilon to avoid singularities, and evaluates the resulting pose via a segment-index-dependent function. The o... | def forward_kinematics_platform_fn(
params: Dict[str, Array], q: Array, segment_idx: Array, eps: float = global_eps
) -> Array:
"""
Evaluate the forward kinematics the platform
Args:
params: Dictionary of robot parameters
q: generalized coordinates of shape (n... |
def configuration_to_strains_fn(params: Dict[str, Array], q: Array) -> Array:
"""
Map the generalized coordinates to the strains in the virtual backbone
Args:
params: Dictionary of robot parameters
q: generalized coordinates of shape (n_q, )
Returns:
x... | This function computes the end-effector's Cartesian pose [x, y, theta] using forward kinematics by converting joint coordinates to strains, applying singularity avoidance via epsilon, and evaluating pre-defined symbolic expressions with robot parameters. It maps generalized coordinates to end-effector position/orientat... | def forward_kinematics_end_effector_fn(
params: Dict[str, Array], q: Array, eps: float = global_eps
) -> Array:
"""
Evaluate the forward kinematics of the end-effector
Args:
params: Dictionary of robot parameters
q: generalized coordinates of shape (n_q, )
... |
def configuration_to_strains_fn(params: Dict[str, Array], q: Array) -> Array:
"""
Map the generalized coordinates to the strains in the virtual backbone
Args:
params: Dictionary of robot parameters
q: generalized coordinates of shape (n_q, )
Returns:
x... | The function computes the Jacobian of the end-effector pose with respect to generalized coordinates by converting the configuration to strains, adjusting bending strains to avoid singularities, and evaluating a pre-defined symbolic expression using robot parameters. It returns a 3×n_q array representing the end-effecto... | def jacobian_end_effector_fn(
params: Dict[str, Array], q: Array, eps: float = global_eps
) -> Array:
"""
Evaluate the Jacobian of the end-effector
Args:
params: Dictionary of robot parameters
q: generalized coordinates of shape (n_q, )
eps: small num... |
def configuration_to_strains_fn(params: Dict[str, Array], q: Array) -> Array:
"""
Map the generalized coordinates to the strains in the virtual backbone
Args:
params: Dictionary of robot parameters
q: generalized coordinates of shape (n_q, )
Returns:
x... | The function computes the dynamical matrices (mass, Coriolis, gravity, elastic, dissipative, and actuation terms) of a robotic system using generalized coordinates, velocities, and strain parameters. It maps configurations to strains, applies epsilon adjustments, evaluates symbolic expressions for matrix components, tr... | def dynamical_matrices_fn(
params: Dict[str, Array],
q: Array,
q_d: Array,
z: Optional[Array] = None,
phi: Array = jnp.zeros((num_segments * num_rods_per_segment,)),
eps: float = 1e4 * global_eps,
) -> Tuple[Array, Array, Array, Array, Array, Array]:
"""
... |
def configuration_to_strains_fn(params: Dict[str, Array], q: Array) -> Array:
"""
Map the generalized coordinates to the strains in the virtual backbone
Args:
params: Dictionary of robot parameters
q: generalized coordinates of shape (n_q, )
Returns:
x... | The code computes operational space dynamical matrices for robotics, including the inertia matrix (Lambda), Coriolis/centrifugal terms (mu), end-effector Jacobian (Jee), its time derivative (Jee_d), and a dynamically-consistent Jacobian pseudo-inverse (JeeB_pinv). It uses generalized coordinates (q, q_d), inertia (B), ... | def operational_space_dynamical_matrices_fn(
params: Dict[str, Array],
q: Array,
q_d: Array,
B: Array,
C: Array,
eps: float = 1e4 * global_eps,
) -> Tuple[Array, Array, Array, Array, Array]:
"""
Compute the dynamics in operational space.
The im... |
def getPositions(self):
return deepcopy(self.positions)
def winCheck(self, positions): # check if state is in win, loss, or tie condition
# tie is only if at horizon and no wins
# can check wins efficiently with kernels and convolve2, "Python connect 4 check win function" on Stack Overflow
... | The code simulates a game rollout for a specified number of moves, alternating between players. It checks for immediate winning moves, prioritizing the current player's win or blocking the opponent's win. If no decisive move is found, it randomly selects the next position. The function returns a win value if achieved d... | def rollout(self, numMoves, whichPlayer): #whichPlayer is 1 for self
# get sample vHat
positions = self.getPositions()
winVal = self.winCheck(positions)
if winVal != -1:
return winVal
for move in range(numMoves):
prevPositions = deepcopy(positions)
... |
def getPositions(self):
return deepcopy(self.positions)
def actionHeight(self, positions, action):
for height in range(6):
if positions[action][height] == 0:
return height
return -1
def checkIfWinMove(self, positions, whichPlayer): #prob needs to be more efficient
... | The function `sampleY` updates game positions by placing a move (value 1) at the specified action. It prioritizes blocking an opponent's winning move (value 2) if detected, or placing a winning move for itself if possible. If neither, it samples a random next move for player 2 and returns the updated board state. This ... | def sampleY(self, action):
positions = self.getPositions()
positions[action][self.actionHeight(positions, action)] = 1
check2 = self.checkIfWinMove(positions, 2) # if can make a winning move
if check2 != -1:
positions[check2][self.actionHeight(positions, check2)] = 2
... |
def getPositions(self):
return deepcopy(self.positions)
def winCheck(self, positions): # check if state is in win, loss, or tie condition
# tie is only if at horizon and no wins
# can check wins efficiently with kernels and convolve2, "Python connect 4 check win function" on Stack Overflow
... | This function performs a game rollout simulation to determine the outcome of a game state by iteratively checking for immediate winning moves, alternately selecting moves for two players, and returning a win value or heuristic estimate if no decisive outcome is found within the specified number of moves. | def rollout(self, numMoves, whichPlayer): #whichPlayer is 1 for self
# get sample vHat
positions = self.getPositions()
winVal = self.winCheck(positions)
if winVal != -1:
return winVal
for move in range(numMoves):
prevPositions = deepcopy(positions)
... |
def getPositions(self):
return deepcopy(self.positions)
def actionHeight(self, positions, action):
for height in range(6):
if positions[action][height] == 0:
return height
return -1
def checkIfWinMove(self, positions, whichPlayer): #prob needs to be more efficient
... | The code's main task is to determine the next move in a game by prioritizing a winning move for player 2, then blocking player 1's potential win, and finally selecting a random valid move if neither condition is met. It updates the game state by placing a '2' in the chosen position, ensuring strategic gameplay. | def sampleY(self, action):
positions = self.getPositions()
positions[action][self.actionHeight(positions, action)] = 1
check2 = self.checkIfWinMove(positions, 2) # if can make a winning move
if check2 != -1:
positions[check2][self.actionHeight(positions, check2)] = 2
... |
def sampleY(self, action):
positions = self.getPositions()
positions[action][self.actionHeight(positions, action)] = 1
check2 = self.checkIfWinMove(positions, 2) # if can make a winning move
if check2 != -1:
positions[check2][self.actionHeight(positions, check2)] = 2
... | This code updates an action's state by sampling positions, propagating through a tree structure with depth-dependent budgets, calculating a reward estimate (qHat), and updating statistics like visits, samples, Q-bar, and variance for the action. | def update(self, action, depth, depthBudget, initProbeBudget): # depth budget gives budget at each depth level
positions = self.sampleY(action)
# divide actions in two for now
childState = OCBAState(positions=positions)
if depth > 1:
for sample in range(depthBudget[depth-1]):... |
def sampleY(self, action):
positions = self.getPositions()
positions[action][self.actionHeight(positions, action)] = 1
check2 = self.checkIfWinMove(positions, 2) # if can make a winning move
if check2 != -1:
positions[check2][self.actionHeight(positions, check2)] = 2
... | This function updates a node's value in a UCB tree by sampling child states, calculating a new value estimate (qHat) from rewards and child node values, then updating visit counts, action statistics, and UCB parameters to guide future exploration in a Monte Carlo Tree Search. | def update(self, action, depth, depthBudget, exploreParam):
positions = self.sampleY(action)
childState = UCBState(positions=positions, exploreParam=self.exploreParam)
if depth > 1:
for sample in range(depthBudget[depth-1]):
childState.UCBTree(depth - 1, depthBudget,... |
def winCheck(self, positions): # check if state is in win, loss, or tie condition
# tie is only if at horizon and no wins
# can check wins efficiently with kernels and convolve2, "Python connect 4 check win function" on Stack Overflow
# for now, just manually check each
# alternatively,... | This function evaluates a game tree to determine the optimal value (vHat) by checking for immediate wins, sampling rewards at terminal depth, and iteratively exploring under-sampled actions. It updates action values using a budget constraint, prioritizes actions with insufficient samples, and adjusts for "starving" act... | def OCBATree(self, depth, depthBudget, initProbeBudget): # returns vHat
winVal = self.winCheck(self.positions)
if winVal != -1:
self.vHat = winVal
return
# winCheck = self.checkIfWinMove(self.positions, 1)
# if winCheck != -1:
# self.vHat = 1
... |
def winCheck(self, positions): # check if state is in win, loss, or tie condition
# tie is only if at horizon and no wins
# can check wins efficiently with kernels and convolve2, "Python connect 4 check win function" on Stack Overflow
# for now, just manually check each
# alternatively,... | The UCBTree function performs a UCT (Upper Confidence Bound for Trees) search to explore game states, balancing exploration and exploitation. It checks for terminal states, samples rewards at depth 0, updates UCB values, selects under-explored ("starving") actions, and recursively evaluates optimal paths within a depth... | def UCBTree(self, depth, depthBudget, exploreParam):
winVal = self.winCheck(self.positions)
if winVal != -1:
self.vHat = winVal
return
# winCheck = self.checkIfWinMove(self.positions, 1)
# if winCheck != -1:
# self.vHat = 1
# return
... |
def calc_height(self, node):
if not node:
return -1
return node.height
def settle_violation(self, data, node):
balance = self.calc_balance(node)
#case 1 -> left left heavy situation
if balance > 1 and data < node.left_child.data:
print("case 1 -> left lef... | This function inserts a new node with given data into an AVL tree recursively, adjusts the height of the affected node, and ensures tree balance by calling `settle_violation` to handle rotations if necessary. | def insert_node(self, data, node):
if not node:
print("inserting {}".format(data))
return AVLNode(data)
if data < node.data:
node.left_child = self.insert_node(data, node.left_child)
else:
node.right_child = self.insert_node(data, node.right_child)... |
def send_message_to_connection(message, conn):
conn.send(convert_to_bytes(message))
def broadcast(message, connection):
for client_connection in list_of_clients:
if client_connection != connection:
try:
send_message_to_connection(message, client_connection)
excep... | The main task of the code is to handle client communication in a chatroom by sending a welcome message, receiving and decoding client messages, broadcasting them to all connected clients with sender identification, and managing disconnections or errors by removing the connection. | def clientthread(conn, addr):
'''
sends welcome message to the client.
'''
send_message_to_connection('Welcome to this chatroom!', conn)
while True:
try:
encoded_message = conn.recv(2048)
message = encoded_message.decode(MESSAGE_ENCODING)
sender = '<' + ... |
def terminal_node(node):
y_boot = node["y_boot"]
pred = max(y_boot, key=y_boot.count)
return pred
def find_split_point(
x_boot,
y_boot,
max_features
):
feature_ls = list()
num_features = len(x_boot[0])
while len(feature_ls) <= max_features:
feature_idx = np.rando... | The main task of the code is to recursively split a decision tree node into terminal (leaf) nodes or child nodes based on conditions like maximum depth, minimum samples for splitting, and bootstrapped data. It deletes existing children, checks for empty data, and creates terminal nodes if splits are invalid. If valid, ... | def split_node(
node,
max_features,
min_samples_split,
max_depth, depth
):
left_child = node["left_child"]
right_child = node["right_child"]
del (node["left_child"])
del (node["right_child"])
if len(left_child["y_boot"]) == 0 or len(right_child["y_boot"]) == 0:
... |
def draw_boot(x_train, y_train):
boot_indices = list(
np.random.choice(
range(len(x_train)),
len(x_train),
replace=True
)
)
oob_indices = [i for i in range(len(x_train)) if i not in boot_indices]
x_boot = x_train.iloc[boot_indices].values
y_boot = ... | This function builds a random forest by generating multiple decision trees using bootstrapped samples from the training data. For each tree, it calculates the out-of-bag (OOB) error on the unused data points. It returns the list of trained trees and prints the average OOB error across all trees, providing an estimate o... | def random_forest(
x_train,
y_train,
n_estimators,
max_features,
max_depth,
min_samples_split
):
tree_ls = list()
oob_ls = list()
for i in range(n_estimators):
x_boot, y_boot, x_oob, y_oob = draw_boot(x_train, y_train)
tree = build_tree(
... |
def move(self):
self.colliding = False
cside = 1
xoff = cside * m.cos(m.radians(self.rotation))
yoff = cside * m.sin(m.radians(self.rotation))
self.collisionNode = Position(
self.currentPos.x+xoff, self.currentPos.y+yoff)
self.currentSegment = (m.floor(sc... | The code updates an object's position and rotation, then periodically inserts a new node into a path at intervals defined by `nodeDelay`, using `writeToPath()` to record the current state. | def update(self):
self.move()
self.setRotation()
if self.nextNodeInsertTime <= time.time():
self.nextNodeInsertTime = time.time() + self.nodeDelay
# print("time: " + str(time.time()))
self.writeToPath() |
def _nested_field_dne(self, field):
"""
Checks if a nested JSON field does not exist (DNE)
"""
if ("." in field or "[" in field) and not get_value_at_json_path(self.data, field):
return False
def log_warning(self, msg):
self.total_warnings += 1
LOG.warning(f"{... | The main task of the code is to validate data by checking for required fields and ensuring date formats are correct. It iterates through required fields, logs warnings if any are missing, and calls a method to validate dates. This ensures data integrity by enforcing field presence and proper date structures. | def validate(self):
"""
Validate the data.
Implement validations such as checking required fields,
validating date formats, ensuring identifiers meet expected patterns, etc.
"""
for field in self.required_fields:
if field not in self.data or self._nested_fiel... |
def validate(self):
"""
Validate the data.
Implement validations such as checking required fields,
validating date formats, ensuring identifiers meet expected patterns, etc.
"""
for field in self.required_fields:
if field not in self.data or self._nested_fiel... | The code processes claims data by validating its integrity, mapping values to standardized formats, and normalizing the data. It updates instance variables, increments a counter for processed rows, and returns the transformed data. | def process(self, data, row_num):
"""
Main method to process the claims data by validating, mapping, and normalizing it.
"""
self.data = data
self.row_num = row_num
self.validate()
self.map_values()
self.normalize()
self.total_rows_processed += 1
... |
def generate_password(self, length=None):
if length is None:
length = 20
self.add_item(
title="Copy password to clipboard",
subtitle=f"Generate {length}-symbol length password",
method="generate_and_copy_password",
parameters=[length],
... | The code processes user input to either generate a password (if a numeric length is provided), add a new password (if "add" or "new" is specified), or retrieve an existing password (using the input as a key). It parses the query, determines the action, and delegates to corresponding methods like `generate_password`, `a... | def query(self, query: str):
query = str(query).strip()
length = None
try:
length = int(query)
except:
length = None
if len(query) == 0 or length is not None:
self.generate_password(length)
return
commands = query.split()
... |
def extract_header_file_output_x64(e_header_file_info ):
file_header = dict()
file_header["ei_Magic"] = ' '.join(e_header_file_info[:16])
file_header["ei_class"] = get_ei_class(e_header_file_info[4])
file_header["ei_data"] = get_ei_data(e_header_file_info[5])
file_header["ei_version"] = get_ei_vers... | The main task of the code is to analyze an x86-64 ELF binary by extracting headers, symbol tables, and dynamic sections, disassembling code to identify function calls and system calls, and generating a visual graph (DOT format) showing call relationships and syscall mappings. It processes relocation entries, handles en... | def create_output_x64(e_header_file_info , h_structur_extracted , e_program_header , e_section_header , f):
file_header = dict()
file_header = extract_header_file_output_x64(e_header_file_info )
program_headers = extract_program_header_output_x64(e_program_header)
section_headers = extract_section_heade... |
def extract_header_file_output_x86(e_header_file_info ):
file_header = dict()
file_header["ei_Magic"] = ' '.join(e_header_file_info[:16])
file_header["ei_class"] = get_ei_class(e_header_file_info[4])
file_header["ei_data"] = get_ei_data(e_header_file_info[5])
file_header["ei_version"] = get_ei_vers... | The code processes a 32-bit x86 ELF binary by extracting headers, symbol tables, and dynamic sections. It disassembles code to detect function calls and syscalls, builds a call graph, and visualizes it as a DOT file. The output includes nodes for functions, edges for calls/returns, and syscall numbers, highlighting int... | def create_output_x86(e_header_file_info , h_structur_extracted , e_program_header , e_section_header , f):
file_header = dict()
file_header = extract_header_file_output_x86(e_header_file_info )
program_headers = extract_program_header_output_x86(e_program_header)
section_headers = extract_section_heade... |
def process_file(content, file_extension):
""" Process the file (.txt or .p) containing the graph and return its nodes and edges.
"""
data, nodes, edges = [], [], []
if file_extension == 'txt':
data = [el.strip() for el in content.split(".") if len(el.strip())>0]
elif file_extension == 'p':
... | The main task of the code is to update or rebuild graphs based on user actions (file upload or searches) in a Dash application. It processes uploaded data, constructs graphs, manages node positions, and visualizes search results or paths. The function stores graph data efficiently in intermediary storage, handles dual-... | def process_graph(content, model, search_value, n_clicks, search_type, filepath, G1, pos1, G2, pos2):
""" Update/rebuild the graph when the user picks a new file or searches something.
Stores the graph and its nodes positions in an intermediary div (replace div with dcc.store).
This littl... |
def _pawn_at_start(pos, color):
if (color == "W") & (pos[0] == 1):
return True
elif (color == "B") & (pos[0] == 6):
return True
return False
def _will_be_check(board, color, move):
board_copy = copy.deepcopy(board)
_apply_move(board_copy, move)
check = is_check(board_copy, color)
return check
def _in_passing... | This function validates a pawn's move on a chessboard, checking if the move is legal based on pawn movement rules (including double-step and capture), en passant, and whether the move would leave the king in check. It verifies the path is clear, checks for valid target positions, and ensures the move complies with colo... | def _pawn_valid_move(board, color, move):
delta = (move[1][0]-move[0][0], move[1][1]-move[0][1])
up = UP[color]
if delta[1] == 0:
if delta[0] == 2*up:
if not _pawn_at_start(move[0], color):
return False
for pos_x in range(move[0][0]+1,move[1][0]+1):
if board.board[pos_x][move[0][1]] != "_":
return ... |
def in_board(pos):
if (pos[0] < 0) | (pos[0] > 7) | (pos[1] < 0) | (pos[1] > 7):
return False
return True
def is_check(board, color):
king_pos = ()
for i in range(8):
for j in range(8):
piece_color = board.board[i][j][0] #"_" will not be considered
if (piece_color == color) & (board.board[i][j][1:] == "K... | This function validates a king's move on a chessboard, specifically checking for castling legality. It verifies if the rook has moved, ensures the path between king and rook is clear, and confirms the move doesn't expose the king to check. If the move is a castling, it checks intermediate positions and future check con... | def _king_valid_move(board, color, move):
delta_y = move[1][1]-move[0][1]
if abs(delta_y) == 2:
sign = delta_y//2
if sign < 0:
rock_allowed = (not board.memory[color]["has_left_rook_move"]) & (not board.memory[color]["has_king_move"])
else:
rock_allowed = (not board.memory[color]["has_right_rook_move"]) ... |
def _pawn_possible_moves(board, color, pos):
up = UP[color]
moves = []
for base_move in BASE_MOVES["P"]:
end_pos = ((pos[0]+up*base_move[0]), (pos[1]+up*base_move[1]))
if not in_board(end_pos):
continue
if (board.board[end_pos[0]][end_pos[1]][0] == color):
continue
if _pawn_valid_move(board, color, (po... | This function generates all possible moves for a given player's pieces on a chessboard. It iterates through each cell, checks if the piece matches the specified color, identifies the piece type (pawn, bishop, etc.), and calls corresponding helper functions to calculate valid moves. The results are aggregated into a lis... | def possible_moves(board, color):
moves = []
for i in range(8):
for j in range(8):
piece_color = board.board[i][j][0] #"_" will not be considered
if piece_color == color:
piece = board.board[i][j][1:]
if piece == "P":
moves += _pawn_possible_moves(board, color, (i,j))
elif piece == "B":
... |
def _pawn_possible_moves(board, color, pos):
up = UP[color]
moves = []
for base_move in BASE_MOVES["P"]:
end_pos = ((pos[0]+up*base_move[0]), (pos[1]+up*base_move[1]))
if not in_board(end_pos):
continue
if (board.board[end_pos[0]][end_pos[1]][0] == color):
continue
if _pawn_valid_move(board, color, (po... | This function checks if a move is valid for a player's piece on a chessboard by verifying if the target position aligns with the movement rules of the piece at the current position. It identifies the piece type, matches it to the player's color, and uses corresponding helper functions to validate the move. If valid, it... | def is_valid_move(player, board, move):
pos = move[0]
color = board.board[pos[0]][pos[1]][0]
if color == player.color:
piece = board.board[pos[0]][pos[1]][1:]
if piece == "P":
if move in _pawn_possible_moves(board, color, pos):
return True
elif piece == "B":
if move in _bishop_possible_moves(board, c... |
def generate_stationary_waypoints(params,bounds):
"""
Generates stationary waypoints based on specified parameters.
Parameters:
- params (list): List containing the coordinate and total_xy_points.
- bounds (tuple): tuple of yaw,azimuth, and elevation dictionarys which describe the robots physical b... | The function `custom_paths` generates custom trajectories for two robots by selecting path types (e.g., stationary, exhaustive, sinusoidal, circular) from `option_list`, applying corresponding parameters and bounds, and compiling waypoints into a list. Each path type uses dedicated generation functions to create trajec... | def custom_paths(option_list, bounds_list, params_list):
"""
Generate custom path for two robots
"""
waypoints_list = []
for option, bounds, params in zip(option_list,bounds_list, params_list):
if option == "Stationary":
waypoints_list.append(generate_stationary_waypoints(pa... |
def generate_params_bounds(option1, option2):
"""
Generate robot parameters and bounds
"""
if option1 == "Stationary":
params1 = ((0,0), 90000)
bounds1 = {'min': 0, 'max': 0, 'step': 1}, {'min': 0, 'max': 0, 'step': 1}, {'min': 0, 'max': 0, 'step': 1}
elif option1 == "Exhaustive":
... | The code generates and saves robot waypoints for different path types (e.g., Stationary, Exhaustive) using custom path generation functions, then visualizes the trajectories with direction indicators. It creates a CSV file with waypoint data and plots the paths for two robots. | def generate_waypoints():
df = pd.DataFrame(columns=DATA_TITLES) # Include the column titles)
df.to_csv(FILE_PATH, mode='a', header=True, index=False)
#Example Params
path_options = ["Stationary", "Exhaustive", "Sinusoidal", "Circular"]
option1, option2 = path_options[0], path_options[1]... |
def initialize(self, noVar, k):
np.random.seed(self.seed_number)
# initialize k bayesian network
for i in range(k):
bn = BN()
bn.randomBN(noVar, seed_number = i)
self.mixtureBN.append(bn)
# initialize weight component
self.weight_components =... | The code performs parameter estimation for a probabilistic model using the Expectation-Maximization (EM) algorithm. It initializes model structure, iterates 20 times, and in each iteration, computes expected values (E-step) and updates parameters (M-step) based on the data. The process refines model parameters to bette... | def estimate(self, data, bn):
np.random.seed(self.seed_number)
self.children = bn.children
self.parents = {i: [] for i in self.children}
self.initialize(bn.numVars, self.k)
for _ in range(20):
ws = self.E_step(data)
self.M_step(ws, data) |
def makeDBconnection():
#Establishing the connection
conn = psycopg2.connect(
database="botdb", user='postgres', password='admin', host='127.0.0.1', port= '5432'
)
#Setting auto commit false
conn.autocommit = True
return conn
def send_message(errorMessage, availableShots = "NA", forDate ... | The main task of the code is to continuously check database slots in an infinite loop, incrementing a counter each iteration. It sends periodic "running" status messages every 25 cycles, maintains a persistent database connection, and closes it upon completion. The core functionality revolves around monitoring slot ava... | def main_function():
i = 0
conn = makeDBconnection()
send_message(errorMessage="running")
while True:
check_slots(noOfTimes=i, conn = conn)
i = i + 1
#time.sleep(60)
if(i%25 == 0):
send_message(errorMessage="running")
conn.close() |
def reset(self):
"""Reset the model state."""
self.eval_tokens.clear()
self.eval_logits.clear()
def eval(self, tokens: Sequence[int]):
"""Evaluate a list of tokens.
Args:
tokens: The list of tokens to evaluate.
"""
invalidInputError(self.ctx is not No... | The main task of the code is to generate tokens sequentially from a given prompt using specified sampling parameters (e.g., top-k, temperature). It manages model state by resetting or detecting prefix matches to avoid repetition, applies penalties for frequency/presence, and yields each generated token via a generator.... | def _generate(
self,
tokens: Sequence[int],
top_k: int = 40,
top_p: float = 0.95,
temp: float = 0.80,
repeat_penalty: float = 1.1,
reset: bool = True,
frequency_penalty: float = 0.0,
presence_penalty: float = 0.0,
tfs_z: float = 1.0,
... |
def load_state(self, state: LlamaState) -> None:
invalidInputError(self.ctx is not None, "The attribute `ctx` of `Llama` object is None.")
self.eval_tokens = state.eval_tokens.copy()
self.eval_logits = state.eval_logits.copy()
state_size = state.llama_state_size
invalidInputError... | The main task of the code is to generate text completions using a language model based on a given prompt, with parameters like temperature, max tokens, and stop sequences. It tokenizes the input, handles streaming output, manages caching for efficiency, and returns generated text along with metadata such as log probabi... | def _create_completion(
self,
prompt: str,
suffix: Optional[str] = None,
max_tokens: int = 16,
temperature: float = 0.8,
top_p: float = 0.95,
logprobs: Optional[int] = None,
echo: bool = False,
stop: Optional[Union[str, List[str]]]=[],
freq... |
def norm(img, max_val=255):
mi, ma = np.min(img), np.max(img)
if mi == ma:
return img * max_val
return (img - mi) / (ma - mi) * max_val
def _subtract_background(img, background_sigma=151):
img_bck = cv2.GaussianBlur(img, (background_sigma, background_sigma), 0)
res = img.astype(float) - img_... | The function suppresses non-grid artifacts in an image by normalizing the input after background subtraction, generating a candidate heatmap based on a threshold, and combining the normalized image with the heatmap to highlight grid-like structures while reducing irrelevant details. | def _suppress_non_grid_artifacts(img, threshold):
# Normalize image and calculate candidate heatmap
img_no_bck = norm(_subtract_background(img))
candidates_heatmap = _calculate_candidates_heatmap(img_no_bck, threshold)
return norm(img_no_bck * candidates_heatmap).astype(np.uint8) |
def _suppress_non_grid_artifacts(img, threshold):
# Normalize image and calculate candidate heatmap
img_no_bck = norm(_subtract_background(img))
candidates_heatmap = _calculate_candidates_heatmap(img_no_bck, threshold)
return norm(img_no_bck * candidates_heatmap).astype(np.uint8)
def _segment_indents(im... | The function generates a mask highlighting indents in an image by suppressing non-grid artifacts, segmenting indents via thresholding, and enhancing shapes through morphological closing with a diamond kernel. It returns the processed binary mask as a uint8 array. | def get_indent_mask(img, threshold_h, threshold_l, close_size=41):
# Apply preprocessing to highlight indents
img_highlight = _suppress_non_grid_artifacts(img, threshold_h)
mask = _segment_indents(img_highlight, threshold_l)
# Morphological closing to enhance indent shapes
return cv2.morphologyEx(ma... |
def _suppress_non_grid_artifacts(img, threshold):
# Normalize image and calculate candidate heatmap
img_no_bck = norm(_subtract_background(img))
candidates_heatmap = _calculate_candidates_heatmap(img_no_bck, threshold)
return norm(img_no_bck * candidates_heatmap).astype(np.uint8)
def get_indent_mask(img... | This code identifies grid-like features in a cropped image region by suppressing non-grid artifacts, generating a mask, detecting component centers, and adjusting coordinates to the original image's system. If no valid centers are found or too many, it returns a default coordinate. | def find_origin_last(img, x_start, x_end, y_start, y_end):
filtered_centers_last = np.array([])
cropped = img[y_start:y_end, x_start:x_end]
threshold = 20
img_highlight = _suppress_non_grid_artifacts(cropped, threshold)
threshold_h = 15
threshold_l = 15
mask1 = np.array([])
mask1 = get_... |
def _suppress_non_grid_artifacts(img, threshold):
# Normalize image and calculate candidate heatmap
img_no_bck = norm(_subtract_background(img))
candidates_heatmap = _calculate_candidates_heatmap(img_no_bck, threshold)
return norm(img_no_bck * candidates_heatmap).astype(np.uint8)
def get_indent_mask(img... | The main task of the code is to detect specific features (e.g., grid points or indentations) in a cropped region of an image, transform their coordinates back to the original image's coordinate system, and return them. If no valid features are found or too many are detected, it defaults to a predefined coordinate. The ... | def find_origin_start(img, x_start, x_end, y_start, y_end):
filtered_centers1 = np.array([])
cropped = img[y_start:y_end, x_start:x_end]
threshold = 20
img_highlight = _suppress_non_grid_artifacts(cropped, threshold)
threshold_h = 15
threshold_l = 15
mask1 = np.array([])
mask1 = get_ind... |
def _suppress_non_grid_artifacts(img, threshold):
# Normalize image and calculate candidate heatmap
img_no_bck = norm(_subtract_background(img))
candidates_heatmap = _calculate_candidates_heatmap(img_no_bck, threshold)
return norm(img_no_bck * candidates_heatmap).astype(np.uint8)
def get_indent_mask(img... | This function processes a cropped image region to detect grid-like patterns, applies thresholding to suppress artifacts, identifies component centers, and returns their coordinates relative to the original image. If no valid centers are found or multiple are detected, it defaults to a predefined coordinate. | def find_origin_middle(img, x_start, x_end, y_start, y_end):
filtered_centers_m = np.array([])
cropped = img[y_start:y_end, x_start:x_end]
threshold = 50
img_highlight = _suppress_non_grid_artifacts(cropped, threshold)
threshold_h = 15
threshold_l = 15
mask1 = np.array([])
mask1 = get... |
def _suppress_non_grid_artifacts(img, threshold):
# Normalize image and calculate candidate heatmap
img_no_bck = norm(_subtract_background(img))
candidates_heatmap = _calculate_candidates_heatmap(img_no_bck, threshold)
return norm(img_no_bck * candidates_heatmap).astype(np.uint8)
def get_indent_mask(img... | This function identifies real points around a specified image coordinate by cropping a region, suppressing artifacts, generating a mask, and returning the closest valid center point adjusted to the original image's coordinate system. | def find_real_points_around_point(
img, x, y, threshold=20, threshold_h=30, threshold_l=30
):
x_start, x_end = x - 50, x + 50
y_start, y_end = y - 50, y + 50
cropped = img[y_start:y_end, x_start:x_end]
img_highlight = _suppress_non_grid_artifacts(cropped, threshold)
mask = get_indent_mask(img... |
def callMonitorInterface():
try:
info = subprocess.run(["systemctl","status","monitor"], capture_output=True, text=True)
lines = info.stdout
newLines = lines.splitlines()
rtn = []
for l in newLines:
rtn.append(l)
nRtn = ""
for r in rtn:
... | This function processes command requests from a specified file by reading each line, executing corresponding functions based on keywords (e.g., "monitorStatus", "sms_dev"), generating results, writing them to a results file, and deleting the command file. It handles errors, logs exceptions, and supports commands for da... | def checkForCommandFile():
try:
filename = config.get("CommandInterface","cmd_file")
if os.path.exists(filename):
f = open(config.get("CommandInterface","cmd_file"),"r")
results = ""
for line in f:
if line.strip() == "":
... |
def isSolved(puzzle):
solvedPuzzle = pyraminx_puzzle([],None)
if solvedPuzzle == puzzle:
return True
else:
return False
def key(puzzle):
return ''.join([''.join([str(j) for j in i]) for i in puzzle])
def MCTS_with_depth(scramble,ideal,depth = 4):
Tree={}
solved = False
for a ... | This function uses Monte Carlo Tree Search (MCTS) with a depth limit to solve a Rubik's cube scramble within a specified maximum number of moves. It iteratively applies MCTS to generate moves, tracks the sequence of states, and returns whether a solution was found along with the number of moves and path. If the cube is... | def solve_nmcts(scramble,maxmoves,dpt = 4,ideal=1):
n=0
solvedPath=[]
while(n<=maxmoves):
if isSolved(scramble):
return True,n,solvedPath
solvedPath.append(key(scramble))
# print(scramble)
a=MCTS_with_depth(scramble,dpt,ideal)
scramble=Move(scramble,a)
... |
def scramble(numScrambles):
puzz = None
for _ in range(numScrambles):
puzz = pyraminx_puzzle([random.choice(Actions)], puzz)
return puzz
def key(puzzle):
return ''.join([''.join([str(j) for j in i]) for i in puzzle])
def reiter(model,optimizer,path):
checkpoint = torch.load(path)
mod... | The code tests and compares different neural network models (NN1, NN2, ADI variants) and a tabular method on solving scrambled Pyraminx puzzles using MCTS, Greedy, and pMCTS algorithms. It evaluates the number of moves required to solve puzzles at varying distances, logging results for performance analysis. | def test_pyraminx(dist):
global model
global optimizer
global epsilon
global const_Virtualloss
c1 = 50
rs = []
scrambledPuzzle = scramble(dist)
print(key(scrambledPuzzle))
solveMCTS = mctsState()
model = predictor.NN1()
optimizer = torch.optim.Adam(model.parameters(),lr=1e-8)... |
def timeout_set(self, x):
self.resume_time = time.time() + x
def wake(self):
self.timeout_set(0)
self.write_bytes(255)
if self.firmware_version >= 264:
time.sleep(0.05) # 50 ms
self.write_bytes(27, 118, 0) # Sleep off (important!)
else:
for i... | The code initializes a printer interface with configurable serial parameters and firmware settings. It handles default baud rates, firmware version, and output destinations. If not writing to stdout, it configures printer settings like heating time, density, and initializes the device with delays and reset commands to ... | def __init__(self, *args, **kwargs):
# NEW BEHAVIOR: if no parameters given, output is written
# to stdout, to be piped through 'lp -o raw' (old behavior
# was to use default port & baud rate).
baudrate = 19200
if len(args) == 0:
self.write_to_stdout = True
if... |
def feed(self, x=1):
if self.firmware_version >= 264:
self.write_bytes(27, 100, x)
self.timeout_set(self.dot_feed_time * self.char_height)
self.prev_byte = '\n'
self.column = 0
else:
# datasheet claims sending bytes 27, 100, <x> works,
... | The code prints a barcode with specified text and type on a thermal printer, selecting appropriate firmware-specific command codes from two dictionaries (new_dict for firmware >=264, old_dict for <264). It handles text formatting differences between firmware versions, sending length-byte-prefixed data for newer version... | def print_barcode(self, text, type):
new_dict = { # UPC codes & values for firmwareVersion >= 264
self.UPC_A: 65,
self.UPC_E: 66,
self.EAN13: 67,
self.EAN8: 68,
self.CODE39: 69,
self.ITF: 70,
self.CODABAR: 71,
self... |
def landmarks_detection(self, image, plot=True):
gray = self.get_gray(image)
rects = self.detector(gray, 1)
if not rects.__len__() :
return None, None, None
shapes = []
points = []
for (i, rect) in enumerate(rects):
point = []
shape ... | The main task of the code is to perform facial feature swapping between two images using Thin Plate Spline (TPS) deformation. It detects landmarks in both source and destination images, computes TPS weights for coordinate mapping, warps the source image's pixels onto the destination's facial structure, and blends the r... | def TPS_swap(self, src_image, dst_image, plot=False):
check1, _, src_shapes = self.landmarks_detection(src_image, plot=False)
# src_box_coordinates, src_features, src_cropped = self.bounding_box(src_image, shapes[0])
check2, _, dst_shapes = self.landmarks_detection(dst_image, plot=False)
... |
def get_images(self, rects, video_image, image, edge=25):
if len(rects) == 1:
src_image = self.get_face(video_image, rects[0], edge=edge)
dst_image = image
return src_image, dst_image
elif len(rects)>1:
src_image = self.get_face(video_image, rects[0], ed... | The code performs image swapping in a video frame using methods like PRNet, TPS, or DLN based on input arguments. It detects regions, swaps source and destination images, resizes outputs, and replaces original regions in the video image. The function returns success status and the modified video image, handling multipl... | def swap_operation(self, args, video_image, image, prn=None):
if args.method == 'prnet':
ckeck, output = PRNet_process(prn, video_image, image, args.tf)
if ckeck is None:
return None, video_image
return True, output
edge = self.edge
rects ... |
def extract_features(data, sr, frame_length=2048, hop_length=512):
result = np.array([])
result = np.hstack((result,
zeroCrossingRate(data, frame_length, hop_length),
rmse((data, frame_length,hop_length)),
mfcc(data, frame_length, hop_... | The code's main task is to extract audio features from an input audio file and its augmented versions (noise-added, pitch-shifted, and combined noise-pitch-shifted). It loads the audio data, processes it through multiple augmentation techniques, extracts features for each version, and concatenates all feature sets into... | def get_features(path, duration=2.5, offset=0.6):
data, sample_rate = librosa.load(path, duration=duration, offset=offset,
sr = 8025)
# without augmentation
res1 = extract_features(data, sample_rate)
result = np.array(res1)
# data with noise
noise_data = no... |
def update_pantry(self):
for i, name in enumerate(self.grab_all_pantry_items()):
self.pantryTable.setRowCount(i + 1)
item_name = QtWidgets.QTableWidgetItem(name)
item_name.setText(name)
self.pantryTable.setItem(i, 0, item_name)
def update_today_meals(self):
... | The code's main task is to initialize an object by updating its pantry data and meal plans for today and tomorrow. The `__init__` method triggers three updates: pantry inventory, current day's meals, and tomorrow's meals, ensuring the object's state reflects the latest information upon creation. | def __init__(self):
self.update_pantry()
self.update_today_meals()
self.update_tommorow_meals() |
def get_item_from_text(self):
return self.addItemBox.text()
def get_gram_from_text(self):
return self.addGramsBox.text()
def update_pantry(self):
for i, name in enumerate(self.grab_all_pantry_items()):
self.pantryTable.setRowCount(i + 1)
item_name = QtWidgets.QTableWidget... | This function adds a new food item to a SQLite database if the input name is alphabetic and gram value is numeric. It inserts fixed nutritional values (10 calories, 100 protein) into the 'registry' table, then updates the pantry display. | def add_item(self):
item = self.get_item_from_text()
gram = self.get_gram_from_text()
calories = 10
protein = 100
if item.isalpha() and gram.isnumeric():
db = sq.connect("/home/ioan/PycharmProjects/hackathon/src/pipeline/scran")
c = db.cursor()
... |
def get_item_from_text(self):
return self.addItemBox.text()
def get_gram_from_text(self):
return self.addGramsBox.text()
def update_pantry(self):
for i, name in enumerate(self.grab_all_pantry_items()):
self.pantryTable.setRowCount(i + 1)
item_name = QtWidgets.QTableWidget... | The main task of the code is to add a new food item to a database with predefined nutritional values (10 calories, 100 protein) after validating input: the item name must be alphabetic and the gram value numeric. It connects to a SQLite database, inserts the item into the "registry" table, then closes the connection an... | def add_item(self):
item = self.get_item_from_text()
gram = self.get_gram_from_text()
calories = 10
protein = 100
if item.isalpha() and gram.isnumeric():
db = sq.connect("/home/ioan/PycharmProjects/hackathon/src/pipeline/scran")
c = db.cursor()
... |
def on_update_button(self):
self.update_budget()
self.update_today_meals()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "SCRAN"))
self.todayLabel.setText(_translate("MainWindow", "Today"))
... | This code sets up a GUI for a meal planning application, creating a window with sections to view today's, tomorrow's, and day-after meals, a budget input, and a pantry management system. It includes tables for meal tracking, a tabbed interface to add/edit/remove pantry items, and a method to update daily meals based on... | def setupUi(self, MainWindow):
self.budget = 100000
MainWindow.setObjectName("MainWindow")
MainWindow.resize(995, 679)
MainWindow.setMinimumSize(QtCore.QSize(640, 480))
MainWindow.setTabShape(QtWidgets.QTabWidget.Triangular)
self.centralwidget = QtWidgets.QWidget(MainWind... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.