dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def __set_username(self):
validUserName = False
# while the username entered has a corresponding profile
while validUserName == False:
self.username = input("> () Steam account username -> ")
# scrape data
allData = self.__collect_all_data(self.__get_url(sel... | The main task of the code is to execute three private methods: setting a username, configuring game options, and deleting files. This likely prepares the environment for game-related operations, such as initializing user data, adjusting game settings, or cleaning up temporary files before retrieving or processing game ... | def find_games(self):
self.__set_username()
self.__games_options()
self.__delete_files() |
def check_keydown_event(event,ai_Settings,screen,ship,bullets):
"""Respond to keypresses."""
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:
fire_bullet(ai_Settings,screen,ship,bul... | This function handles game events like quitting, keyboard inputs for ship movement/shooting, and mouse clicks on the play button. It processes Pygame events to update game state, manage user interactions, and trigger actions such as firing bullets or restarting the game when the play button is clicked. | def check_events(ai_Settings,screen,stats, sb, play_button,ship,aliens,bullets):
"""Respons to events """
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_event(event,ai_Settings,screen,ship,bullets... |
def check_fleet_edge(ai_Settings, aliens):
"""Respond appropriately if any aliens have reached an edge."""
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai_Settings,aliens)
break
def ship_hit(ai_Settings, screen, stats, sb, ship, aliens, bullets):
... | This function updates alien positions by checking fleet edges and moving them. It detects collisions between the ship and aliens, triggering a response if hit, and checks if any aliens reach the screen's bottom, initiating appropriate actions. | def update_aliens(ai_Settings, screen, stats, sb, ship, aliens, bullets):
""" Check if the fleet is at an edge,
and then update the postions of all aliens in the fleet.
"""
check_fleet_edge(ai_Settings, aliens)
aliens.update()
#Look for alien and ship collsion
if pygame.sprite.spritecollid... |
def posting_list(data_input):
data = section_removal(data_input)
all_dict = dict()
for index in data:
temp_dict = dict()
for section in index:
if section[:3] == " .I":
temp_dict["id"] = section[3:].strip()
if section[:3] == " .T":
temp_dict["title"] = section[3:].strip()
... | The code processes input data to generate a posting list by cleaning, tokenizing, and normalizing text (title, abstract, authors) using stemming and stop-word removal. It creates word frequency counts, tracks term positions, and structures the data for indexing. The output is stored in a dictionary and written to "post... | def format_posting_list(data_input,is_stem,is_stopword):
data = posting_list(data_input)
stop_words = get_file_data("common_words"," ")[0].split(" ")
ps = PorterStemmer()
for key in data:
title = list(filter(None, [ x.lower() for x in re.sub('[^A-Za-z0-9]+',' ',data[key]["title"]).split(" ") if not x.isnume... |
def query_filtering(query,is_stem,is_stopwords):
temp_query_words = [re.sub('[^A-Za-z0-9]+', '', x) for x in query]
query_words = [x.lower() for x in temp_query_words if not x == '']
if is_stem:
query_words = [ps.stem(x) for x in query_words if x not in stop_words] if is_stopwords else [ps.stem(x) f... | The function processes a query by splitting it into terms, filtering using stemming and stopwords, retrieving relevant documents, and ranking them. For multi-term queries, it filters, retrieves, and ranks documents; for single terms, it directly fetches results. The main task is to retrieve and rank documents based on ... | def search(query,is_stem,is_stopwords):
temp_query = [x for x in query.split(" ") if not x == '']
if len(temp_query) > 1:
unfiltered = query_filtering(temp_query,is_stem,is_stopwords)
query_words = sorted(set(unfiltered))
doc_id = relavance_doc_retrieval(query_words)
return doc_r... |
def sbm(g: gt.Graph, degree_corrected: bool = True) -> CommunityDetectionResult:
scale_exponential_distribution = np.array(g.ep['weight'].a).mean()
state_args = dict(recs=[g.ep['weight']], rec_types=["real-exponential"],
rec_params=[{"alpha": 1, "beta": scale_exponential_distribution}], de... | This function executes community detection on a graph using the specified algorithm, returning either a CommunityDetectionResult or HierarchicalCommunityDetectionResult based on the chosen method. It acts as a dispatcher, routing the input graph and parameters to the appropriate community detection implementation (e.g.... | def run_community_detection(g: gt.Graph, algorithm: Algorithm, **kwargs) -> Union[CommunityDetectionResult, HierarchicalCommunityDetectionResult]:
if algorithm == Algorithm.SBM:
return sbm(g=g, **kwargs)
elif algorithm == Algorithm.ASSORTATIVE_SBM:
return assortative_sbm(g=g)
elif algorithm ... |
def nx_to_gt(g: nx.Graph) -> gt.Graph:
gGt = gt.Graph(directed=False)
gGt.add_vertex(len(g.nodes))
gGt.add_edge_list([(int(e[0]), int(e[1])) for e in g.edges])
_set_vertex_properties(gGt, g)
_set_edge_properties(gGt, g)
_set_graph_properties(gGt, g)
return gGt
def gt_to_nx(g: gt.Graph) -> nx... | This function converts graph objects between different libraries (NetworkX, Graph-tool, igraph) based on specified input and target types. It checks the provided `type_from` and `type_to` parameters, delegates conversion to specialized helper functions (e.g., `nx_to_gt`), and raises an error if the conversion is unsupp... | def convert_graph(g: Union[nx.Graph, gt.Graph, ig.Graph], type_from: GraphType, type_to: GraphType) -> Union[nx.Graph, gt.Graph, ig.Graph]:
if type_from == GraphType.NX and type_to == GraphType.GT:
return nx_to_gt(g)
elif type_from == GraphType.GT and type_to == GraphType.NX:
return gt_to_nx(g)
... |
def set_up_neural_networks(self, train):
if not train:
self.load()
else:
if self.actor is None:
self.set_up_learning_components()
def run_iteration(self, train, render):
previous_state = self.env.reset()
iteration_reward = 0
while True:
... | The code trains a neural network for a specified number of iterations, optionally rendering each iteration and printing progress. If training is enabled, it sets up the neural network, runs iterations to collect rewards, and saves the model after training. | def run(self, iterations=100, render=False, verbose=False, train=True):
self.set_up_neural_networks(train)
for i in range(iterations):
reward = self.run_iteration(train, render)
if verbose:
print('Iteration: {0}, score: {1}'.format(i, reward))
if train:
... |
def get_objects_num_by_classes(selected_classes):
total = 0
for row in DataJson()['classes_table_content']:
if row['name'] in selected_classes:
total += row['obj_num']
return total
def get_predicted_labels_for_batch(labels_batch, model_session_id, top_n, padding):
inference_data = ge... | This function processes images in batches using a progress bar, predicts labels based on model settings, and updates project annotations. It handles multi-label classification, adjusts batch sizes, and ensures all items are annotated by iterating through images, batching them, predicting labels, and applying results to... | def update_annotations_in_for_loop(state):
selected_classes_list = g.selected_classes_list if state['selectedLabelingMode'] == "Classes" else None
total = get_objects_num_by_classes(selected_classes_list) if state['selectedLabelingMode'] == "Classes" else g.output_project.total_items
with card_widgets.labe... |
def clean_up_preview_images_dir():
preview_files_path = os.path.join('static', 'preview_images')
static_files_dir = os.path.join(g.app_root_directory, preview_files_path)
os.makedirs(static_files_dir, exist_ok=True)
sly.fs.clean_dir(static_files_dir)
def get_predicted_labels_for_batch(labels_batch, mod... | The function generates a set of image previews for a project by selecting a subset of labeled images, predicting their labels using a model, and formatting them into a list with URLs and titles derived from the predictions. It cleans the preview directory, retrieves project metadata, filters images based on labeling mo... | def get_images_for_preview(state, img_num):
clean_up_preview_images_dir()
g.output_project_meta = f.get_project_meta_merged_with_model_tags(g.project_dir, state)
selected_classes_list = g.selected_classes_list if state['selectedLabelingMode'] == "Classes" else None
labels_batch = []
for label_info... |
def speed_calc(self):
return self.speed_control.get()
def remove_inactive():
for k in inactive_delete.items():
if k[0] in cells:
cells.pop(k[0])
inactive_delete.clear()
def cell_neighbors():
print('cell_neighbors')
neighbors = {}
census = []
for cell i... | The main task of the code is to iteratively update a grid's cell visuals by applying status-specific colors and text, using a recursive timer to animate changes. It processes each cell from a dictionary, configures GUI elements with corresponding colors, and schedules the next update. When iteration completes, it trigg... | def draw_changes(self, it_dict=None):
print('draw_changes')
if it_dict is None:
it_dict = iter(cells.items())
cell = next(it_dict, -1)
if cell != -1:
cell_color = colors[cell[1]['status']]['color']
text_color = colors[cell[1]['status']]['text']
... |
def generate_optionmenu(self):
global var
var = tk.StringVar(self.root)
list_values = [
'Select a way to get started',
'Pick 3-4 adjoining cells',
'Randomly assign cells',
'Pre-Programmed: Cross'
]
## default to the first value in ... | The function processes user selections from an option menu, resetting the board (sides=9) and triggering specific actions: randomly assigning cells, manual selection of adjoining cells, or applying a predefined "Cross" pattern. It regenerates the menu and updates game state/behavior based on the chosen option, calling ... | def optionmenu_loop(self, value):
global sides, cells
sides = 9 ## always a reset when a new choice is picked from the list of values
if value == "Randomly assign cells": ## assess value and pick accordingly
self.generate_optionmenu() ## rerun the option menu to default appropria... |
def _init_vocab(self):
"""Populates vocab dictionary with default special symbols.
Adds PAD, UNK, SOS, EOS tokens as well as ASCII letters, digits,
punctuation and space character. Initializes all with frequency of 0.
Also initializes vocab_size to match size of vocab dictionary... | The code initializes a BPE Tokenizer with three modes: unconfigured, pretrained (via JSON file), or new vocabulary training (using a corpus and specified size). It sets default symbols, loads or trains the vocabulary, and prepares encoder/decoder mappings. The main task is to configure the tokenizer's vocabulary based ... | def __init__(self, corpus_or_txt_path=None, vocab_size=None, vocab_or_json_path=None):
"""Constructor to initialize BPE Tokenizer.
Supports three initialization modes:
1) Unconfigured: Leave arguments unspecified
2) Pretrained: Provide pretrained vocab_or_json_path
3) New vocab:... |
def is_flush(self) -> bool:
"""Return if the Combination is a flush or not."""
for count in self.group_by_color().values():
if count >= 5: return True
return False
def __str__(self) -> str:
return f"{[card.__str__() for card in self.__card_l... | This code checks if a poker hand is a straight flush by first verifying if it's a flush. It then checks for specific A-2-3-4-5 combinations in each suit. If not found, it sorts the cards, groups them by suit, and iterates through their values to detect five consecutive ranks in sequence. If five consecutive values are ... | def is_straight_flush(self) -> bool:
"""Return if the Combination is a straight flush or not."""
if self.is_flush():
# Check if we are in one of first straight case (with ACE as ONE)
if ( all(card in self.__str__() for card in ["AC", "2C", "3C", "4C", "5C"]) or
... |
def is_pair(self) -> bool:
"""Return if the Combination is a pair or not."""
for count in self.group_by_value().values():
if count == 2: return True
return False
def is_two_pair(self) -> bool:
"""Return if the Combination is a two pair or not."""
... | The main task of the code is to determine if a poker hand is a full house by checking if it contains either a pair or two pairs combined with a three-of-a-kind. It returns `True` if both conditions are met, otherwise `False`.) | def is_full_house(self) -> bool:
"""Return if the Combination is a full house or not."""
if (self.is_pair() or self.is_two_pair()) and self.is_three_of_kind():
return True
return False |
def is_royal_flush(self) -> bool:
"""Return if the Combination is a royal flush or not."""
# Check if we are in one of first straight case (with ACE as ONE)
if ( all(card in self.__str__() for card in ["AC", "KC", "QC", "JC", "10C"]) or
all(card in self.__str__() for card in ["AD", ... | This code determines the rank of a poker hand by checking for specific combinations in descending order of precedence, returning the highest matching PokerHandRank enum value, such as ROYAL_FLUSH or HIGH_CARD, based on the hand's card configuration. | def poker_hand_rank(self) -> PokerHandRank:
"""Return what PokerHandRank the Combination is."""
if self.is_royal_flush(): return PokerHandRank.ROYAL_FLUSH
if self.is_straight_flush(): return PokerHandRank.STRAIGHT_FLUSH
if self.is_four_of_kind(): return PokerHandRank.FOUR_OF_KIND
... |
def sort_by_value(self) -> None:
"""Sort the Combination's card_list by descending value order."""
self.card_list.sort(key = lambda card: card.__value__().value, reverse = True)
def value_list(self) -> list[Value]:
"""Return a Combination's value list, a list of every Card's value."""
re... | The function `value_to_compares` generates a list of card values based on the current poker hand's rank, prioritizing critical values for comparison. It handles cases like High Card, Pairs, Three of a Kind, Straights, Flushes, Full House, Four of a Kind, and Royal Flush, returning the most relevant values to determine ... | def value_to_compares(self) -> list[Value]:
"""Return the most important card_list, depending of Combination's PokerHandRank"""
self.sort_by_value()
value_list: list[Value] = self.value_list()
match (self.poker_hand_rank()):
case PokerHandRank.HIGH_CARD:
... |
def send(self, data):
crc = add_crc(data)
msg = [0xFF, 0xFF]
msg += data
msg.append(crc)
#self.l.info('sending: {}'.format(msg))
self.ser.write(msg)
self.ser.flush()
def get_position(self):
""" Readback all the current joint positions """
channel ... | The main task of the code is to initialize and prepare a robotic system by creating timers for status updates and control loops, waiting for the system to start, sending initialization and enable commands, retrieving position data, calculating hardware values, and setting up a periodic control timer to execute the cont... | def start_up(self):
self.status_timer = self.create_timer(0.1, self.status_publisher, callback_group=self.status_group)
while not self.running:
time.sleep(0.5)
self.send(self.initialize)
time.sleep(0.302)
#self.send(self.disable)
#time.sleep(0.002)
#se... |
def parse_html_file(path: Path) -> Document:
content = load_raw_text_with_soup(path)
metadata = get_full_metadata_from_html_file(path)
return Document(page_content=content, metadata=metadata)
def split_document(documents: list[Document]):
splitter = RecursiveCharacterTextSplitter(
chunk_size=CHU... | The function processes an HTML file by parsing its content, splitting it into smaller documents, and saving them as JSON files in a specified directory. It ensures the output directory exists, skips processing if the JSON file already exists, and avoids redundant work by checking file existence before processing. | def preprocess_and_save_html_file(path: Path) -> None:
if not SPLIT_DATASET_DIR.exists():
SPLIT_DATASET_DIR.mkdir(parents=True)
save_path = SPLIT_DATASET_DIR / f"{path.name[:-5]}.json"
if save_path.exists():
return
doc = parse_html_file(path)
splitted_docs = split_document([doc])
... |
def parse_post_photo(post, photo_dir):
'''
converts photo tag to markdown image link
'''
post_photo = '\n\n'.format(src=post['photo'])
return post_photo
def parse_post_text(post):
# TODO: handle reply-to
post_raw_text = post['text']
post_parsed_text = ''
if type(pos... | The main task of the code is to generate formatted text from a post object by combining optional image and media content with the post's text. The function constructs a string by appending results from helper functions: `parse_post_photo` for images, `parse_post_text` for the main text, and `parse_post_media` for media... | def parse_post(post, photo_dir, media_dir):
'''
converts post object to formatted text
'''
post_output = ''
# optional image
if 'photo' in post:
post_output += str(parse_post_photo(post, photo_dir))
# post text
post_output += str(parse_post_text(post))
# optional media
... |
def create_faceted_brep(self):
self.create_vertices()
faces = []
for polygon in self.settings["blender_void"].data.polygons:
faces.append(
self.file.createIfcFace(
[
self.file.createIfcFaceOuterBound(
... | This function generates a Blender mesh from IFC data by selecting an appropriate method based on schema version or user settings: creating faceted BREP for IFC2X3 or forced faceting, triangulated face sets for forced triangulation, or polygonal face sets otherwise. | def create_blender_mesh(self):
self.ifc_vertices = []
if self.file.schema == "IFC2X3" or self.settings["should_force_faceted_brep"]:
return self.create_faceted_brep()
if self.settings["should_force_triangulation"]:
return self.create_triangulated_face_set()
return... |
def display_cohort_cagr(df_marker_index, df, arr_low, arr_hi, g_e=0):
st.markdown("---")
a0, a1 = (arr_low, arr_hi)
interval_ranges = pd.IntervalIndex.from_tuples([(a0, a1)])
df_r = cohort_cagr_over_marker_series(df=df,
df_marker_index=df_marker_index, interval_... | The main task of the code is to generate multiple visualizations comparing company growth metrics (CAGR and time-to-growth) across IPO cohorts for ARR ranges between $200M and $400M. It creates bar charts, scatter plots, histograms, and box plots to analyze implied CAGR, growth timelines, and cohort distributions, usin... | def plots_over_arr_ranges(bins, cohort_labels, df_marker_index, df):
for a, b in [(200,400)]:
df_r = display_cohort_cagr(df_marker_index, df, a, b, 0.9)
df_r = add_ipo_cohort_info(df_r, bins=bins, labels=cohort_labels)
df_r['Time (months)'] = df_r['Time (Yrs)'] * 12
'''
####... |
def benchmark_camera_ready(df):
bins = [2002, 2015, 2018, 2022]
cohort_labels = [f"{b0 + 1}-{b1}" for b0, b1 in zip(bins, bins[1:])]
cohort_labels[-1] = f"{bins[-2] + 1}-Today"
df = df[df['Status'] == 'Public']
def preprocess(df):
df[['ARR_p', 't_p']] = df.groupby('ticker')[['ARR', 't']].sh... | The code processes a financial dataframe for benchmarking analyses. It filters companies by status (Public/Private), adjusts ticker symbols, calculates lag/lead metrics for ARR and time variables, and executes specific benchmarking functions (e.g., CAGR analysis) based on the 'analysis' parameter. The main task is to p... | def benchmark_main(df, analysis):
if analysis == 'Camera-ready':
return benchmark_camera_ready(df)
list_private_cos()
df.loc[df['ticker'] == 'DB', 'ticker'] = 'Private'
selected_status = st.sidebar.selectbox('Type', ('All', 'Public', 'Private'))
if selected_status != 'All':
df = df[... |
def make_grid(grid_size):
grid = np.full((grid_size, grid_size, 3), (255,255,255), dtype = np.uint8)
# middle obstacle
for i in range(50):
for j in range(50):
grid[i+75][j+80] = (0, 0, 0)
#parked car 1
length = 40
width = 20
for i in range(width):
for j in r... | The main task of the code is to plan a path for a differential drive robot on a 200x200 grid from a start position (20,25) to an end position (180,85). It generates a visual plot of the planned path, saves it as 'DiffDrive.png', and creates a video ('diffdrive.mp4') showing the robot's movement along the path using the... | def main():
save_path = os.path.join("data")
if os.path.exists(save_path):
shutil.rmtree(save_path)
os.mkdir(save_path)
else:
os.mkdir(save_path)
grid = make_grid(200)
car_length = 12
car_width = 25
start_pos = (20,25)
end_pos = (180, 85)
path = planner... |
def make_grid(grid_size):
grid = np.full((grid_size, grid_size, 3), (255,255,255), dtype = np.uint8)
# middle obstacle
for i in range(50):
for j in range(50):
grid[i+75][j+80] = (0, 0, 0)
#parked car 1
length = 40
width = 20
for i in range(width):
for j in r... | The main task of the code is to plan a car's path on a 200x200 grid from a start to end position using a planner, simulate parking maneuvers, visualize the path with a plot and video, and save outputs to a directory. It creates a 'data' folder, generates a grid, computes the path, plots coordinates, saves a PNG image, ... | def main():
save_path = os.path.join("data")
if os.path.exists(save_path):
shutil.rmtree(save_path)
os.mkdir(save_path)
else:
os.mkdir(save_path)
grid = make_grid(200)
car_length = 12
car_width = 25
start_pos = (20, 25, 0)
end_pos1 = (130, 60, 0)
path = plan... |
def resetHeader():
os.system('clear')
print("---=== Tesla Power Modelling System ===---")
def viewAppQuestions(house):
resetHeader()
option=True
while option:
print("""
1. Appliance Ratings
2. All Appliance Usage plot
3. Appliance Usage Plot
4. Day General Us... | This function provides a menu-driven interface for managing household appliances, allowing users to view usage data, search appliances, add new ones, or return to the main menu. It checks for existing appliances before plotting/searching and ensures valid input, displaying appropriate messages for empty data or invalid... | def menuModelling(house):
resetHeader()
option=True
while option:
print("""
1. View Appliance Usage
2. Search Appliance
3. Add Appliances
4. Go back
""")
option=input("What would you like to do? ")
if option=="1":
#Ensure there are... |
def get_webdriver_exec(self):
webdriver_exec = self.mapped_browsers[self.browser]["executable_path"]()
if webdriver_exec:
webdriver_exec = webdriver_exec.install()
return webdriver_exec
def set_general_options_to_browser(self):
options = self.mapped_browsers[self.browser]["o... | The main task of the code is to launch a selected browser using a specified webdriver executable path and browser options. It retrieves the webdriver executable, configures browser options, initializes the browser driver with these settings, and logs the browser version. The function allows customization of the executa... | def launch_selected_browser(self):
webdriver_exec = self.get_webdriver_exec()
options = self.set_general_options_to_browser()
self.driver = self.mapped_browsers[self.browser]["driver"](
executable_path=webdriver_exec, options=options
) # you can set your custom executable_pa... |
def handle_button_click(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
if self.button_rect.collidepoint(pygame.mouse.get_pos()):
self.incr_clients()
def reset_dir_texts(self):
self.progresses = []
self.file_names = []
for directory in self.load_balance... | This code defines a game loop that continuously processes Pygame events (like quitting or button clicks), resets text elements, updates the screen with new content, and refreshes the display to render changes in real-time. It maintains the application's state and user interaction handling until the user exits. | def loop(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
self.handle_button_click(event)
self.screen.fill((255, 255, 255))
self.reset_dir_texts()
self.reset_client_te... |
def init_objects(self):
self.dir_rects = []
for i in range(0, self.DIR_NUMBER):
self.dir_rects.append(pygame.rect.Rect(i * self.screen.get_width() / self.DIR_NUMBER, 0,
self.screen.get_width() / self.DIR_NUMBER,
... | The code initializes a Pygame application by setting up a display window with a specific resolution, initializing variables for managing files and clients, creating and starting a load balancer, and preparing game objects and text elements. It then enters the main loop to run the application. | def __init__(self):
pygame.init()
pygame.display.init()
resolution = (1450, 800)
self.screen = pygame.display.set_mode(resolution)
self.files_to_remove = []
self.DIR_NUMBER = 5
self.CLIENTS_NUMBER = 0
self.client_list = []
self.load_balancer = MyL... |
def apply_rules(self, rules, out_field=None):
"""
Apply a number of rules to objects.
Parameters
----------
rules : list
List of dictionaries of keyword arguments to single_rule
Returns
---------
pd.series : Boolean series indicating if all r... | The function classifies objects based on threshold and adjacency rules, assigning a specified class name to their 'class' field. It applies rules to determine eligible objects, updates the class field conditionally (overwriting or only for unclassified objects), and optionally counts passed rules. The method optimizes ... | def classify_objects(self, class_name,
class_fld=None,
threshold_rules=None,
adj_rules=None,
overwrite_class=False,
count_passed_rules=True):
"""Classify objects according to rules passed... |
def create_population(self):
self.chromosomes = []
for i in range(self.pop_size):
chromosome = np.arange(0, self.chromosome_size)
self.chromosomes.append(self.shuffle(chromosome))
def population_fitness(self):
distance = []
for c in self.chromosomes:
... | The code solves the Traveling Salesman Problem (TSP) using a genetic algorithm. It initializes a population of potential paths, iterates over generations to evaluate fitness, selects the optimal path (lowest distance), and evolves new populations until completion. The final optimal path is returned after specified gene... | def solve_tsp(self, tsp_data):
self.tsp_data = tsp_data
self.chromosome_size = len(tsp_data.product_locations)
self.create_population()
optimal_path = None
for i in range(generations):
fitness = self.population_fitness()
optimal_path = self.chromosomes[fi... |
def update_totals(self):
self.player.total = get_sum(self.player.cards)
self.house.total = get_sum(self.house.cards)
if len(self.deck) == 0:
self.shuffle_deck()
def check_state(self):
if self.house.total > 21:
# print('You win!')
self.score[0] += 1
... | The code's main task is to either update game totals and check the current state if the reset flag is False, or reset the game entirely if the reset flag is True. This conditional logic determines whether to continue processing game data or restart the game based on the value of `self.reset`.)> | def run(self):
if not self.reset:
self.update_totals()
self.check_state()
else:
self.reset_game() |
def reset_board(self):
teams = ["w", "b"]
# Init Pawns
for i in range(0, 8):
self.board["b"][i] = Pawn(f"b{i}", teams[0])
self.board["g"][i] = Pawn(f"b{i}", teams[1])
backLinePlace = {"R": [0, 7], "N": [1, 6], "B": [2, 5], "Q": [3], "K": [4]}
# TODO: NE... | The code initializes a chess game, sets up a CSV writer, randomly assigns player turns, and processes moves. It alternates between white and black players, records each move, checks for a win, and writes move data to a CSV file. The game loop continues until a player exits or a win is detected, ending with a forfeit me... | def InitGame(self):
# Initialize custom CSV_Writer Object
self.writer = CSV_Writer.CSV_Writer()
# Initiate Game here
print("Welcome To Basic Chess!")
# random player order
sides = ["w", "b"]
random.shuffle(sides)
self.reset_board()
# Object ass... |
def solve_cross_section(L, A, R, slant_length=False):
"""
Given cross-section dimension constraints, find the coordinates
of all points needed to construct arcs and lines.
L : array of all lengths
A : array of all angles
R : array of all radii
slant_length: if True, return a tuple of l1, l2,... | The function generates a closed 2D cross-section profile by combining left and right profiles. It calculates key points (P, C) using solve_cross_section, constructs the left profile with get_profile, creates the mirrored right profile via get_offset_profile, and stacks them with the initial point to form a closed face ... | def get_cross_section_face(L, A, R, t, numpoints=11, validate=True):
"""
Given the dimensions, get the cross-section closed-face.
"""
# Calculate the points
P, C = solve_cross_section(L, A, R)
left_profile = get_profile(P, C, R, t, numpoints, validate)
right_profile = get_offset_profile(t, P... |
def finished(self) -> bool:
if self.pointer >= len(self.elements):
return True
return False
def read(self) -> T:
self.pointer += 1
return self.elements[self.pointer - 1]
def decrement(self) -> None:
self.pointer -= 1
if self.pointer == -1:
error("... | This function reads items from a reader until an 'exit' token is found, handling nested 'enter' tokens. It tracks nesting levels and collects items into a list, optionally including the 'exit' token if 'keep' is True. If the reader finishes without finding a proper exit, it raises an error. The result is a list of item... | def until(self, enter: str, exit: str, keep: bool = False):
level = 0
inside = False
result: list[T] = []
while not self.finished():
item = self.read()
if inside:
if item == enter:
level += 1
if item == exit ... |
def find_best_node(instances, labels):
"""Find the best point to create a node in the decision tree
Args:
instances (numpy.ndarray): Instances, numpy array of shape (N, K)
N is the number of instances
K is the number of attributes
labels (numpy.ndarray): Cla... | The function `induce_decision_tree` recursively constructs a decision tree by selecting the optimal attribute and split value to partition the dataset. It sorts instances based on the chosen attribute, splits them into left/right subsets, and checks if further splitting is possible. If not, it returns a leaf node; othe... | def induce_decision_tree(instances, labels, depth=0):
"""Induce a decision tree for a given dataset
Args:
instances (numpy.ndarray): Instances, numpy array of shape (N, K)
N is the number of instances
K is the number of attributes
labels (numpy.ndarray): Cl... |
def getTolerances(tolerances):
rtn = {}
for relationship, _ in tolerances.items():
rtn[relationship] = getToleranceInput(relationship)
return rtn
def getSettings():
return {
'constraint': getSettingsInput(f"What's magnitude of the scale we're using? (i.e. 100 for -100 to 100): "),
... | The main task of the code is to collect user preferences for traits by processing a JSON file, handling input constraints, and saving the results. It reads tolerances and settings, prompts users to assign weights (numbers or 'na') to each trait, manages input errors by reverting questions, and writes the final answers ... | def generate(outFile):
with open(args.preferencesFile, 'r') as f:
tolerances, traits, settings = jsonc.load(f)
traits = OrderedDict(traits)
answers = OrderedDict()
# First get tolerances and settings
print("Tolerances:")
tolerances = getTolerances(tolerances)
print()
print(... |
def space2MultiPolygon(space, side_len=1):
# Autoreshape it if it's flat
if len(space.shape) == 1:
space = space.reshape((int(len(space)/3), 3))
return MultiPolygon([Polygon(corners) for corners in compute_corners(space, sideLen=side_len)])
def within_boundary(self):
for square in self.squar... | The main task of the code is to reset the environment's state by generating a valid initial observation. It initializes the random seed, samples a new observation from the observation space, converts it to a geometric representation (MultiPolygon), and ensures it meets validity and boundary constraints. If a seed is pr... | def reset(self, seed=None, start_valid=True, options=None):
# We need the following line to seed self.np_random
super().reset(seed=seed)
self.steps = 0
# Why does the Space constructor have a seed and not the .sample() method??
if seed is None:
newObs = self.observat... |
def multiPolygon2Space(multi, side_len=1):
# Skip the first coordinate, because the first and last are the same
rtn = compute_coords([list(p.exterior.coords)[1:] for p in multi.geoms])
# Then normalize them to all be positive (due to our space requirements)
for c in rtn:
if c[2] < 0:
... | The code defines a `step` method in a reinforcement learning environment. It updates the environment state by applying an action to the current observation (representing geometric shapes), enforces bounds (clipping or looping values), and returns the new observation, reward, termination status, and additional info. The... | def step(self, action):
self.steps += 1
# Compute the shifted squares
obs = multiPolygon2Space(self.squares)
if self._flat:
assert action.shape == (self.N*3,), f'Action given to step is the wrong shape (Expected shape ({self.N*3},), got {action.shape})'
#TODO: I'm... |
def scrape_list():
"""
Establishes a connection with wikipedia's pages listing philosophers
then scrapes every url of every catalogued philosopher. Note that
all of these links are the canonical urls, so no check is needed.
"""
list_of_philosophers = []
wiki_philosopher_lists = ['/wiki/List_... | The code scrapes philosopher data from Wikipedia, constructs nodes with details, validates links and node integrity, and exports the cleaned dataset. It ensures accuracy by checking each link and node, then summarizes and outputs the final validated records. | def main():
global nodes
global node_pages
print("Discovering Philosophy Network...\n")
# Scrape the list of wiki pages first
philosopher_list = scrape_list()
node_pages = [wiki_page for _, wiki_page, _ in philosopher_list]
# Create a dictionary of nodes using the scrap philosopher functio... |
def removal(string):
"""Remove any non-numeric characters of specific structure from a string"""
# Remove [1]
proc = re.sub('\[\d+\]', '', string)
return proc
def find_date(string):
orig_string = copy.copy(string)
string = re.sub('c\.', '', string)
string = re.sub('circa', '', string)
n... | The code extracts a philosopher's birth date and geographic coordinates (latitude/longitude) from their Wikipedia page. It parses HTML to locate infobox data, identifies the 'born' entry, processes the date (handling BC/AD formats and validation), and retrieves location data via multiple fallback methods if initial par... | def get_wiki_birth(philosopher_extension):
wiki_url = "https://en.wikipedia.org"
url = wiki_url + philosopher_extension
page = requests.get(url)
page.raise_for_status()
soup = BeautifulSoup(page.text, 'html.parser')
div = soup.find_all(['th','td'], {'class': ['infobox-label', 'infobox-data']})
... |
def sort_array2(array: list[tuple[str, str, str]]) -> list[tuple[str, str, str]]:
"""sort 2D array of str but if they are all numeric then it will sort them as numeric
specifically it will sort them index 1,0 because it is expecting x,y.
This is to ensure it is in the right order for XY grid processing"""
... | The code combines multiple images into a single output image by arranging them in a grid based on sorted coordinates. It dynamically calculates the output size, blends overlapping regions using linear gradients or seam masks depending on the blend mode, and pastes images row by row, ensuring seamless horizontal and ver... | def invoke(self, context: InvocationContext) -> ImageOutput:
new_array = [json.loads(s) for s in self.xyimages]
sorted_array = sort_array2(new_array)
images = [context.images.get_pil(item[2]) for item in sorted_array]
x_coords = sort_array(list({item[0] for item in sorted_array}))
... |
def write_setup(self, outfile):
with open(outfile, "w") as fo:
fo.write("#!/usr/bin/env python\n")
ctx = text_wrap('''
import sys
import os
from setuptools import setup
from Cython.Build import cythonize
py_... | The main task of the code is to compile a Python file (pyf) into a shared object (.so) file using a setup script and interpreter. It creates a temporary directory, writes a setup file, executes the compilation command, moves the generated .so file, deletes the original .py file if successful, and cleans up temporary fi... | def compile(self, pyf):
self.logger.info("start compile %s file", pyf)
fin = False
with Tempdir() as td:
tf = os.path.join(td, "ccbuild.py")
self.write_setup(tf)
cmd = [self.interpreter, tf, pyf]
_so = self.call(cmd, out=True, shell=False,
... |
def list_compile_files(self):
if os.path.isfile(self.pdir):
if self.pdir.endswith(self.py_ext):
copy_to_dir(self.pdir, self.cdir)
py = os.path.join(self.cdir, os.path.basename(self.pdir))
self.compile_file.append(py)
if py == self.pdir:... | The main task of the code is to compile multiple files in parallel using a process pool if available, or sequentially if only one thread is allowed, while handling errors gracefully and cleaning up source files afterward. | def compile_all(self):
if len(self.compile_file) == 0:
self.list_compile_files()
nproc = min(self.threads, len(self.compile_file))
try:
if nproc > 1:
with ProcessPoolExecutor(nproc) as p:
p.map(self, self.compile_file)
else:... |
def _create_clusters(self, centroids):
clusters = [[] for _ in range(self.k)]
for idx, sample in enumerate(self.X):
centroid_idx = self._closest_centroid(sample, centroids)
clusters[centroid_idx].append(idx)
return clusters
def plot(self):
fig, ax = plt.subplots(f... | The code implements the K-Means clustering algorithm's prediction phase. It initializes centroids randomly, iteratively updates cluster assignments and centroids, checks for convergence, and returns final cluster labels for input data $ X $. The process optimizes cluster membership and centroid positions until converge... | def predict(self, X):
self.X = X
self.n_samples, self.n_features = X.shape
# init centroids
random_sample_idxs = np.random.choice(self.n_samples, self.k, replace=False)
self.centroids = [self.X[idx] for idx in random_sample_idxs]
# optimization
for _ in range(se... |
def exchange_device_access_token_for_service_account_access_token(
device_access_token, service_account_email
):
"""Exchanges device access token to service account access token."""
# [START iot_access_token_service_account_token]
# device_access_token = 'device-access-token'
# service_account_email... | This code handles command-line operations for IoT device management and cloud services, validating required parameters and executing tasks like token exchange, access token generation, Pub/Sub messaging, and device command sending. It ensures all necessary arguments are provided before invoking corresponding functions ... | def run_program(args):
"""Calls the program."""
if args.command == "exchange-device-token-for-service-account-token":
if args.service_account_email is None:
print("Please specify the service_account_email parameter.")
return
if args.device_access_token is None:
... |
def getDHT(self):
data = dict()
curTry = 0
while curTry < self.dht_tries:
try:
outTemp = self.dht.temperature * (9 / 5) + 32
outHumidity = self.dht.humidity
data["outTemp"] = outTemp
data["outHumidity"] = outHumidity
... | This function generates an infinite loop of data packets containing timestamped sensor readings. It constructs a packet dictionary, conditionally updates it with values from various sensors (DHT, rain, wind, temperature, soil, BMS, VE), and yields the packet. Each iteration checks available hardware interfaces, aggrega... | def genLoopPackets(self):
while True:
# Create packet
packet = {"dateTime": int(time.time() + 0.5), "usUnits": weewx.US}
if self.dht_pin is not None:
packet.update(self.getDHT())
if self.rain_addr is not None:
packet.update(self.g... |
def parse_cmdline():
parser = argparse.ArgumentParser()
parser.add_argument(
"--input",
type=str,
nargs="+",
required=True,
help=(
"Input filename(s): file(s) of undefined symbols produced by running"
"`nm -uC <archive>`."
),
)
pars... | The main task of the code is to process input files, parse command-line arguments, and generate output in C++, JSON, or XML formats. It reads messages and modules, handles errors during input reading, and conditionally writes outputs. For XML, it extracts enum information from C++ output if available, then writes struc... | def main():
args = parse_cmdline()
try:
modules, messages = read_input(args.input)
except Exception as e:
raise Exception(f"{str(e)} from file {args.input}")
if args.cpp_output is not None:
write_cpp(messages, modules, args.cpp_headers, args.cpp_output)
if args.json_output ... |
def random_control_bits(n):
return [random.getrandbits(1) for _ in range((2*n + 1) << n )]
def permutation(c):
m = 1
while (2*m-1) << (m-1) < len(c):
m += 1
assert (2*m-1) << (m-1) == len(c)
n = 1 << m
pi = list(range(n))
for i in range(2*m-1):
gap = 1 << min(i, 2*m-2-i)
... | The code tests the consistency of a permutation transformation process. It runs `test_num` trials, generating random control bits of size `n`, applying a permutation, then recomputing control bits and re-permuting. If the final permutation differs from the original, it counts as a failure. The goal is to verify whether... | def test_random_control_bits(n, test_num):
fail = 0
for _ in range(test_num):
cb = random_control_bits(n)
p = permutation(cb)
cb2 = controlbits_recur(p)
p2 = permutation(cb2)
if p != p2:
fail += 1
successes = test_num - fail
print(f"Tested {test_num} t... |
def random_control_bits(n):
return [random.getrandbits(1) for _ in range((2*n + 1) << n )]
def permutation(c):
m = 1
while (2*m-1) << (m-1) < len(c):
m += 1
assert (2*m-1) << (m-1) == len(c)
n = 1 << m
pi = list(range(n))
for i in range(2*m-1):
gap = 1 << min(i, 2*m-2-i)
... | This function tests the consistency of the `controlbits_extended` function by generating random control bits, applying permutations, and checking if the extended control bits produce the same permutation. It runs `test_num` trials for size `n`, counting failures where the original and extended permutations differ. The ... | def test_random_control_bits_extended(n, test_num):
fail = 0
for _ in range(test_num):
cb = random_control_bits(n)
p = permutation(cb)
cb2 = controlbits_extended(p)
p2 = permutation(cb2)
if p != p2:
fail += 1
successes = test_num - fail
print(f"Tested ... |
def _add_features(self,data:pd.DataFrame,scamy_words:List[str]):
""" add all features into the DF
"""
data = self._add_length(data)
data = self._add_scamy_words(data, scamy_words)
data = self._add_numbers(data)
return data
def _fit(self, df:pd.DataFrame):
self.ss.... | The main task of the code is to preprocess and transform a DataFrame by removing duplicates and missing values, adding features, scaling numerical data, and encoding text using CountVectorizer or TfidfVectorizer. It returns feature matrix X and target y, optionally including raw text data, for machine learning model tr... | def transform(self,df:pd.DataFrame):
"""Process, encodes and transforms DF into features
for the model to train and returns X and Y
"""
# remove dups
df.drop_duplicates(inplace=True)
# remove NAs
df.dropna(inplace=True)
df = self._add_features(df,self.sc... |
def display_stock_line_graph(company):
st.title(f"{DICT_OF_COMPANIES[company]} Stocks Dashboard")
stock_data = get_required_table(PROJECT_ID, TABLE_ID_YFINANCE, company)
stock_data.sort_values(by='Date')
fig = go.Figure()
fig.add_trace(go.Scatter(x=stock_data["Date"], y=stock_data["Close"], name="c... | The code creates a Streamlit web app for stock analysis, featuring a navigable sidebar with "Home" and "Company Analysis" pages. The Home page introduces the app's purpose and features (line graphs, sentiment analysis, word clouds). The Company Analysis page lets users select a company to view stock data, news, and twe... | def main():
# Set up page configuration
st.set_page_config(
page_title="Stock Analysis App",
page_icon=":chart_with_upwards_trend:",
)
# Create a sidebar for navigation
st.sidebar.title("Navigation")
pages = ["Home", "Company Analysis"]
selected_page = st.sidebar.radio("Go t... |
def authorize():
auth = tw.OAuthHandler(keys.key, keys.keySecret)
auth.set_access_token(keys.token, keys.tokenSecret)
api = tw.API(auth, wait_on_rate_limit=True)
return auth, api
def initSearchArray():
keywords = readInKeywords()
keywords = addHashtags(keywords)
return keywords
def searchLoo... | The main task of the code is to search for and retrieve a specified number of tweets (100) using a Twitter API, authorized via the `authorize()` function, and keywords initialized by `initSearchArray()`, then process these tweets through the `searchLoop()` function. | def main():
#Establish number of tweets
numTweets = 100
#Authorize
auth, api = authorize()
#Initialize Search Arrays
keywords = initSearchArray()
#Perform Searches
searchLoop(keywords, auth, api, int(numTweets)) |
def howToUse():
print("*** Begin User Input ***\n")
def getFileName():
name = input("Please enter the file name: ")
return name
def cleanFile(fileName):
newOutName = "CLEAN_" + fileName
with open(fileName) as csvFile:
csvReader = csv.reader(csvFile, delimiter=',')
for row in csv... | The main task of the code is to execute a sequence of steps: display usage instructions, prompt the user for a filename, process the file by cleaning its content, and finally display a congratulatory message upon completion. | def main():
howToUse()
fileName = getFileName()
cleanFile(fileName)
congrats() |
def gemiddeldeBerekenen(variabele):
totaal = 0
lenoflist = count(variabele)
for i in variabele:
totaal += i
gemiddelde = totaal / lenoflist
return int(gemiddelde)
def mediaan(variabele):
n = count(variabele)
if n < 1:
return None
if n % 2 == 1:
return sorted(varia... | The main task of the code is to calculate and return four statistical measures—mean, median, mode, and standard deviation—for a given dataset of variables. It utilizes helper functions to compute each metric and aggregates the results into a tuple for output. | def gegevens(variabelen):
gemiddelde = gemiddeldeBerekenen(variabelen)
Mediaan = mediaan(variabelen)
Modus = modus(variabelen)
std = stddev(variabelen)
return gemiddelde, Mediaan, Modus, std |
def get_guess(self, prompt="Enter word: ") -> None:
while True:
try:
w = input(prompt).lower()
except EOFError as e:
if input("Are you sure you want to end? [y/n]").lower() not in ('y'):
sys.exit()
if w in self.VALID_WORDS:
... | The code implements a word guessing game where the player attempts to guess a target word within a limited number of tries. It displays the word value, processes each guess, checks validity, generates regex patterns, shows possible matches, and determines success when all letters are correctly guessed. The game ends af... | def play_person_game(self):
print(f"Word value: {self.word}")
for i in range(self.MAX_GUESS_NUM):
print(f"On guess {i}")
self.get_guess("Enter guess here: ")
guess_arr = self.check_guess()
print(self.generate_regex())
print(self.get_possible_w... |
def createObjects(block_type: str, content: str, **keys) -> list[dict]:
contents = splitContent(content)
return [BLOCK_MAP[block_type](content=x, **keys).__dict__ for x in contents]
def createBlocks(block: dict, list_type: str = "") -> list[dict]:
match (block_type := block["type"]):
case "thematic_... | This function converts a Jupyter notebook (as JSON) into a list of structured blocks. It processes code cells by combining source code and outputs into Python code blocks, and markdown cells by parsing text with plugins (tables, lists, etc.) into corresponding block elements. The result is a list of block dictionaries ... | def createNotebook(notebook) -> list[dict]:
notebook = json.loads(notebook)
blockList: list[dict] = []
for cell in notebook["cells"]:
match cell:
case {"cell_type": "code", "source": source, "outputs": outputs, **rest}:
content = "".join(source)
if output... |
def prefixComments():
currentYear = int(date.today().year)
license = \
'''/*
* Copyright {} Denis Yaroshevskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* ... | The main task of the code is to concatenate and return a complete code string by combining prefix comments, prefix code, generated main code, and suffix code components. The function `generateCode()` sequentially appends outputs from four helper functions—`prefixComments()`, `prefixCode()`, `generateMainCode()`, and `s... | def generateCode():
res = prefixComments()
res += prefixCode()
res += generateMainCode()
res += suffixCode()
return res |
def get_shape_and_size(range1, range2, part):
shape = random.choice(['box', 'sphere']) if part == 'body' else random.choice(['box', 'capsule', 'cylinder'])
if shape in ['box', 'capsule', 'cylinder']:
shape_xz = round(random.uniform(range1[0], range1[1]), 2)
shape_y = round(random.uniform(range2... | The code generates a creature's phenotype (physical description) from its genotype (genetic structure). It uses the genotype's graph to determine body/leg configurations, applying shape/size parameters and formatting segments into a string. The function returns a structured phenotype representation, combining body and ... | def build_creature_pheno(geno):
body_shape_size = get_shape_and_size([0.2, 0.25], [0.25, 0.3], 'body')
leg_shape_size = get_shape_and_size([0.06, 0.09], [0.1, 0.2], 'leg')
pheno = '''{}'''
legs = ''
for node in geno.graph.items():
if node[0] == 'body':
body = add_body(body_shape_... |
def init_creature_geno(leg_num, leg_seg_num):
creature = Graph()
creature.add_node('body')
for i in range(leg_num):
which_leg = 'leg' + str(i)
creature.add_node(which_leg)
creature.add_edge('body', which_leg)
for i in range(leg_seg_num):
creature.add_edge(which_le... | The code simulates the initial evolution of creatures by generating random genotypes and phenotypes, evaluating their movement fitness through Mujoco simulations, and selecting the highest-performing individual. It records fitness, genotype, and phenotype data for each parent creature, runs physical simulations to asse... | def run_initial_simulation(num_parents):
fitness_record = []
geno_record = []
pheno_record = []
for j in range(num_parents):
# actually simulating the model:
num_leg = random.randint(1, 8)
geno = init_creature_geno(num_leg, random.randint(0, 3))
pheno_traits = generate_p... |
def mutate_geno(parent_geno):
leg_seg = random.randint(0, 1)
del_add = random.randint(0, 1)
new_geno = parent_geno.make_copy()
leg_num = 'leg' + str(len(parent_geno.get_nodes()) - 1)
if leg_seg == 0:
if del_add == 0:
new_geno.delete_node(leg_num)
if del_add == 1:
... | This function performs evolutionary simulation by generating mutated offspring from a parent's genotype/phenotype, evaluating their fitness through movement simulation, selecting the fittest individual, and recursively evolving the population for a specified number of generations. It tracks genetic and phenotypic recor... | def begin_evolution(parent_geno, parent_pheno, winner, num_children, counter, evolve_num):
if counter > evolve_num:
return
counter += 1
fitness_record = [winner]
geno_record = [parent_geno]
pheno_record = [parent_pheno]
for j in range(num_children):
# actually simulating the mode... |
def _process_json_response(self, r, action_result):
# Try a json parse
try:
resp_json = r.json()
except Exception as e:
err = self._get_error_message_from_exception(e)
return RetVal(
action_result.set_status(
phantom.APP_ERR... | This function processes an HTTP response by determining its content type and routing it to the appropriate handler. It logs debug data (status code, headers, text) for troubleshooting, then delegates to specialized methods for JSON, file-based (HTML/image/PDF) responses, or empty responses. If none match, it returns an... | def _process_response(self, r, action_result):
# store the r_text in debug data, it will get dumped in the logs if the action fails
if hasattr(action_result, 'add_debug_data'):
action_result.add_debug_data({'r_status_code': r.status_code})
action_result.add_debug_data({'r_text': ... |
def _handle_py_ver_compat_for_input_str(self, input_str):
"""
This method returns the encoded|original string based on the Python version.
:param input_str: Input string to be processed
:return: input_str (Processed input string based on following logic 'input_str - Python 3; encoded inp... | The main task of the code is to make a REST API call to a specified endpoint with error handling. It constructs the URL, attaches authentication tokens, sends HTTP requests (defaulting to POST), and handles exceptions like invalid URLs or connection errors. The function returns processed responses or sets error statuse... | def _make_rest_call(self, endpoint, action_result, method="post", **kwargs):
# **kwargs can be any additional parameters that requests.request accepts
params = dict()
resp_json = None
try:
request_func = getattr(requests, method)
except AttributeError:
r... |
def _handle_py_ver_compat_for_input_str(self, input_str):
"""
This method returns the encoded|original string based on the Python version.
:param input_str: Input string to be processed
:return: input_str (Processed input string based on following logic 'input_str - Python 3; encoded inp... | This code generates a PDF from a given URL using specified options (header/footer, background printing, landscape mode) and saves it as a vault attachment. It handles REST API calls, temporary file storage, and returns success/failure status with metadata about the stored PDF file. | def _handle_get_pdf(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
s_url = self._handle_py_ver_compat_for_input_str(param['url'])
headerfooter = param.get('headerfoote... |
def _handle_py_ver_compat_for_input_str(self, input_str):
"""
This method returns the encoded|original string based on the Python version.
:param input_str: Input string to be processed
:return: input_str (Processed input string based on following logic 'input_str - Python 3; encoded inp... | This code handles downloading content from a URL via a REST call, processes the response, and stores it in a vault. It checks for Python version compatibility, manages attachment creation using Vault methods, and updates the action result with success/failure status and metadata like vault ID, file name, and path. | def _handle_get_content(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
s_url = self._handle_py_ver_compat_for_input_str(param['url'])
followRefresh = param.get('follow... |
def _handle_py_ver_compat_for_input_str(self, input_str):
"""
This method returns the encoded|original string based on the Python version.
:param input_str: Input string to be processed
:return: input_str (Processed input string based on following logic 'input_str - Python 3; encoded inp... | This code handles screenshot requests by validating parameters, constructing REST queries for PNG/JPEG formats, making API calls, and saving the resulting image as a vault attachment. It checks input values, manages different screenshot options, and stores the output securely, returning success/failure status according... | def _handle_get_screenshot(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
s_url = self._handle_py_ver_compat_for_input_str(param['url'])
ftype = self._handle_py_ver_co... |
def _handle_test_connectivity(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
self.save_progress("Connecting to endpoint")
query = '{"url":"https://google.com"}'
# make rest call
ret_val, _ = self._make_rest_call('/stats', action_result, data=json... | The code defines a method `handle_action` that determines and executes the appropriate action based on the action identifier. It retrieves the action ID, logs it, and routes the request to specific handler methods like `_handle_test_connectivity`, `_handle_get_pdf`, etc., returning the result. The main task is to dispa... | def handle_action(self, param):
ret_val = phantom.APP_SUCCESS
# Get the action that we are supposed to execute for this App Run
action_id = self.get_action_identifier()
self.debug_print("action_id: {}".format(self.get_action_identifier()))
if action_id == 'test_connectivity':
... |
def load_file(self, file):
with open(file, "r") as stream:
try:
return yaml.load(stream, Loader=Loader)
except yaml.YAMLError as exc:
print(exc)
except UnicodeDecodeError:
return
def key_from_gymlstr(self, path):
if '.' ... | The code loads challenge data from a YAML file, organizes it into a structured dictionary using keys derived from '__RowId', translates specific fields like 'Name', 'RequestActor', and 'RequestLocation' for human readability, and processes each step's 'Message' for non-'Ready' steps. It returns the translated and organ... | def load_challenge(self):
raw = self.load_file(self._romfs+"/RSDB/Challenge.Product.100.rstbl.yml")
#This bloc organise challanges with keys
for challenge in raw:
key = self.key_from_gymlstr(challenge['__RowId'])
self.Challenge[key] = challenge
#Here we make i... |
def load_file(self, file):
with open(file, "r") as stream:
try:
return yaml.load(stream, Loader=Loader)
except yaml.YAMLError as exc:
print(exc)
except UnicodeDecodeError:
return
def key_from_gymlstr(self, path):
if '.' ... | This method loads YAML data containing enhancement material information, processes each entry by converting its unique ID, creates EnhancementMaterial objects, and translates actor names to item names within those objects. | def load_EnhancementMaterial(self):
raw = self.load_file(self._romfs+"/RSDB/EnhancementMaterialInfo.Product.100.rstbl.yml")
for material in raw:
material['__RowId'] = self.key_from_gymlstr(material['__RowId'])
self.EnhancementMaterial[material['__RowId']] = EnhancementMaterial(ma... |
def load_EnhancementMaterial(self):
raw = self.load_file(self._romfs+"/RSDB/EnhancementMaterialInfo.Product.100.rstbl.yml")
for material in raw:
material['__RowId'] = self.key_from_gymlstr(material['__RowId'])
self.EnhancementMaterial[material['__RowId']] = EnhancementMaterial(ma... | The code loads pouch data from a YAML file, initializes Pouch objects with translated names/captions, links enhancement materials, and processes armor-related attributes. It populates a dictionary (`self.Pouch`) with these objects, handling translations and conditional fields like armor upgrades and effects. | def load_pouch(self):
self.load_EnhancementMaterial()
raw = self.load_file(self._romfs+"/RSDB/PouchActorInfo.Product.100.rstbl.yml")
for pouch in raw:
self.Pouch[pouch['__RowId']] = Pouch(pouch)
self.Pouch[pouch['__RowId']].Name = self.translate('Work/Actor/'+pouch['__Row... |
def get_data():
"""Retrieves data for the different models.
Parameters:
Returns:
"""
cursor = get_connection()
print('Fetching data...')
config = configparser.ConfigParser()
config.read('config/settings.ini')
data_record_limit = config.getint('general', 'data_record_limit', fallb... | This function evaluates collaborative filtering models (KNNBasic or NMF) on a dataset, optionally validating CBF results. It loads data, selects the specified model, executes evaluation, and returns success status. | def base_collaborative_filtering(mode, cbf_eval = False):
"""Entry function for collaborative filtering.
Parameters:
mode (str): specifies which model should be evaluated (can be KNNBasic or NMF)
cbf_eval (bool): specifies whether a CBF result should be checked with the specified model
Returns:
... |
def DMSG(msg):
if DEBUG:
print(msg)
def DMSG_HEX(char):
if DEBUG:
print('%x' % char)
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + ... | The function `writeGPIO` sets the state of the PN532's P3 GPIO pins using an 8-bit `pinstate` value. It ensures reserved pins (P32/P34) are forced high (1) to prevent system instability. The function constructs a command buffer with the specified GPIO configuration, sends it, and returns success (1) or error (0) status... | def writeGPIO( pinstate: int):
"""
Writes an 8-bit value that sets the state of the PN532's GPIO (P3)
:warning: This function is provided exclusively for board testing and
is dangerous since it will throw an error if any pin other
than the ones marked "Can be used as GPIO" are m... |
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out.append(length)
data_out.append((~length & 0... | The function `readGPIO()` reads the state of the PN532's P3 GPIO pins (P30–P35) by sending a `READGPIO` command (0x0C) and parsing the response. It returns an 8-bit value where each bit represents the state of a specific P3 pin. The response also includes unused P7 and interface mode pins, but only the P3 data (respons... | def readGPIO():
"""
Reads the state of the PN532's GPIO pins (P3)
:returns: An 8-bit value containing the pin state where:
pinState[0] = P30
pinState[1] = P31
pinState[2] = P32
pinState[3] = P33
pinState[4] = P34
pi... |
def DMSG(msg):
if DEBUG:
print(msg)
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out... | The function configures the Secure Access Module (SAM) by sending a specific command with parameters (normal mode, 1-second timeout, IRQ pin usage) to a PN532 device. It writes the command, checks for write errors, reads the response, and returns True if the operation succeeds (status ≥ 0), otherwise False. | def SAMConfig():
"""
Configures the SAM (Secure Access Module)
:returns: True if success, False if error
"""
header = bytearray([PN532_COMMAND_SAMCONFIGURATION,
0x01, # normal mode
0x14, # timeout 50ms * 20 = 1 second
0x01])... |
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out.append(length)
data_out.append((~length & 0... | This function detects an ISO14443A passive target card, reads its UID, and optionally marks it as inlisted. It sends a command to the PN532 reader, processes the response to extract the card's unique identifier, and returns a success status along with the UID bytes. If 'inlist' is True, it stores the tag number in a gl... | def readPassiveTargetID( cardbaudrate: int, timeout: int = 1000, inlist: bool = False): # -> (bool, bytearray):
global inListedTag
"""
Waits for an ISO14443A target to enter the field
:param cardBaudRate: Baud rate of the card
:param timeout: The number of tries before timing out
:par... |
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out.append(length)
data_out.append((~length & 0... | This function authenticates a specific memory block on a MIFARE card using the INDATAEXCHANGE command. It prepares an authentication request with the provided key, block number, and UID, sends it to the card, and checks the response for success. If the response contains valid authentication bytes (0xD5 0x41 0x00), it r... | def mifareclassic_AuthenticateBlock( uid: bytearray, blockNumber: int, keyNumber: int, keyData: bytearray):
global _key
global _uid
"""
Tries to authenticate a block of memory on a MIFARE card using the
INDATAEXCHANGE command. See section 7.3.8 of the PN532 User Manual
for more informat... |
def DMSG(msg):
if DEBUG:
print(msg)
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out... | The function reads a 16-byte data block from a Mifare Classic card at the specified block address. It sends a read command, checks the response for errors, and returns a tuple indicating success/failure and the retrieved data bytes (or an empty bytearray on failure). The block number must be within valid ranges for 1KB... | def mifareclassic_ReadDataBlock ( blockNumber: int): # -> (bool, bytearray):
"""
Tries to read an entire 16-bytes data block at the specified block
address.
:param blockNumber: The block number to authenticate. (0..63 for
1KB cards, and 0..255 for 4KB cards).
:param d... |
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out.append(length)
data_out.append((~length & 0... | This function reads a 4-byte page from a Mifare Ultralight card using the PN532 module. It sends a read command with the specified page number, checks the response for errors, and returns the extracted data bytes (if successful) or False with an empty bytearray on failure. | def mifareultralight_ReadPage( page: int): # -> (bool, bytearray):
"""
Tries to read an entire 4-bytes page at the specified address.
:param page: The page number (0..63 in most cases)
:returns: (result, data)
result: bool True if successful, False if error
data:... |
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out.append(length)
data_out.append((~length & 0... | This function exchanges an APDU command with a connected NFC tag. It sends a predefined header and data payload, checks for transmission errors, validates the response status, and returns a success flag along with the processed response data if no errors occur. | def inDataExchange( send: bytearray): # -> (bool, bytearray):
global inListedTag
"""
Exchanges an APDU with the currently inlisted peer
:param send: Pointer to data to send
:param response: Pointer to response data
:param responseLength: Pointer to the response dat... |
def DMSG(msg):
if DEBUG:
print(msg)
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out... | This function communicates with a passive RFID tag via PN532 (reader/initiator) to list the tag (peer/card). It sends a command, checks the response, and stores the tag's identifier in `inListedTag` if successful. Returns `True` on success, `False` otherwise. | def inListPassiveTarget():
global inListedTag
"""
'InLists' a passive target. PN532 acting as reader/initiator,
peer acting as card/responder.
:returns: True if command succeeded, False otherwise
"""
header = bytearray([
PN532_COMMAND_INLISTPASSIVETARGET,
1,
... |
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out.append(length)
data_out.append((~length & 0... | This function sends a command to retrieve data from a PN532 device, checks response status, and returns the data length and content if successful, or error codes and empty data on failure. | def tgGetData(): # -> (int, bytearray):
header = bytearray([PN532_COMMAND_TGGETDATA])
if (writeCommand(header)):
return -1, bytearray()
status, response = readResponse()
if (0 >= status):
return status, bytearray()
length = status - 1
if (response[0] != 0):
DMSG... |
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out.append(length)
data_out.append((~length & 0... | The function polls for FeliCa cards using a PN532 reader, sending a command with specified system code and request type. It checks for card presence, validates response data length, extracts the card's IDm (8 bytes), PMm (8 bytes), and optional system code (2 bytes), then returns a status and these values. If no card i... | def felica_Polling( systemCode: int, requestCode: int, timeout: int = 1000): # -> (int, bytearray, bytearray, int):
global inListedTag
"""
Poll FeliCa card. PN532 acting as reader/initiator,
peer acting as card/responder.
:param timeout:
:param systemCode: Designatio... |
def DMSG(msg):
if DEBUG:
print(msg)
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out... | The function sends a FeliCa command to an inlisted peer, validates the command length, constructs a header, and transmits the command. It waits for a response, checks for errors in the response status and length, and returns the processed data if successful. Errors trigger negative status codes with descriptive message... | def felica_SendCommand( command: bytearray): # -> (int, bytearray):
"""
Sends FeliCa command to the currently inlisted peer
:param command: FeliCa command packet. (e.g. 00 FF FF 00 00 for Polling command)
:returns: (status, response)
status 1: Success, < 0: er... |
def DMSG(msg):
if DEBUG:
print(msg)
def writeCommand( header: bytearray, body: bytearray = bytearray()):
global _command
_command = header[0]
data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2]
length = len(header) + len(body) + 1 # length of data field: TFI + DATA
data_out... | This function releases all FeliCa targets by sending an INRELEASE command via PN532. It checks for ACK confirmation, waits for the card's response, validates the status code, and returns 1 on success or negative codes for errors like no ACK, missing response, or invalid status. | def felica_Release():
"""
Release FeliCa card
:returns: 1: Success, < 0: error
"""
# InRelease
header = bytearray([
PN532_COMMAND_INRELEASE,
0x00, # All target
])
DMSG("Release all FeliCa target\n")
if (writeCommand(header)):
DMSG("No ACK\n")
ret... |
def set_col_addr( col_start, col_end ):
setpin(led, 0)
D0 = 0x21
D1 = col_start & 0x7f
D2 = col_end & 0x7f
myData = [D0, D1, D2]
spi.writebytes( myData )
def set_page_addr( page_start, page_end ):
setpin(led, 0)
D0 = 0x22
D1 = page_start & 0x3
D2 = page_end & 0x3
myData = [D0... | This function renders ASCII characters on an OLED display by iterating through font data, setting display addresses, and sending pixel data via SPI. It loops through 32 characters per page, splits them into two display pages, updates the screen with each character, and clears the display after a 2-second delay. | def oledascii():
for k in range(3):
start_col = 0
for j in range(32): # 16 characters per two pages
mychar = [None] * 12
tmp = j + (k << 5)
tmp1 = (tmp << 3) + (tmp << 2) # tmp x 12
for i in range(12):
mychar[i] = font7x14... |
def initpin(pinnum, mode):
'''
pinnum: pin number, eg. 172, 175 etc.
mode: pin mode, valid values: in or out
'''
if not check_already_exported(pinnum):
with open('/sys/class/gpio/export', 'w') as f:
f.write(str(pinnum))
with open('/sys/class/gpio/gpio' + str(pinnum) + '/d... | This code tests an SSD1306 OLED display by initializing hardware, configuring SPI communication, and rendering patterns, ASCII art, and text messages. It sets display modes, sends pixel data via SPI, clears the screen, displays "This is a test!" and "It works!", then closes resources. The task verifies display function... | def ssd1306_test():
initpin(led, 'out')
setpin(led, 1)
spi.open(32766, 0)
spi.max_speed_hz = 5000000
ssd1306_init()
# set_page_mode()
set_horizontal_mode()
set_col_addr( 0, 127 )
set_page_addr( 0, 3 )
setpin(led, 1)
for j in range(4):
i = 0
while i < 128:
... |
def checkUniqueValueGroup(self, cell_group: list[Cell]) -> bool:
counts = [0] * 10
for cell in cell_group:
for option in cell.options:
counts[option] += 1
if 1 in counts:
unique_val = counts.index(1)
for cell in cell_group:
... | The code checks if any row, column, or 3x3 box in a Sudoku grid contains duplicate values. It iterates through each group (0–8), uses helper methods to retrieve cells, and verifies uniqueness. If duplicates are found in any group, it returns True; otherwise, it returns False after checking all groups. | def checkUniqueValue(self) -> bool:
for num in range(9):
if self.checkUniqueValueGroup(self.getCellsFromRow(num)):
return True
if self.checkUniqueValueGroup(self.getCellsFromCol(num)):
return True
if self.checkUniqueValueGroup(self.getCellsFrom... |
def patronenvinder(periode):
patronen=[]
for i in range(0,len(permutaties)):
jongleerbaar=[]
for j in range(0,periode):
jongleerbaar.append((permutaties[i][j]-beats[j])%periode)
patronen.append(jongleerbaar)
return cykelvuller(patronen)
def lijstgenerator(sequentie):... | The function generates new sequences by combining elements from existing patterns with scaled values from another list, then processes them with a filler function. It iterates through patterns, creates modified versions by adding scaled values, and aggregates results before returning a processed version of the generate... | def sequencegenerator():
jongleer_patronen=[]
for i in range(0,len(patronenvinder(p))):
huidige=patronenvinder(p)[i]
goeie_sommen=lijstgenerator(huidige)
if isinstance(goeie_sommen, list):
for j in range(0,len(goeie_sommen)):
patroon=[]
... |
def login(s):
# get initial session and nonce
resp = s.get(f"https://{ENDPOINT}")
nonce=re.findall(b"'csrfNonce': \"(.*)\"", resp.content)[0]
login = supersecret.getSecret(f"{ENDPOINT}", "login")
password = supersecret.getSecret(f"{ENDPOINT}", "password")
resp = s.post(f"https://{ENDPOINT}/logi... | This code defines a command-line interface (CLI) tool for interacting with a coding/learning platform. It handles commands like login, listing dojos/categories, retrieving challenges, starting problems, and downloading challenge materials. The tool uses argparse for argument parsing, manages session cookies for authent... | def main():
parser = argparse.ArgumentParser()
subparser = parser.add_subparsers(dest="command")
subparser.add_parser("login")
subparser.add_parser("dojos")
categories_parser = subparser.add_parser("categories")
categories_parser.add_argument("--dojo", required=True)
challenges_parser = su... |
def generate_real_samples(dataset, n_samples):
"""
Takes as input cleaned dataset and a number of samples to be generated
Returns a random sample of n_samples images and their corresponding label (=1 because these are real images)
"""
# Choose random instances (i.e., randomly select n_samples indexe... | This function trains a GAN by alternatingly training the discriminator on real/fake samples and the generator via the GAN model. It adjusts sample counts based on discriminator accuracy to balance training, saves models and generated images periodically, and tracks loss/accuracy metrics per epoch. The generator creates... | def train(generator_model, discriminator_model, gan_model, dataset, path_discriminator_model, path_generator_model, path_gan_model, path_discriminator_info, path_images_generated_per_epoch, latent_dim = 100, n_epochs=160, n_batch_per_epoch=15):
number_of_samples_per_batch = int((dataset.shape[0] / n_batch_per_epoch... |
def search_workspace(self):
self.console_writer.write("Searching for existing workspace.")
# Find all blocks that contain the database name
db_results = self.client_py.search_blocks(self.params["db_name"], limit=50)
# and table name
tb_results = self.client_py.search_blocks(self... | The code initializes a Notion workspace by setting up two clients (SDK and py), retrieving configuration parameters from a GUI, searching for existing databases/workspaces, and creating them if absent. It manages database entries, using the SDK for creation and py for block retrieval, ensuring data synchronization and ... | def __init__(self, gui, attr_list) -> None:
self.date, _ = get_date_and_time()
attr_dict = {}
for attr in attr_list:
attr_dict.update({attr: getattr(gui, attr)})
self.params = attr_dict["params"]
self.console_writer = attr_dict["console_writer"]
# We use bo... |
def speak(audio):
print(AIname + ': ' + audio)
engine.say(audio)
engine.runAndWait()
def wait():
m.getch()
def now():
Time = datetime.datetime.now().strftime('%I:%M:%p')
speak("The current time is")
speak(Time)
def date():
today = datetime.datetime.now().strftime('The date of today is %... | The code processes voice commands to execute tasks like opening websites (Google Maps, YouTube), searching the web, launching apps (Notepad), playing music, and providing time/date info. It uses speech recognition to detect keywords, triggers corresponding actions (e.g., `os.startfile`, `webbrowser`), and responds with... | def takecommand():
while True:
data = stream.read(4000, exception_on_overflow=False)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
result = rec.Result()
result = json.loads(result)
query = result['text']
print("Boss: " + que... |
def train_test_validation_split(data, test_size=.20, validation_size=0.20):
x, y = separate_data(data)
split = int(test_size*x.shape[0])
x_test = x[:split]
x_val = x[split:(split*2)]
x_train = x[(split*2):]
y_test = y[:split]
y_val = y[split:(split*2)]
y_train = y[(split*2):]
print... | The code performs polynomial regression using gradient descent with regularization. It trains a model by iteratively adjusting parameters (theta) to minimize mean squared error (MSE) on the training set, while tracking training, validation, and test errors. Polynomial features are added to input data, and regularizatio... | def polynomial_regression(data, degree, num_epochs=100000, alpha=1e-4, lamb=0):
x_train, y_train, x_test, y_test, x_val, y_val = train_test_validation_split(
data)
train_errors = []
val_errors = []
# Add the appropriate amount of columns to each of the sets of data.
x_train = add_polycols(... |
def train_test_split(data, train_size=.80):
x, y = separate_data(data)
per = int(train_size*x.shape[0])
x_train = x[:per]
x_test = x[per:]
y_train = y[:per]
y_test = y[per:]
return x_train, y_train, x_test, y_test
def mse(y_pred, y_true):
n = len(y_pred)
return 0.5*(1/n)*np.sum((y_p... | The code trains a linear regression model using gradient descent on training data, tracks training and test mean squared errors (MSE) over epochs, and returns the optimized parameters (theta) along with error histories for analysis. | def linear_regression(data, num_epochs=30000, alpha=0.00005):
x_train, y_train, x_test, y_test = train_test_split(data)
train_errors = []
test_errors = []
# Defining theta
theta = np.zeros((x_train.shape[1], 1))
for i in range(num_epochs):
train_error = mse(np.dot(x_train, theta), y_... |
def git_clone_source(PUSH_URI, TEMP_DIR):
local('git clone "{}" "{}"'.format(PUSH_URI, TEMP_DIR))
def checkout_branch(branch_name, cwd):
with( shell_env( GIT_COMMITTER_EMAIL='travis@travis', GIT_COMMITTER_NAME='Travis CI' ) ):
print('checkout branch: {}'.format(branch_name))
run_command('git checkout {}'.fo... | The main task of the code is to process a Dependabot pull request by cloning the repository, merging the specified PR branch into the 'develop' branch, and pushing the updated changes to the remote repository. It includes steps to fetch, checkout, merge, and push commits, ensuring the PR's updates are integrated into t... | def process_dependabot_PR(PUSH_URI, pr_branch, cwd, no_push_uri = False):
print('hello process dependabot PR')
'''
Step 1: From your project repository, bring in the changes and test.
git fetch origin
git checkout -b "dependabot/npm_and_yarn/bulma-toast-tryout/lodash-4.17.19" "origin/dependabot/npm_and_yarn/... |
def check_branch_exist(branch_name, cwd):
print_message('check branch exist, {}'.format(branch_name))
with( shell_env( GIT_COMMITTER_EMAIL='travis@travis', GIT_COMMITTER_NAME='Travis CI' ) ):
print('check branch exist: {}'.format(branch_name))
result = [temp.replace('* ','').strip() for temp in run_command(... | (The function checks if a Git branch exists in the specified directory. If it exists, it checks out the branch; if not, it creates the branch and checks it out, ensuring the branch is active in the current working directory.) | def create_branch_if_not_exist(branch_name, cwd):
'checkout branch if exist, create and checkout if not exist'
if check_branch_exist(branch_name, cwd):
checkout_branch(branch_name, cwd)
else:
create_new_branch(branch_name, cwd) |
def check_branch_exist(branch_name, cwd):
print_message('check branch exist, {}'.format(branch_name))
with( shell_env( GIT_COMMITTER_EMAIL='travis@travis', GIT_COMMITTER_NAME='Travis CI' ) ):
print('check branch exist: {}'.format(branch_name))
result = [temp.replace('* ','').strip() for temp in run_command(... | This function checks if a Git branch (local or remote) exists. If it does, it checks out the branch; if not, it creates and checks out the new branch. The task ensures the specified branch is available locally, creating it if necessary. | def create_branch_if_not_exist_remote(branch_name, cwd):
'checkout branch if exist, create and checkout if not exist'
if check_branch_exist(branch_name, cwd) or check_remote_branch_exist(branch_name, cwd):
checkout_branch(branch_name, cwd)
else:
create_new_branch(branch_name, cwd) |
def run_command(command_body, cwd=OS_CWD, ignore_error=True, except_in=MyException.command_error):
if (DRY_RUN):
return dummy_run_result()
else:
with settings(warn_only=True):
command_to_run = 'cd {} && {}'.format(cwd, command_body)
command_result = local(command_to_run, capture=True)
pri... | The main task of the code is to clone a specified branch from a Git repository, merge it into the 'develop' branch, and optionally push the merged changes to the remote repository. The function handles cloning, merging, and conditional pushing based on the 'no_push_uri' flag. | def process_pre_merge_branch(PUSH_URI, pre_merge_branch_in, cwd, no_push_uri = False):
branch_name = get_branch_name(pre_merge_branch_in)
run_command('git clone -b {} {} .'.format(pre_merge_branch_in, PUSH_URI), cwd)
merge_to_develop_branch(pre_merge_branch_in, cwd)
if no_push_uri:
print('no pushing commi... |
def run_command(command_body, cwd=OS_CWD, ignore_error=True, except_in=MyException.command_error):
if (DRY_RUN):
return dummy_run_result()
else:
with settings(warn_only=True):
command_to_run = 'cd {} && {}'.format(cwd, command_body)
command_result = local(command_to_run, capture=True)
pri... | The function clones a specified Git branch, merges it into the master branch, and optionally pushes the merged changes to a remote repository, depending on the 'no_push_uri' flag. | def process_pre_merge_master_branch(PUSH_URI, pre_merge_branch_in, cwd, no_push_uri = False):
'checkout pre-merge-master branch'
'on master branch, merge pre-merge-master and re-test'
run_command('git clone -b {} {} .'.format(pre_merge_branch_in, PUSH_URI), cwd)
merge_to_master_branch(pre_merge_branch_in, cwd... |
def run_command(command_body, cwd=OS_CWD, ignore_error=True, except_in=MyException.command_error):
if (DRY_RUN):
return dummy_run_result()
else:
with settings(warn_only=True):
command_to_run = 'cd {} && {}'.format(cwd, command_body)
command_result = local(command_to_run, capture=True)
pri... | The function `process_test_branch` clones a test branch from a given URI, merges it into a feature branch, and conditionally pushes the merged commit to the URI if `no_push_uri` is false, handling errors during cloning and raising exceptions for critical failures. | def process_test_branch(PUSH_URI, test_branch_name, cwd, no_push_uri = False):
branch_name = get_branch_name(test_branch_name)
feature_branch_name = 'feature/'+branch_name
# CAUTION: using cwd inside run_command
with settings(warn_only=True):
run_result = run_command('git clone -b {} {} .'.format(test_br... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.