dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def handle_lldp(self, datapath,pkt_lldp):
#print(pkt_lldp.tlvs[1].port_id[0]-48)
#print(int(bytes.decode(pkt_lldp.tlvs[0].chassis_id,encoding='utf-8')))
self.datapathlist[int(bytes.decode(pkt_lldp.tlvs[0].chassis_id,encoding='utf-8'))-1].addport(int(bytes.decode(pkt_lldp.tlvs[1].port_id,encodin... | This code processes incoming packets on an SDN switch by inspecting their protocol type. It identifies Ethernet frames, checks for LLDP packets (for network discovery), ARP requests (for address resolution), and IPv4 packets (for routing). Depending on the packet type, it delegates handling to specialized methods like ... | def packet_in_handler(self, ev):
msg = ev.msg
datapath = msg.datapath
port = msg.match['in_port']
pkt = packet.Packet(data=msg.data)
pkt_ethernet = pkt.get_protocol(ethernet.ethernet)
if not pkt_ethernet:
return
pkt_lldp = pkt.get_protocol(... |
def _check_event(self):
#Watch out for any key or mouse press.
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_event(event)
def _update_raindrops(self):
"""Upd... | The code defines a game loop that continuously checks for events, updates raindrop positions, and redraws the screen at 60 FPS to maintain smooth gameplay. The main task is to sustain the game's real-time interaction by processing inputs, updating game elements, and rendering visuals within a fixed frame rate. | def run_game(self):
"""Start the main loop for the game"""
while True:
self._check_event()
self._update_raindrops()
self._screen_update()
self.clock.tick(60) |
def __search_celeb(self, celeb_name: str):
search = self.driver.find_element(By.NAME, "q")
search.send_keys(celeb_name)
search.send_keys(Keys.RETURN)
def __click_element(self, css_selector: str):
element = self.wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, css_sele... | The main task of the code is to scrape celebrity information from a webpage, including their name, professions, and works. It searches for the celebrity, navigates to their profile, extracts details like name and professions, expands the "works" section, iterates through each work, opens it to scrape specific data, and... | def get_celeb_info(self, celeb_name: str):
self.__search_celeb(celeb_name)
## get to celebrity page
self.__click_element("li.find-name-result:nth-child(1) > div:nth-child(2) > div:nth-child(1) > a:nth-child(1)")
name = self.__get_element(".sc-856aec89-0").text
## get all the pr... |
def forward_pass(self, inp):
# clear previous values
s_val = np.array([])
self.u_prime = np.array([])
# forward pass for one row of features
for layer in self.network.layers[1:]:
# empty output from previous layer
outputs = np.array([])
for per... | This code trains a neural network over multiple epochs, performing forward and backward passes on training data, calculating RMSE for training and validation sets, and tracking the best network based on validation error. It includes momentum and self-attention features, adjusts learning rates, and implements stop detec... | def train(self, epoch=1000, momentum=False, sa=False, max_lr=0.9, min_lr=0.01, stop_detection=True):
self.momentum = momentum
self.sa = sa
self.epoch = self.epoch + epoch
self.max_lr = max_lr
self.min_lr = min_lr
for i in range(epoch):
self.current_epoch = (se... |
def drawLoading():
text = info.font.render('Loading...', True, (0, 0, 0))
rect = text.get_rect()
rect.center = (info.win_width-info.slider_width//2, info.win_height-20)
window.blit(text, rect)
pygame.display.update()
def initPath():
world.clearPath()
currentId = world.graph.getRandomNodes(1)... | The main task of the code is to generate a continent by repeatedly attempting to create it through a stepping process. It initializes paths, checks outcomes (success or failure), and terminates after a timeout limit (1000 iterations) to prevent infinite loops. The function uses a loading indicator, handles graph data, ... | def generateContinent():
drawLoading()
if len(world.graph.getIds()) == 0:
return
timeout = 0
createdContinent = False
while not createdContinent:
initPath()
isStepping = True
while isStepping:
stepOutcome = step()
if stepOutcome == 1:
... |
def drawLoading():
text = info.font.render('Loading...', True, (0, 0, 0))
rect = text.get_rect()
rect.center = (info.win_width-info.slider_width//2, info.win_height-20)
window.blit(text, rect)
pygame.display.update()
def generateContinent():
drawLoading()
if len(world.graph.getIds()) == 0:
... | The main task of the code is to generate multiple continents on a map. It initializes the map with a water background, creates continents based on a slider value, and updates the display. The function draws a loading indicator, fills the map with water, iterates to generate continents, redraws the map, and updates the ... | def generateMultipleContinents():
drawLoading()
pygame.draw.rect(window, info.getWater(), pygame.Rect(
0, 0, map_width, info.win_height))
for i in range(info.sliders['continents'].getValue()):
generateContinent()
redraw()
pygame.display.update() |
def drawLoading():
text = info.font.render('Loading...', True, (0, 0, 0))
rect = text.get_rect()
rect.center = (info.win_width-info.slider_width//2, info.win_height-20)
window.blit(text, rect)
pygame.display.update()
def clearContinents():
drawLoading()
world.clearContinents()
redraw()
d... | The main task of the code is to automatically generate and refine the visual representation of continents through a series of steps: drawing a loading indicator, clearing existing data, updating colors, generating nodes and multiple continents, and iteratively refining their shapes with increasing complexity. The proce... | def autoGenerate():
drawLoading()
clearContinents()
updateColor()
generateNodes()
generateMultipleContinents()
refine('water')
drawContinents()
refine(shape='dot', attemptsPerIteration=500)
for i in range(25):
refine(attemptsPerIteration=1500) |
def calc_loss_batch(input_batch, target_batch, model, device):
input_batch, target_batch = input_batch.to(device), target_batch.to(device)
logits = model(input_batch)
loss = torch.nn.functional.cross_entropy(
logits.flatten(0, 1), target_batch.flatten()
)
ret... | The function trains a machine learning model using a specified optimizer and device over a given number of epochs. It processes training batches, computes losses, performs backpropagation, and updates model parameters. Periodically, it evaluates model performance on training and validation data, logs losses, and prints... | def train_model_simple(model, train_loader, val_loader, optimizer, device, num_epochs,
eval_freq, eval_iter, start_context):
train_losses, val_losses, track_tokens_seen = [], [], []
tokens_seen, global_step = 0, -1
for epoch in range(num_epochs):
model.train()
for in... |
def sendATcmd(self, command, desired_response = "OK\r\n", timeout_s = None):
if timeout_s is None:
timeout_s = self.timeout
if (ser.isOpen() == False):
ser.open()
self.compose = str(command) + "\r"
# debug_print(self.compose)
ser.wri... | This function sends UDP data via an AT command. It constructs a `AT+QISEND` command with the connection ID and data length, checks for a prompt, encodes and transmits the data, then waits for a "SEND OK" confirmation. If unsuccessful, it logs an error. | def sendUdpData(self, data):
self.compose = "AT+QISEND=" + self.connectID + "," + str(len(data))
if self.sendATcmd(self.compose,">"):
ser.write(data.encode())
self.waitUnsolicited("SEND OK", 5)
else:
self.debug_print("ERROR message not send \"" + str(data.enco... |
def sendATcmd(self, command, desired_response = "OK\r\n", timeout_s = None):
if timeout_s is None:
timeout_s = self.timeout
if (ser.isOpen() == False):
ser.open()
self.compose = str(command) + "\r"
# debug_print(self.compose)
ser.wri... | The main task of the code is to initialize a network connection for a module by sending AT commands to configure modem settings, set TCP/IP context with a given APN, and check for successful network registration within a specified time interval. It returns True if registration is confirmed, otherwise False after the ti... | def initNetwork(self, contextID, APN="", check_time_s = 60):
self.sendATcmd("AT+CBC")
self.sendATcmd("AT+CMEE=2")
self.sendATcmd("AT+CPIN?", "OK\r\n", 5)
self.sendATcmd("AT+CFUN=1")
self.sendATcmd("AT+CEREG=0")
self.configTcpIpContext(contextID, APN)
interval = 1... |
def run_spotify():
'''
Access the Spotify API with a client ID and client secret
from the client_details.json file
'''
creds = {'client_id': os.environ.get("CLIENT_ID"),
'client_secret': os.environ.get("CLIENT_SECRET")}
spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials... | The main task of the code is to create a Spotify recommendation system that interacts with users to gather preferences (artists, genres, favorite songs, and mood) and generate personalized music recommendations. It includes error handling for artist selection, allows repeated gameplay, and provides a thank-you message ... | def main():
play_again = 'y'
while play_again == 'y':
spotify = run_spotify()
try:
music_artists = artist_selection(spotify)
except:
spotify = run_spotify()
music_artists = artist_selection(spotify)
user_genres = genre_selection(spotify)
... |
def estimate_eigenmoments(X, Y, num_moments, comb_M_2ps=None):
"""
Compute unbiased moment estimates.
Parameters
----------
X : ndarray
(samples x neurons) matrix of responses.
Y : ndarray
(samples x neurons) matrix of responses.
num_moments : int
Maximum moment to c... | The function estimates the similarity between two noisy signal matrices (X, Y) by calculating eigenmoments, bootstrapping covariance, and applying regularization. It returns the similarity metric, its variance, bias, and a naive estimate using nuclear norm. The method adjusts for bias and variance via parameters like a... | def full_similarity_metric_estimator(X, Y, num_moments=10, alpha=1,
num_bootstraps=500,
remove_constant=True,
bias_frac=1, comb_M_2ps=None):
"""
Complete function to estimate sim... |
def estimate_eigenmoments(X, Y, num_moments, comb_M_2ps=None):
"""
Compute unbiased moment estimates.
Parameters
----------
X : ndarray
(samples x neurons) matrix of responses.
Y : ndarray
(samples x neurons) matrix of responses.
num_moments : int
Maximum moment to c... | This function estimates the similarity metric between two noisy signal matrices X and Y using eigenmoments and bootstrapping. It computes the estimator, its variance, and bias, while also providing a naive nuclear norm-based estimate. The method involves normalizing inputs, calculating covariance, and leveraging polyno... | def full_signal_similarity_metric_estimator(X, Y, num_moments=10, alpha=1,
num_bootstraps=500, remove_constant=True,
bias_frac=1):
"""
Complete function to estimate similarity metric between two noisy vector... |
def handle_telegram(self):
checks, status = self.check_required_data()
if status == 400:
return checks, status
bot_names = self.data.get('tel_bot_names')
if not bot_names:
return "Bot names field is required.", 400
tel_response, tel_status = send_telegr... | The main task of the code is to process services like Telegram, Email, and Slack by calling respective handlers. It checks each service's status: if any handler returns a non-200 status, it immediately returns the error response and status. If all services succeed, it returns a predefined success value (`self.return_va... | def parse_services(self):
if 'telegram' in self.services:
tel_response, tel_status = self.handle_telegram()
if tel_status != 200:
return tel_response, tel_status
if 'email' in self.services:
email_response, email_status = self.handle_email()
... |
def get_mac(self):
"""
Helper method get_mac
Used when creating the payload for setting the ip address of the oneview dcs appliance.
returns mac address of the oneview dcs appliance.
Parameters:
----------
none
"""
url = "/rest/appliance/network-... | This function changes the IP address of a OneView DCS appliance by configuring network interfaces with provided IPv4 addresses, gateway, subnet, and virtual IP. It constructs a payload, sends a POST request via SSH, checks task status, logs the new virtual IP, and writes it to a file for persistence. | def change_ovDcs_ip(self, app1Ipv4Addr, app2Ipv4Addr, virtIpv4Addr,
ipv4Gateway, ipv4Subnet, ):
"""
Changes the Ip address of the oneview dcs appliance.
Parameters:
----------
app1Ipv4Addr: str
Node1 IPv4 address in a two-node cluster
app2Ipv4Addr: ... |
def get_secure_headers(self):
"""
Helper method to appliance_request().
Gives header information required by the appliance with authentication information.
Return
------
_secure_header: dict. Dictionary containing X-API-Verions, Content-Type, and Auth. The Auth parameter... | The main task of the code is to retrieve tasks from a system using optional filters, then iterate through each task to check its status by calling get_task() on their URIs, primarily used during hardware discovery processes. | def search_task(self, param):
"""Gets all the tasks based upon filters provided. Note: filters are optional.
iterate through all the task collected and calls get_task() to check the status.
Used while running hardware discovery
Parameters:
----------
param: str
... |
def get_lines(self, st_no, end_no):
"""
To get list of lines from starting
line number to ending line number.
"""
lines = list()
self.load_md()
for no in range(st_no, end_no):
lines.append(dict({'line_no': no, 'line': self.all_lines[no]}))
retu... | The function validates and marks data points in a document's specified range. It retrieves lines, checks existing endpoints against web scraping data using a minus sign for invalid entries, and validates new endpoints with a checkmark. Valid new points are collected for further processing, ensuring data consistency and... | def add_checks(self, st_no, end_no, webscraping_data):
"""
To add marks in required places.
"""
lines = self.get_lines(st_no, end_no)
old_end_points = self.get_old_end_points(st_no, end_no, webscraping_data)
for old_end_point in old_end_points:
self.validate_... |
def accept_eula_once(self, service_access="yes"):
"""
On initial communication with the appliance, the end user service agreement (EULA) must be accepted.
This only needs to occur once. Additional calls will not change the status of the EULA nor the status of the service access.
If a ch... | The main task of the code is to configure the DCS appliance's network settings by changing its administrator password, updating its IP addresses (including node IPs, virtual IP, gateway, and subnet), and accepting the EULA. It sets up a two-node cluster with specified IPv4 addresses and ensures the DCS is reachable via... | def dcs_network_configuration(self, app1Ipv4Addr, app2Ipv4Addr,
virtIpv4Addr, ipv4Gateway, ipv4Subnet):
"""Changes the passwordthe dcs appliance and sets new Ip of the appliamce.
Parameters:
app1Ipv4Addr: str ... |
def add_column(self, product_table_name):
"""
To add a empty column in endpoints-support.md file
till end of file with new API version in header
only once
"""
count = 0
self.load_md()
for line in self.all_lines:
count += 1
if prod... | The main task of the code is to scrape data from specified resources, process it by adding checks between start/end rows, and write the results to an endpoints file in Markdown format. It iterates through resource names, performs web scraping, formats data, and updates the output file incrementally, concluding with a c... | def main(self):
i = 0
print("------Initiating write to endpoints file--------")
# # for ele in self.resource_dict.keys():
# # formatted_resource_name = '**' + ele + '**'
# # self.resource_names.append(formatted_resource_name)
self.add_column(self.product_table_nam... |
def remove_node_from_neighbouring_list(node, neighbour_list):
removed_node = None
for n in neighbour_list:
if n[0] == node:
removed_node = n
neighbour_list.remove(n)
if node in n[1]:
n[1].remove(node)
return removed_node
def get_current_neighbour(nodes,... | This function performs a crossover operation between two parent paths (parent1 and parent2) to generate a new child path (k). It starts with a random node from either parent, then iteratively selects the next node by choosing the best available neighbor (based on edges) or a random one if no neighbors exist, ensuring t... | def crossover(parent1, parent2, edges):
k = []
previous = None
current = random.choice([parent1[0], parent2[0]])
while True:
k.append(current)
if len(k) == len(parent1):
break
previous = remove_node_from_neighbouring_list(current, edges)
current_neighbour =... |
def fitness(x):
m_x = np.zeros(n)
m_y = np.zeros(n)
# print(x)
# print(x[1])
# Calculate the unbalance of the total system in iterative loop
for j in range(0, n):
m_x[j] = Blade_data[x[j], 1] * r * np.cos((2 * 180 * j) / n)
m_y[j] = Blade_data[x[j], 1] * r * np.sin((2 * 180 * j) ... | The code implements a genetic algorithm to optimize a permutation-based problem, aiming to find the best solution (highest fitness score) over a number of generations. It initializes a population of random permutations, evaluates fitness, selects parents, applies crossover and mutation with given probabilities, and upd... | def genetic_algorithm(fitness, n_iter, n_pop, pc, pm):
# initial population of random bitstring
blade = []
change = 5000
for i in range(1, n + 1):
blade.append(i)
# print(blade)
pop = [random.sample(blade, len(blade)) for _ in range(n_pop)]
# print(pop)
# keep track of best solut... |
def init_malmo(self):
"""
Initialize new malmo mission.
"""
my_mission = MalmoPython.MissionSpec(self.get_mission_xml(), True)
my_mission_record = MalmoPython.MissionRecordSpec()
my_mission.requestVideo(1000, 700)
my_mission.setViewpoint(1)
max_retries = ... | The code resets the environment for a new episode by reinitializing Malmo, tracking episode metrics (returns, steps, diamonds collected), logging data periodically, and returning the initial observation as a flattened numpy array. | def reset(self):
"""
Resets the environment for the next episode.
Returns
observation: <np.array> flattened initial obseravtion
"""
# Reset Malmo
world_state = self.init_malmo()
# Reset Variables
self.returns.append(self.episode_return)
... |
def init_malmo(self):
"""
Initialize new malmo mission.
"""
my_mission = MalmoPython.MissionSpec(self.get_mission_xml(), True)
my_mission_record = MalmoPython.MissionRecordSpec()
my_mission.requestVideo(1200, 900)
my_mission.setViewpoint(1)
max_retries = ... | The code resets the environment for a new episode by reinitializing Malmo, updating tracking variables (episode returns, steps, diamonds collected), logging data periodically, and returning a flattened initial observation. It prepares the environment state for the next episode while maintaining episode-specific metrics... | def reset(self):
"""
Resets the environment for the next episode.
Returns
observation: <np.array> flattened initial obseravtion
"""
# Reset Malmo
world_state = self.init_malmo()
# Reset Variables
self.returns.append(self.episode_return)
... |
def enterCommand(self):
command = "0"
print('')
print("Enter command (help for Q&A)")
while (command not in self.commands):
command = input("->")
if (command not in self.commands):
print("There is no such command")
else:
... | The code defines a method `dostaff` that runs a loop until a task value of 1 is received. It displays a menu for a QR matrix method, processes user commands (tasks 2-11) to handle data input, display, configuration, and matrix operations, and exits when task 1 is selected. | def dostaff(self):
task = 0
while (task != 1):
print('')
print("QR (Lab1) method for matrix v0.0002 betta")
print('')
task = self.enterCommand()
if (task == 2):
self.somedata()
pass
elif (task == 3):
... |
def enterCommand(self):
command = "0"
print('')
print("Enter command (help for Q&A)")
while (command not in self.commands):
command = input("->")
if (command not in self.commands):
print("There is no such command")
else:
... | The main task of the code is to handle a menu-driven interface for matrix operations. It continuously prompts the user for commands, executing tasks like showing help, inputting new data, displaying matrices, or creating defaults. The loop persists until the user selects task 1, which terminates the loop. Recursive cal... | def dostaff(self):
task = 0
while (task != 1):
print('')
print("Matrix calculation v0.0002 betta task #15")
print('')
task = self.enterCommand()
if (task == 2):
self.dostaff()
elif (task == 3):
pass
... |
def __print_markdown(self, data: str):
self.__console.print(Markdown(data))
def __upload(self, path) -> Optional[str]:
resp: ServerResponse = self.__api.upload(path, self.__token)
if resp["code"] != 0:
print_from_resp(self.__console, resp)
return
return resp["data... | (The main task of the code is to deploy a local Python application or a Git repository to Funix Cloud. It handles both local file/directory uploads and Git URLs, validates entry files, packages code into a zip, uploads it, and monitors deployment status. It also manages environment variables, rate limiters, and app sec... | def deploy(
self,
url_or_path: str,
instance_name: str,
file: str = "main.py",
no_frontend: bool = False,
transform: bool = False,
app_secret: str | None = None,
rate_limiters: list[RateLimiter] | None = None,
env: dict[str, str] | None = None,
... |
def generate_recommendation(self, transcript: Transcript) -> str:
"""
Generates a recommendation for a given transcript using the OpenAI
GPT-3 model.
Args:
transcript (Transcript): The transcript object containing the text
for which recommendation is needed.
... | The main task of the code is to process transcript files, generate recommendations for each, and save them in text, JSON, and SQLite formats within configured folders. It ensures directory existence, creates a SQLite database, and stores recommendation data alongside transcript filenames. Each recommendation is logged ... | def generate_recommendations(self) -> None:
"""
Processes each transcript file and generates recommendations.
The recommendations are saved in various formats in the
configured folders.
"""
# Ensure the base folders exist
self.config.RECOMMENDATIONS_FOLDER.mkdir(e... |
def get_superuser_session(users_dict, login_hosts, login_port):
"""
Search for an administrator user in the users_dict dictionary and return connected cassandra session
:param users_dict: Dictionary with alupperl users sent to ansible module
:param login_hosts: Cassandra host or hosts list
:param lo... | (The code defines an Ansible module to manage Cassandra users by validating connection parameters, establishing a session with a superuser, checking user configuration changes, and applying them if not in check mode. It processes each user in `users_dict`, compares against existing configurations, and reports or execut... | def main():
global module
module = AnsibleModule(
argument_spec={
'users_dict': {
'required': True,
'no_log': True,
'type': 'dict'
},
'login_hosts': {
'required': True,
'type': 'list'
... |
def get_superuser_session(users_dict, login_hosts, login_port):
"""
Search for an administrator user in the users_dict dictionary and return connected cassandra session
:param users_dict: Dictionary with all users sent to ansible module
:param login_hosts: Cassandra host or hosts list
:param login_p... | This code manages Cassandra user permissions via Ansible by comparing desired states (from users_permissions_dict) with current states, applying necessary changes (grant/revoke privileges) on target hosts, and returning a summary of changes made. It uses a superuser session for cluster access and supports check mode fo... | def main():
global module
module = AnsibleModule(
argument_spec={
'users_permissions_dict': {
'required': True,
'no_log': True,
'type': 'dict'
},
'users_dict': {
'required': True,
'no_log'... |
def get_poke_species_list(self):
response = requests.get(self.poke_species_url)
count = response.json()['count']
response = requests.get(self.poke_species_url + '?limit=' + str(count))
return response.json()['results']
def get_poke_list(self):
response = requests.get(self.poke_ur... | The code initializes a class to fetch Pokémon data from the PokeAPI, cache it, and insert Pokémon attributes into a database. It sets up URLs, retrieves species and Pokémon lists, loads cached data, and iterates through each Pokémon to extract details and store them in the database using the `insert` method. | def __init__(self, db):
self.poke_species_url = 'https://pokeapi.co/api/v2/pokemon-species/'
self.poke_url = 'https://pokeapi.co/api/v2/pokemon/'
self.poke_species = self.get_poke_species_list()
self.poke_list = self.get_poke_list()
self.cache = {}
self.species_cache = {}... |
def in_window(seed_eta, seed_phi, seed_iz, eta, phi, iz, window_deta_up, windows_deta_down, window_dphi):
if seed_iz != iz: return False, (-1,-1)
# Delta Eta ordering
etaw = eta - seed_eta
if seed_eta < 0:
etaw = -etaw
phiw = DeltaPhi(seed_phi, phi)
if etaw >= windows_deta_down and etaw ... | The function `get_windows` processes event data to associate superclusters (or electron/photon reco objects) with calorimeter (calo) and generated (gen) particles. It filters calo seeds, matches clusters to calo/gen particles, and computes metrics like energy, eta/phi, and cluster accuracy (correct/missing/spurious). O... | def get_windows(self, event, assoc_strategy, nocalowNmax, min_et_seed=1,
sc_collection="superCluster", reco_collection="none", loop_on_calo=False, debug=False):
## output
output_object = []
output_event = []
# Branches
pfCluster_energy = event.pfCluster_ener... |
def make_dirs():
if not os.path.exists('img/'):
os.makedirs('img/')
def scan_planet(Data=None, real_data=False, numel=[101, 101, 0], planet_id=5, nu=100e9, T=110,
beam_type='po', p=None, fwhm=40./60., angle=30., ec=1.5,
noise_type=None, fit=False, compute_bias=False):
... | The code runs multiple simulations (`sim_number`) by varying a specified parameter (`noise`, `fwhm`, `nsamp`, or `ra_dec`), collecting results in a 2D array. It saves the data to a pickle file and, if enabled, plots a histogram of the fifth column (e.g., `fwhm` differences) to visualize parameter distribution across si... | def run_sims(sim_number, pace=1, parameter='noise', plot_comparison=True):
comparison = np.zeros((sim_number,7))
make_dirs()
if parameter == 'noise':
for i in range(sim_number):
print(' sim {}/{}'.format(i, sim_number))
comparison[i,:] = scan_planet(noise_type='random')
... |
def is_solved(self):
return '0' not in self.cases.values()
def count_zero(self):
count = 0
for elt in self.cases.values():
if elt == '0':
count += 1
return count
def getPossibility(self, case):
"""returns a list of possible numbers that could go in the... | The code solves a Sudoku puzzle by iteratively filling cells with only one possible value and checking for numbers that can only fit in one position. It repeats this process until the puzzle is solved or a sanity check (max 100 iterations) is exceeded, ensuring logical deduction without backtracking. The method updates... | def solve(self):
sanity_check = 0
while not self.is_solved():
sanity_check += 1
if sanity_check > 100:
print("Err, something went wrong...")
break
before = 0
after = -1
while before != after:
befo... |
def gen_crest(xyz_files, out_files):
# generate crest conformer ensemble (crest_conformers.xyz, cre_members, crest.energies)
# from a group of xyz files for the same molecule (list_xyz_files)
fail = False
# initialize lists
cre_members = []
energies = []
xyz = []
raw_files = []
cre_m... | The code generates molecular descriptors for multiple conformers using ORCA calculations, applies Boltzmann weighting, and returns descriptor dictionaries, conformer ensembles, and calculation metadata for a given number of salt structures. | def get_ORCA_descriptors(orca_dir, n=58, ORCA=True, withh=True, dispersion=True, SASA=True, XTB=True, LFCs=False):
conf_dict = {}
desc_dict = {}
for i in list(range(n)):
print(f"----- Salt #{i} -----")
# orca_dir = f"salt_{i}/with_chlorine/CONFORMERS/ORCA/"
xyz_files = [orca_dir+j for... |
def generate_real_samples(dataset, n_samples):
# choose random instances
ix = randint(0, dataset.shape[0], n_samples)
# select images
X = dataset[ix]
# generate class labels, -1 for 'real'
y = -ones((n_samples, 1))
return X, y
def generate_fake_samples(generator, latent_dim, n_samples):
... | The code trains a GAN by iteratively updating the critic (Wasserstein critic) multiple times per generator update, using real and synthetic samples. It tracks losses, evaluates performance periodically, and plots training progress. The critic is trained on real/fake data, while the generator is optimized via the combin... | def train(g_model, c_model, gan_model, dataset, latent_dim, n_epochs=10, n_batch=64, n_critic=5):
# calculate the number of batches per training epoch
bat_per_epo = int(dataset.shape[0] / n_batch)
# calculate the number of training iterations
n_steps = bat_per_epo * n_epochs
# calculate the size of ... |
def init_map(self):
"""Intialize the map before each search"""
# Add start and goal nodes
self.start_node = Node(self.start)
self.goal_node = Node(self.goal)
# Initialize the containers
self.samples = []
self.solution = []
# Update samples and kdtree
... | The main task of the code is to search for a path in a graph from a start configuration to a goal configuration using a specified RRT-based algorithm (RRT, RRT*, or Informed RRT*). The function initializes the environment, selects the appropriate path-planning method based on the sampling strategy, executes the algorit... | def plan(self, start, goal):
"""Search for a path in graph given start and goal location
arguments:
start - start configuration
goal - goal configuration
"""
self.start = start
self.goal = goal
self.init_map()
if self.sampling_method == "... |
def same_classification(examples):
return len(set(ex.tag for ex in examples)) == 1
def MODE(examples):
if sum(ex.tag == 'yes' for ex in examples) > sum(ex.tag == 'no' for ex in examples):
return 'yes'
return 'no'
def choose_attribute(attributes, examples):
max_gain = -1 # always gain >=0
be... | The main task of the code is to implement the ID3 algorithm for building a decision tree. It recursively selects the best attribute to split examples, creates decision nodes, and constructs subtrees for each attribute value, using majority mode when no attributes remain or examples are exhausted. | def ID3(examples, attributes, default):
if len(examples) == 0:
return Node(default)
elif same_classification(examples):
return Node(examples[0].tag)
elif len(attributes) == 0:
return Node(MODE(examples))
else:
best = choose_attribute(attributes, examples)
tree = N... |
def init_attributes_dic(examples):
for i in range(len(attr_list)):
attr_dic[attr_list[i]] = sorted((list(set(ex.features_values[i] for ex in examples))))
def ID3(examples, attributes, default):
if len(examples) == 0:
return Node(default)
elif same_classification(examples):
return Nod... | The code implements a decision tree classifier using the ID3 algorithm. It trains the model on the provided training data, constructs the decision tree with 'yes' as the target class, evaluates it on the test data by comparing predicted labels with actual tags, and returns the accuracy (ratio of correct predictions) al... | def decision_tree(train_file, test_file):
global attr_list
training, attr_list = read_examples(train_file)
init_attributes_dic(training)
testing, _ = read_examples(test_file)
dt = ID3(training, list(attr_list), 'yes') # tree
# calculate true positive and false negative
right_prediction = s... |
def parse_arguments(arguments: List[str]) -> Tuple[str, Dict[str, str]]:
command, parameters = "", {}
for index, argument in enumerate(arguments):
if index == 0:
command = argument
continue
is_valid_argument = argument.startswith("--")
if not is_valid_argument:
... | The code generates documentation from specified files or directories, handling input validation, output directory configuration via parameters, and recursive file processing. It supports options like `--init-only` and `--recursive`, and outputs generated docs to a specified folder, defaulting to a `docs` subdirectory. | def main():
arguments = sys.argv[1:]
command, parameters = parse_arguments(arguments)
if command == "help":
print(
"gendoc <filename> --out=<output-folder(optional)> --init-only --recursive"
)
else:
if not os.path.exists(command):
create_error(f"{command},... |
def createBitArrayPM(bits):
"""
creates the array of bits to multiply the sin wave
"""
l = len(bits)
bit_array = []
res = get_gausian(DURATION_PM)
bit_len = int(DURATION_PM * SAMPLE_RATE)
for k in range(l):
bit_array.append(np.ones(bit_len) * bits[k])
final_bit_array = bit_ar... | The code performs Phase Modulation (PM) on input binary data, generates a modulated signal, checks for errors during transmission using Hilbert transform (if enabled), and returns the modulated signal samples. It also deciphers the received signal, compares it to original bits, and counts errors. | def PM_modulation(bits, check=False):
t = np.arange(int(SAMPLE_RATE * DURATION_PM) * len(bits)) / SAMPLE_RATE # time base
info = (np.pi / 2) * createBitArrayPM(bits)
print('info = ', len(info))
print('t = ', len(t))
# Phase Modulation
m_t = info * np.cos(2 * PI * FM_PM * t + info)
x = np.... |
def write_sample_list(bits, d=0, t=0, n=1):
final_sample_list = []
### create the one fitted ###
one_array = write_notes(bits, delta=d * FREQ_SHIFT)
### create the zero fitted ###
zeros_array = write_notes(1 - bits, theta=t * PI)
final_array = one_array + zeros_array * n
for samp in final_... | The code's main task is to apply different modulation techniques (FM, binary, phase, PM, or multi-symbol FM) to the input data `to_transmit` based on the specified `mode` parameter, returning the corresponding modulated signal as a list of samples. It selects the appropriate modulation method and delegates the generati... | def modulation(to_transmit, mode=None):
if mode == "FM":
### simple FREQUENCY_SHIFT modulation
final_sample_list = write_sample_list(to_transmit, d=1)
elif mode == "binary":
### simple BINARY_SHIFT modulation
final_sample_list = write_sample_list(to_transmit, n=0)
elif mode... |
def next_observation(self, actions):
if self.is_visual:
next_states, rewards, dones = self.collect_visual_observation(actions, initial=False)
else:
# agent will act on the action vector where everything is set to "0"
# signal it to ignore thes... | The code generates individualized trajectories for each agent by collecting states, actions, rewards, and other attributes over episodes. It processes these into tensors, computes advantages and returns, and reshapes data for training in a PPO framework, returning structured trajectory buffers for each agent. | def create_trajectories(self):
"""
Inspired by: https://github.com/tnakae/Udacity-DeepRL-p3-collab-compet/blob/master/PPO/agent.py
Creates trajectories and splites them between all agents, so each one gets individualized trajectories
Returns:
A list of dictionaries, where each ... |
def get_all_items(clusters):
"""
Unites all items from cluster into one global cluster
:param clusters: input clusters
:return: global cluster
"""
all_items = []
for cluster in clusters:
for item in cluster:
all_items.append(item)
... | This function recursively splits input clusters into smaller clusters using a bisecting k-means approach, prioritizing clusters with higher error values. It repeatedly identifies the most error-prone cluster, splits it into two using k-means, and continues until all clusters meet a minimum size threshold. The process r... | def bisect_kmeans(self, base_clusters, clusters_items):
"""
Splits base clusters to smaller ones
:param base_clusters: input base clusters
:param clusters_items: corresponded item ids to input clusters
:return: output clusters, corresponded item ids to output clusters
"""... |
def set_base_clusters(self, data_set):
"""
Creates base clusters from frequent queries
:param data_set: type of data set (train or test)
:return: base clusters, corresponded item ids for base clusters
"""
query_clusters = []
cluster_items = []
for query in... | The code's main task is to perform clustering by first generating base clusters, splitting them using k-means bisect, merging resulting clusters, calculating centroids for merged clusters, and saving intermediate results (base clusters, merged clusters, centroids, and hierarchy) via pickle files. The function returns m... | def run(self):
"""
Calculate base clusters, splits it with k means bisect, merges
clusters items and calculates centroids for merged clusters
:return:
"""
set_of_data = "train"
base_path = os.path.dirname(os.path.realpath(__file__))
to_base_clusters = os.p... |
def state_to_state_dict(state):
"""state is the state of the system
returns a dictionary mapping the name of the state to its value
"""
names=['Hq0','Hq1','Hq2','Hq3','Hpx','Hpy','Hpz','h_vx','h_vy','h_vz','h_ax','h_ay','h_az','h_gx','h_gy','h_gz']
state_names_body=['Bq0','Bq1','Bq2','Bq3','Bpx','Bp... | The code initializes a state dictionary representing body part orientations and positions using sensor data from head, body, arm, and forearm. It computes quaternions for each segment via sensor data or defaults to previous joints if data is missing. Positions are derived through quaternion transformations, combining o... | def init_state(data_head,data_body,data_arm,data_forearm):
"""data_head is the data from the upper chest sensor
data_body is the data from the abdomen sensor
data_arm is the data from the arm sensor
data_forearm is the data from the forearm sensor
"""
state_dict,ntoid,idtoname=state_to_state_dic... |
def ReadData(card):
# Read the data from the file
col_names=['it','time','ax','ay','az','gx','gy','gz','mx','my','mz']
data = pd.read_csv("measures2m/nav3_body_head@"+card+".csv",names=col_names,header=None)
return data
def observationModel(Qn, Acc, Mag,Mua=1):
# TODO: Find appropriate value for MUA... | The code runs an experiment to estimate the position and orientation (quaternion) of a head and body using Kalman filters, applying constraints between them. It processes sensor data (accelerometer, magnetometer, gyroscope) to update filters, predicts states, and enforces physical constraints (e.g., body-head relations... | def runExperimentConstraint():
HeadData,BodyData = ReadData("head"),ReadData("body")
itHeadmax,itBodymax=HeadData['it'].max(),BodyData['it'].max()
mus=[1]
PosDic={}
VelocityDic={}
for mu in mus:
itHead,itBody = 0,0
KalmanFilterPosHead = KalmanFilterPos(0.01, np.array([0, 0, ... |
def ReadReferenceData():
#loading the reference data
col_names=['it','time0','time1']
Head_names=['Hq0','Hq1','Hq2','Hq3','HQp0','HQp1','HQp2','HQp3','HQo0','HQo1','HQo2','HQo3','Hpx','HVx','Hax','Hpy','Hvy','Hay','Hpz','Hvz','Haz']
Body_names=['Bq0','Bq1','Bq2','Bq3','BQp0','BQp1','BQp2','BQp3','BQo0'... | The main task of the code is to run an unconstrained Kalman filter experiment for head position and orientation estimation using varying mu parameters (0.1–1). It processes accelerometer and gyroscope data iteratively, updates Kalman filters for position and quaternion, and visualizes the resulting position (distance a... | def runExperimentWithoutConstraint():
ReferenceData=ReadReferenceData()
mus=np.linspace(0.1,1,5)
DicResults={}
for mu in mus:
HeadData= ReadData("head")
itHead = 0
itHeadmax=HeadData['it'].shape[0]
KalmanFilterPosHead = KalmanFilterPos(0.01, np.array([0, 0, 0, 0, 0, 0]))
... |
def init_state(data_head,data_body,data_arm,data_forearm):
"""data_head is the data from the upper chest sensor
data_body is the data from the abdomen sensor
data_arm is the data from the arm sensor
data_forearm is the data from the forearm sensor
"""
state_dict,ntoid,idtoname=state_to_state_dic... | The code applies a Kalman filter to sensor data from head, body, arm, and forearm to estimate and refine the system's state. It initializes the state, iterates through synchronized sensor measurements, updates the filter with Jacobian matrices for state transitions, and adjusts the state based on sensor readings (accel... | def kalman_filtering(file):
"""File is the file containing the data
returns the results of the kalman filtering
"""
data_head,data_body,data_arm,data_forearm=(DataIterable(file,"head"),
DataIterable(file,"body"),
... |
def pull_json(custom_user_config):
user_config = os.path.join(user_config_dir,custom_user_config)
with open(user_config) as json_file:
data = json.load(json_file)
return data
def parse_config_json(data):
## note: json contains floats or json contains integers that we turn into floats
if "design... | The main task of the code is to process design configurations from a JSON file, generate constraint directories and DC configurations for each design, and execute bulk test runs. It reads input parameters, parses project data, iterates through design names, creates configuration files, and triggers test execution with ... | def s_config_run(output_dir,custom_user_json):
data = pull_json(custom_user_json)
#current_config_data = parse_config_json(data)
current_project_data = parse_config_json(data)
design_name_list = current_project_data.get_design_name()
run_count = current_project_data.get_run_count()
for name in d... |
def FGSM_attack(model, device, dat, lbl, eps):
# TODO: Implement the FGSM attack
# - Dat and lbl are tensors
# - eps is a float
return PGD_attack(model=model, device=device, dat=dat, lbl=lbl, eps=eps, alpha=1, iters=1, rand_start=False)
def PGD_attack(model, device, dat, lbl, eps, alpha, iters, rand_st... | The code evaluates adversarial attack effectiveness on white-box and black-box models using CIFAR-10. It applies FGSM, PGD, or MomentumIterative attacks with varying epsilon values, measures model accuracy on perturbed data, and plots results to compare white-box and black-box model robustness against specified attack ... | def attack(whitebox_model, blackbox_model, adv_type):
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
best_acc = 0 # best test accuracy
start_epoch = 0 # start from epoch 0 or last checkpoint epo... |
def convert_model(model: dict, generate_view_metadata: bool = False):
"""Convert a LookML model to a ZenML model
Args: model (dict): A LookML model
generate_view_metadata (bool): Whether to generate view metadata
based on the explores in the ... | The main task of the code is to convert a LookML project structure into processed model, view, and dashboard components. It maps views to their associated models using metadata, processes each model/view with conversion methods, and aggregates results into lists for further use. The function returns the converted model... | def convert_project(self, lookml_project: dict):
models, views, dashboards = [], [], []
view_metadata = {}
views_to_models = {}
for raw_model in lookml_project["models"]:
model = self.convert_model(raw_model, generate_view_metadata=True)
model_view_metadata = mode... |
def gas_to_log_scale(gas):
gas["density"] = np.log10(gas["density"])
gas["temperature"] = np.log10(gas["temperature"])
return gas
def get_gas(z, id):
_, sim_path = get_sim()
gas = il.snapshot.loadHalo(sim_path, get_snap_number(z), id, "gas")
mass_to_sun = 1e10 / h
gas_dict = {}
gas_dic... | The function processes pairs of input parameters (ids, zs) to generate and compile three types of gas-related data for each pair. It converts gas values to a logarithmic scale, retrieves mapped gas data with different output configurations, and aggregates results into a structured list of lists. The 'conf' parameter in... | def get_halo_gases(zs, ids, conf="esc_analysis"):
halo_gases = []
for id, z in zip(ids, zs):
gases = []
gases.append(gas_to_log_scale(get_gas(z, id)))
gases.append(get_mapped_gas(id, z, get_output=False, conf=conf))
gases.append(get_mapped_gas(id, z, get_output=True, conf=conf))
... |
def get_gas(z, id):
_, sim_path = get_sim()
gas = il.snapshot.loadHalo(sim_path, get_snap_number(z), id, "gas")
mass_to_sun = 1e10 / h
gas_dict = {}
gas_dict["density"] = get_number_dens(gas["Density"], z)
gas_dict["mass"] = gas["Masses"] * mass_to_sun
gas_dict["temperature"] = get_tempera... | The main task of the code is to generate a histogram plot of gas data. It retrieves gas data either from TNG (via `get_gas` and log scaling) or a mapped source (via `get_mapped_gas`), then visualizes the distribution using `plot_histogram` with customizable parameters. The function returns no value but produces the plo... | def generate_histogram_plot(
z, id, from_tng=True, get_output=False, plot_params=None, conf="esc_analysis"
):
if from_tng:
gas = get_gas(z, id)
gas = gas_to_log_scale(gas)
else:
gas = get_mapped_gas(id, z, get_output, conf)
plot_histogram(gas, params=plot_params)
return |
def change_month_to_quarter(month_data: list[tuple[datetime.date, float]]) \
-> list[tuple[datetime.date, float]]:
"""
Return a list of tuples of the data in input file in which the date is from left to right.
The first element of tuple contains the initial date of the quarter in datetime object,
... | The code loads and processes multiple economic datasets (2008–2021) from CSV files, converting them into quarterly time series by adjusting granularity (e.g., monthly to quarterly), reversing data order, and combining overlapping data. It returns a dictionary containing standardized time series for unemployment rate, b... | def loading_data() -> dict[str, list[tuple]]:
"""
Return the dictionary of data, including unemployment rate,
balance of payment, population,composite index,exchange rate,
bond yield, inflation rate,overnight rate from 2008 to 2021.
"""
unemployment_rate_1 = change_month_to_quarter(
load... |
def calcHiddenNode(self, node_index):
sum = 0
for i in range(self.ninput):
inputNode = self.current_input[i]
weight = self.weights[0][i][node_index]
sum += np.multiply(inputNode, weight)
return self.sigmoid(sum)
def calcOutput(self, output_index):
sum... | The code trains a neural network using backpropagation over multiple epochs. It iterates through training data, computes hidden/output layer activations, calculates gradients for weight updates, and adjusts weights in both layers using a decaying learning rate (reduced by 5% per epoch) to minimize error. | def fit(self, training_data, training_label):
for e in range(self.epochs):
for i in range(len(training_data)):
data = training_data[i]
label = training_label[i]
self.current_input = data
for j in range(self.nhidden):
... |
def _iterate_package_files(self):
for package_filename in os.listdir(self._input_dir_path):
package_filepath = os.path.join(self._input_dir_path,
package_filename)
if os.stat(package_filepath).st_size > (1024 * 1024):
logger.war... | (The code generates a JSON package from templated files, saves it in a temporary directory, and returns the file path. It reads files, applies templating, creates a temporary directory, writes the JSON file with package data, and returns the path to the generated JSON file.) | def build_package(self):
'''builds a stub universe json package and returns its location on disk'''
# read files into memory and apply templating to files:
updated_package_files = {}
for filename, content in self._iterate_package_files():
updated_package_files[filename] = se... |
def get_objects_dict(filepath):
lines = open(filepath, 'r').readlines()
objects = {}
for line in lines:
line = line.strip()
if line == '':
continue
line = line.split(',')
gold = line[6]
label = 'unacc'
obj = Car(line[0], line[1], line[2], line... | This code constructs a decision tree by iteratively identifying the most effective rules to classify objects based on their 'unacc' label. It updates the tree structure, removes classified objects, adjusts rule counts, and repeats until improvement falls below a threshold, refining the model through rule-based node cre... | def learn(self, filepath):
self.root = Node('True', 'obj.conclusion == "unacc"', None, None, None, [], 0)
objects = get_objects_dict(filepath)
curr_node = self.root
label = 'unacc'
correct_counts = {}
for obj in objects[label][label]:
rules = generate_rules... |
def _init_model(
self,
device,
train_dataset,
valid_dataset,
train_sampler,
valid_sampler,
train_bs,
valid_bs,
n_jobs,
callbacks,
fp16,
train_collate_fn,
valid_collate_fn,
train_shuffle,
valid_shuffle... | This function trains a machine learning model using specified datasets, hyperparameters, and validation. It initializes the model, iterates over epochs, performs training/validation cycles, updates learning rate schedulers, and handles device placement (CPU/GPU/TPU). The deprecated warning advises using newer versions ... | def fit(
self,
train_dataset,
valid_dataset=None,
train_sampler=None,
valid_sampler=None,
device="cuda",
epochs=10,
train_bs=16,
valid_bs=16,
n_jobs=8,
callbacks=None,
fp16=False,
train_collate_fn=None,
valid... |
def _set_training_start(self, data_loader):
if isinstance(data_loader, DataLoader) and isinstance(data_loader.sampler, DistributedSampler):
data_loader.sampler.set_epoch(self.current_epoch)
self.model_state = enums.ModelState.TRAIN
self.train_state = enums.TrainingState.TRAIN_EPOCH_... | The code trains a model by iterating through a data loader, executing training steps for each batch, accumulating losses and metrics, and finalizing training. It initializes training, processes each batch to compute loss and metrics, updates tracking variables, and concludes training with end-state setup. | def train(self, data_loader):
self._set_training_start(data_loader)
losses = AverageMeter()
for batch_index, data in enumerate(data_loader):
self.batch_index = batch_index
self.train_state = enums.TrainingState.TRAIN_STEP_START
loss, metrics = self.train_step(... |
def _init_trainer(self, train_dataset, valid_dataset, config, **kwargs):
self.config = config
self.train_dataset = train_dataset
self.valid_dataset = valid_dataset
if "train_loader" in kwargs:
self.train_loader = kwargs["train_loader"]
else:
self.train_lo... | This code trains a machine learning model for a specified number of epochs using the provided training dataset, with optional validation on a separate dataset each epoch. It initializes training parameters, executes training and validation loops, manages learning rate scheduling, and tracks training states like epoch p... | def fit(self, train_dataset, valid_dataset=None, config: FlashConfig = None, **kwargs):
if config is None:
config = FlashConfig()
self._init_trainer(train_dataset, valid_dataset, config, **kwargs)
for _ in range(self.config.epochs):
self.train_state = enums.TrainingState... |
def get_rel_frame(display_frame=None, current_frame=None):
if display_frame is None:
display_frame = get_display_frame()
if current_frame is None:
current_frame = get_current_frame()
rel_frame = {}
rel_frame['x'] = float(current_frame['x']-display_frame['x']) / display_frame['w']
rel_frame['w'] = float(curre... | The function `get_frame_position` determines a specific position index from a predefined list (`positions`) based on the relative relationship between `display_frame` and `current_frame`. It evaluates the relative frame using helper functions like `_is_pos_right` or `_is_pos_left` (and their fractional variants) to che... | def get_frame_position(display_frame=None, current_frame=None):
rel_frame = get_rel_frame(display_frame, current_frame)
if _is_pos_right(rel_frame):
return positions[6]
if _is_pos_right_2_3(rel_frame):
return positions[66]
if _is_pos_right_1_3(rel_frame):
return positions[666]
if _is_pos_left(rel_fram... |
def _call_strategy(self, current_date, raw_minute_data, offered_options):
# Do we need to call the strategy? We won't call it on empty data
if len(raw_minute_data) != 0:
self.run_strategy_for_minute(raw_minute_data, offered_options)
self.execute_options(current_date, offered_opti... | This code processes CSV data containing options and minute-level financial data. It groups data by date, feeds it to a strategy for analysis, initializes options data, and liquidates remaining positions. It logs date changes, updates options dictionaries with bid/ask prices/volumes, and generates a final chart after pr... | def run(self):
with open(self.data_path) as data_file:
data = csv.reader(data_file)
offered_options, raw_minute_data = {}, []
current_date = ''
for i, row in enumerate(data):
# Ignores the first row as its all titles
if i == 0:
... |
def check_bazi(karbar):
c = 0
for i in range(3):
for j in range(3):
if bazi[i][j] != "-" :
c = c + 1;
if (bazi[0][0] == "🔴" and bazi[0][1] == "🔴" and bazi[0][2] == "🔴" ) :
print_natije("karbar1")
return False
elif (bazi[0][0] == "🔵" and bazi[0... | The main task of the code is to allow a player to take turns placing their piece (🔴) on a board by selecting row and column coordinates. It checks if the selected cell is empty, updates the board if valid, and repeatedly prompts the user until a valid move is made. The function also triggers the PC's turn via `init_pc... | def playwithpc():
while check_bazi("pc"):
while True :
print("shoma ba mohre 🔴 bazi mikonid . ")
karbar_row = int(input ("satr mored nazar khod ra vared konid :"))
karbar_col = int(input ("sotoon mored nazar khod ra vared konid :"))
if bazi[karbar_row-1][karb... |
def read_docs(file):
'''
Reads the corpus into a list of Documents
'''
docs = [defaultdict(list)] # empty 0 index
category = ''
with open(file) as f:
i = 0
dev_start = 0
for line in f:
line = line.strip()
token_line = word_tokenize(line)
... | The code evaluates a text classification model by calculating cosine similarity between query vectors and category centroids derived from training data. It processes documents and queries, computes term frequency profiles for categories, and classifies queries by comparing their similarity to centroids of two categorie... | def experiment():
file = sys.argv[1]
docs = read_docs(file + '.-train.tsv')
queries = read_docs(file + '.-dev.tsv')
processed_docs, processed_queries = process_docs_and_queries(docs, queries, True, False)
category1_total = 0
category2_total = 0
#category3_total = 0
#category4_total = ... |
def read_docs(file):
'''
Reads the corpus into a list of Documents
'''
docs = [defaultdict(list)] # empty 0 index
category = ''
with open(file) as f:
i = 0
dev_start = 0
for line in f:
line = line.strip()
token_line = word_tokenize(line)
#Extracting the line from the JSON file, we want to ex... | The code conducts an experiment to evaluate the accuracy of a classifier trained on sentiment analysis features and category labels from documents, then compares predicted categories against actual labels in query data. It also includes a commented-out section for computing cosine similarity between query vectors and c... | def experiment():
file = sys.argv[1]
docs = read_docs(file + '.-train.tsv')
queries = read_docs(file + '.-dev.tsv')
processed_docs, processed_queries = process_docs_and_queries(docs, queries, True, False)
#SENTIMENT ANALYSIS AND PROCESSING TO BE ABLE TO FIT, TRAIN, AND PREDICT CATEGORIES FOR NEW HEADLINES
#ADD/D... |
def advance(self) -> str:
"""Finds the next character and increment the location."""
# Consider using try/finally here
char = self.source[self.current]
self.current += 1
self.column += 1
return char
def match(self, expected: str) -> bool:
"""Return True and advanc... | This function scans the source code to identify and add a single token, handling punctuation, operators, comments, whitespace, and identifiers. It uses pattern matching to determine token types, checks for multi-character operators (e.g., "!="), skips comments, and delegates to helper methods for numbers, strings, and ... | def scan_token(self) -> None:
"""Scan the source, with the goal of identifying a single Token."""
add_token = self.add_token
match char := self.advance():
case "(":
add_token(TT.LEFT_PAREN)
case ")":
add_token(TT.RIGHT_PAREN)
ca... |
def intializeClient(client_connection, client_address):
#Exchange Public Keys
client_connection.send(
PUB_KEY.public_bytes(
encoding=serialization.Encoding.Raw,
format=serialization.PublicFormat.Raw
)
)
peer_pub_key_bytes = client_connection.recv(2048)
peer_pu... | This code handles client connections by initializing encryption keys, decrypting incoming messages using Fernet, broadcasting decrypted messages to other clients, and managing disconnections by notifying users and removing the client from the system. It continuously receives data, processes it, and ensures secure commu... | def clientConnection(connection, connection_address):
client_key = intializeClient(connection, connection_address)
client_keys.append(client_key)
client_fernet = Fernet(client_key)
while True:
cipher = connection.recv(2048) # Accept and receive up to 2 bytes of data from the message
mess... |
def Conv2DNormLReLU(inputs, filters, kernel_size=3, strides=1, padding='same', use_bias=False):
x = Conv2D(inputs, filters, kernel_size, strides, padding=padding, use_bias=use_bias)
x = layer_norm(x)
return lrelu(x)
def dwise_conv(input, kernel_size=3, channel_multiplier=1, strides=1, padding='same', use_bi... | This function implements an inverted residual block with expansion, depthwise convolution, and residual connection. It first expands input channels via a 1x1 convolution, applies depthwise convolution with normalization and activation, then reduces channels to output_dim. A residual connection is added if input/output ... | def InvertedRes_block(input, expansion_ratio, output_dim, stride, use_bias=False):
# pw
bottleneck_dim = round(expansion_ratio * input.get_shape().as_list()[-1])
net = Conv2DNormLReLU(input, bottleneck_dim, kernel_size=1, use_bias=use_bias)
# dw
net = dwise_conv(net)
net = layer_norm(net)
n... |
def conv(x, channels, kernel=4, stride=2, use_bias=True):
return tf.keras.layers.Conv2D(filters=channels,
kernel_size=kernel,
strides=stride,
padding='same',
use_bias=use_bias)(x)
... | The code defines a discriminator network for a GAN, processing input images through multiple convolutional layers with increasing filters, downsampling, and LeakyReLU activations. It uses layer normalization and outputs a single-channel classification, distinguishing real/fake images via a series of strided convolution... | def discriminator(image_size=(64, 64), channels=3, kernel_size=3, init_filters=64, n_dis=3):
input1 = tf.keras.layers.Input((image_size[0], image_size[1], channels))
x = input1
init_filters = init_filters // 2
x = conv(x, init_filters, kernel=kernel_size, stride=1, use_bias=False)
x = lrelu(x, 0.2)... |
def Conv2DNormLReLU(inputs, filters, kernel_size=3, strides=1, padding='same', use_bias=False):
x = Conv2D(inputs, filters, kernel_size, strides, padding=padding, use_bias=use_bias)
x = layer_norm(x)
return lrelu(x)
def InvertedRes_block(input, expansion_ratio, output_dim, stride, use_bias=False):
# pw
... | The code defines a generator model for a GAN, processing input images through convolutional layers, downsampling, inverted residual blocks, and upsampling to generate high-resolution output images with tanh activation, likely for image-to-image translation tasks. | def generator(image_size=(64, 64), channels=3, kernel_size=3, init_filters=32):
input1 = tf.keras.layers.Input((image_size[0], image_size[1], channels))
x = input1
x = Conv2DNormLReLU(x, init_filters, kernel_size=7)
x = Conv2DNormLReLU(x, init_filters * 2, kernel_size=kernel_size, strides=2)
x = C... |
def selection(node):
"""Select a node in the tree to expand."""
while not node.state.is_game_over(claim_draw=True):
if node.untried_moves:
return expansion(node)
else:
node = node.uct_select_child()
return node
def simulation(node):
"""Simulate a random game from ... | The code implements the Monte Carlo Tree Search (MCTS) algorithm by iteratively selecting leaf nodes, simulating game outcomes, and backpropagating results to update node statistics. After specified iterations, it returns the move associated with the root node's child having the highest visit count, representing the op... | def mcts(root, iterations=1000):
for _ in range(iterations):
leaf = selection(root)
simulation_result = simulation(leaf)
backpropagation(leaf, simulation_result)
# Return the move of the best child based on the highest number of visits
return max(root.children, key=lambda child: chil... |
def _create_display(self, size: (int, int)) -> None:
"""Create display and make it resizeable"""
pygame.display.set_mode(size, pygame.RESIZABLE)
def _draw_current_board(self, color):
"""Draw the current game board with visual effect when matching and landing"""
self._draw_grid_board(colo... | This code initializes and runs a Pygame-based game, managing a falling block (faller) matching game. It creates a 13x6 gameboard, handles game states (active faller, matches, game over), updates game logic every second, and redraws the board with appropriate colors. The loop processes events, checks for matches, spawns... | def run(self):
"""Run the program"""
pygame.init()
try:
ENTER_EVENT = pygame.event.custom_type()
pygame.time.set_timer(ENTER_EVENT, 1000)
self._gameboard = self._gamestate.create_empty_board(13, 6)
self._create_display((_INITIAL_WIDTH, _INITIAL_HEI... |
def make_element_in_board_down(self) -> None:
"""Make all element in the board down"""
board = self.current_game_board()
for i in range(len(board)):
for r in range(len(board)):
for c in range(len(board[r])):
if r != len(board)-1 and board[r][c] != ... | This method scans the game board to identify and mark matching sequences of characters. It iterates through each cell, checks for matches using `matching_sequence_begin_at`, updates the board with '*' for matches, and updates the game state if any changes occur. | def matching(self) -> None:
"""
Check the entire board and if there is matching it will mark the matching character with *
"""
self.make_element_in_board_down()
rows = self._row
columns = self._col
change = []
for row in range(rows):
for col in... |
def freeze_board(self) -> None:
"""Change the format of the faller to freeze"""
board = self.current_game_board()
for i in range(len(board)):
for j in range(len(board[i])):
if '|' in board[i][j]:
board[i][j] = board[i][j][1]
self.update_gam... | This function freezes a Faller object by updating its status, freezes its color list, updates the gameboard, checks for matches, and redraws the board to reflect the frozen state. | def freeze_faller_action(self, faller: Faller) -> None:
"""
Given a Faller object, change the faller state
to freeze, and update faller status on gameboard.
Check matching and draw the gameboard
"""
faller.change_faller_status_to_freeze()
faller.freeze_color_list(... |
def current_game_board(self) -> list[list[str]]:
"""Return the current game board"""
return self._game_board
def there_is_a_match(self) -> bool:
"""Return the matching status"""
return self._matching
def update_matching_game_board(self) -> list[list[str]]:
"""
Replace cha... | This function handles the movement and status updates of a falling element (faller) in a game. It moves the faller down if possible, freezes it upon landing or reaching the board's bottom, checks for game-over conditions, updates the game board, and processes matches by clearing them and resetting the matching status. | def enter_action(self, faller=None) -> None:
"""
Perform enter action, move every element in the faller down
The function also check the status of the faller and update it if necessary
If the faller freeze it will also check if the game is over
"""
game_board = self.curre... |
def constructInitialSolution(self):
initial_trains = self.trains.copy()
initial_unassigned_orders = self.orders.copy()
sort_order = sorted(initial_unassigned_orders, key=lambda x : x.getPriority(), reverse= True)
for job in sort_order:
best_train = None
best_co... | The code's main task is to iteratively optimize a delivery solution by evaluating multiple path splits for each "bad" job, selecting the lowest-cost train combinations to fulfill orders, and updating the solution if improvements are found. It processes each bad job, explores all possible paths, splits them, identifies ... | def runAlgorithm(self):
print("Construct initial solution")
best_solution = self.constructInitialSolution()
print(best_solution.calculateCost())
best_solution.printSolution()
bad = self.bad_jobs.copy()
for order in bad:
paths = self.graph.find_all_paths(order.... |
def getAdmins(groupName):
'''
RETURNS A LIST of all admins given a groupName
'''
db = sqlite3.connect("data/draw.db")
c = db.cursor()
command = 'SELECT username FROM groupMembership WHERE groupName = (?) AND admin = 1 AND request = 0 AND banned = 0;'
c.execute(command,(groupName,))
selec... | The function adds a member to a group by verifying they are not already an admin, member, or banned. If valid, it updates the database to accept the membership request and returns True; otherwise, it returns False. | def addMember(groupName, member):
'''
admin adds a member
'''
if member not in getAdmins(groupName) and member not in getMembers() and member not in getBanned():
return False
else:
requestGroup(member, groupName)
db = sqlite3.connect("data/draw.db")
c = db.cursor()
... |
def qabbalize_and_store(text):
text = text.strip().upper()
aq_value = qabbalize(text)
if text not in DICTIONARY[aq_value]:
print(f"adding {text} with aq value {aq_value} to library")
DICTIONARY[aq_value].add(text)
write_to_store(aq_value, text)
return aq_value
def reverse_lookup(... | This function processes input text by normalizing it and applying qabbalization (a form of text encoding). If 'store' is True, it stores the result; otherwise, it only computes it. When 'rev' is True, it performs a reverse lookup on the computed value and returns formatted results. The function returns either the norma... | def aq_cmd(text, rev=False, store=True):
normalized = text.strip().upper()
if store:
aq = qabbalize_and_store(normalized)
else:
aq = qabbalize(normalized)
print(f"aqabbalized text {normalized} ={aq}")
if rev:
results = reverse_lookup(aq)
fmt = format_rev_lookup(resul... |
def get_state_bounds(self):
if isinstance(self.env, LDSEnv):
state_bound_x = 1.2
state_bound_y = 1.2
elif isinstance(self.env, PendulumEnv):
state_bound_x = 2.8
state_bound_y = 4
else:
raise ValueError("Something isn't right")
r... | This function formulates and solves a mixed-integer program (MIP) to verify system properties by encoding neural networks (ind, policy) into the model. It constructs constraints for state transitions, maximizes the output difference between pre- and post-state encodings, and checks for counterexamples. If optimal, it r... | def check_mip(self):
state_bound_x, state_bound_y = self.get_state_bounds()
opt_model = mip.Model()
mip_ind1 = MixedIntegerEncoding(
self.ind, [-state_bound_x, -state_bound_y], [state_bound_x, state_bound_y]
)
mip_ind1.encode_network(opt_model=opt_model, name="ind_pr... |
def collect_trajectories(policy, env, n=100, prefer_border=False):
buffer = []
for i in range(n):
buffer.extend(single_trajectory(policy, env, prefer_border))
return np.stack(buffer, 0)
def sample_init_border(env, n):
x1 = default_rng.uniform(env.init_space.low[0], env.init_space.high[0], n // 2... | The main task of the code is to generate labeled training data for a safety indicator model. It collects 30 trajectories using the policy, adds 200 border samples, then samples 30% unsafe states based on the environment type (LDSEnv or Pendulum). Safe samples are labeled 1, unsafe 0, and the function returns concatenat... | def get_indicator_training_data(
env,
policy,
bootstrap,
):
pos_samples = collect_trajectories(policy, env, n=30, prefer_border=True)
pos_samples = np.concatenate([pos_samples, sample_init_border(env, n=200)], 0)
amount_of_unsafe = int(0.3 * pos_samples.shape[0])
if isinstance(env, LDSEnv):
... |
def sample_bootstrap(policy, env, n=5000):
print("Collecting unsafe data")
buffer_pos = []
buffer_neg = []
while len(buffer_pos) < n or len(buffer_neg) < n:
px = default_rng.integers(-env.bound_x, env.bound_x + 1)
ax = default_rng.integers(-env.bound_x, env.bound_x + 1)
ay = defa... | The function generates training data for a classifier by collecting safe trajectories (positive samples) and unsafe region samples (negative samples), then concatenating them with corresponding labels. If bootstrapping is enabled, it returns bootstrap samples; otherwise, it uses a ratio to balance positive and negative... | def get_indicator_training_data(policy, env):
if args.bootstrap:
return sample_bootstrap(policy, env)
pos_samples = collect_trajectories(policy, env, n=args.p_trajectories)
amount_of_unsafe = int(args.pm_ratio * pos_samples.shape[0]) # Same amount of less?
neg_samples = sample_unsafe_region_car... |
def check_mip(self):
state_bound_x, state_bound_y = self.get_state_bounds()
opt_model = mip.Model()
mip_ind1 = MixedIntegerEncoding(
self.ind, [-state_bound_x, -state_bound_y], [state_bound_x, state_bound_y]
)
mip_ind1.encode_network(opt_model=opt_model, name="ind_pr... | The code runs a loop to iteratively verify and refine a MIP (Mixed Integer Program) solution. It checks initial and unsafe state conditions, performs sanity checks on predictions, and fine-tunes a model using collected counterexamples. If verification passes, it returns True; otherwise, it raises errors or exits on tim... | def run_loop(self, max_steps=None, timeout=None):
start_time = time.time()
step = 0
while max_steps is None or step < max_steps:
step += 1
print(f"Running MIP step {step}")
ce = self.check_mip()
if ce is None:
# Done # Plot before e... |
def get_indicator_training_data(
env,
policy,
bootstrap,
):
pos_samples = collect_trajectories(policy, env, n=30, prefer_border=True)
pos_samples = np.concatenate([pos_samples, sample_init_border(env, n=200)], 0)
amount_of_unsafe = int(0.3 * pos_samples.shape[0])
if isinstance(env, LDSEnv):
... | This code initializes an indicator network for policy training, using counterexamples and a given environment. It sets up a neural network (ReluNetwork) with Adam optimizer and binary crossentropy loss, trains it on generated data from the environment and policy, and optionally initializes a counterexample buffer with ... | def __init__(
self,
env,
policy,
ind_hidden_dim,
train_eps,
init_samples,
gen_plot=False,
bootstrap=False,
):
os.makedirs("loop", exist_ok=True)
self.ce_buffer = CounterExampleBuffer()
self.env = env
self.policy = policy... |
def get_indicator_training_data(policy, env):
if args.bootstrap:
return sample_bootstrap(policy, env)
pos_samples = collect_trajectories(policy, env, n=args.p_trajectories)
amount_of_unsafe = int(args.pm_ratio * pos_samples.shape[0]) # Same amount of less?
neg_samples = sample_unsafe_region_car... | This code initializes a neural network (ind) to act as an indicator function, trains it using policy-environment data, and sets up counterexample handling. It compiles a ReluNetwork with Adam optimizer, trains it on generated data, and optionally initializes a counterexample buffer. The class also prepares plotting tra... | def __init__(
self,
env,
policy,
ind_hidden_dim,
train_eps,
init_samples,
gen_plot=False,
first_layer_trick=False,
):
os.makedirs("loop", exist_ok=True)
self.ce_buffer = CounterExampleBuffer()
self.env = env
self.policy ... |
def _do_down_conv(self, layer, num_filters):
"""Helper function for convolution and downsampling.
Parameters
----------
layer : Layer
The layer to operate on.
num_filters : int
The number of filters for the convolutional layers.
Returns
-... | The code constructs a U-Net-like image segmentation model using TensorFlow. It builds downsampling layers with increasing filters, a bottleneck layer, upsampling layers with decreasing filters, and a final output layer. The model processes input images through these stages to produce segmented outputs, leveraging skip ... | def _build_model(self):
"""Build the model
Returns
-------
model : Model
The tensorflow model for image segmentation.
"""
input_layer = layers.Input((None, None, 3))
pool = input_layer
down_layers = []
for i in range(config.NUM_DOWNSA... |
def gen_import(args):
# Ensure that the import statements specified by the option comes later.
# For example, if we want to use orjson and specify `import orjson as json`,
# this import statement needs to be added after the import statement
# `import json` added by pypipe.
imports_opt = get_optional... | This function generates and executes code to parse records from input using regex or delimiters, handling headers, field lengths, and filters. It dynamically constructs parsing logic based on arguments, compiles regex patterns, and formats output using specified viewers or print functions. | def rec_handler(args):
is_regex_delimiter = args.delimiter != r'\t' and len(args.delimiter) > 1
if args.regex is not None:
re_compile = rf"pattern = re.compile(r'{args.regex}')"
parse_header = r"header = pattern.findall(next(sys.stdin).rstrip('\r\n'))" if args.header else ""
parse_line =... |
def gen_import(args):
# Ensure that the import statements specified by the option comes later.
# For example, if we want to use orjson and specify `import orjson as json`,
# this import statement needs to be added after the import statement
# `import json` added by pypipe.
imports_opt = get_optional... | The code generates and executes dynamic Python code to handle CSV file processing, including reading/writing with customizable delimiters and options. It constructs reader/writer parameters, manages headers, and applies data transformation logic based on input arguments. The generated code processes CSV records, option... | def csv_handler(args):
output_delimiter = args.output_delimiter or args.delimiter
csv_reader_opts = [("delimiter", f"'{args.delimiter}'")]
csv_writer_opts = [("delimiter", f"'{output_delimiter}'")]
if args.csv_opts:
csv_reader_opts.extend(args.csv_opts)
csv_writer_opts.extend(args.csv_op... |
def __reset(self) -> None:
"""
reset the point process
Parameters:
-----------
- None
Returns:
--------
- None
"""
# Initialize the intensity matrix
self.intensity = self.M.copy()
# Intialize the sequence of events for ea... | This code simulates a multi-type point process up to time T by iteratively generating event times using exponential distributions based on intensity functions, updating event types via uniform sampling, and recording jump times in separate arrays. It resets the process, updates intensities dynamically, and constructs t... | def simulate(self) -> None:
"""
Simulate the point process until time T
Parameters:
-----------
- None
Returns:
--------
- None
"""
self.__reset()
s = 0
intensitymax = np.sum(self.intensity)
while s < self.T:
... |
def _check(self):
"""Assers that the device is connected"""
assert self.connected(), 'Not connected'
def has_data(self,timeout=0):
"""Returns True if there is data waiting on the line, otherwise False"""
self._check()
if self.is_usb:
try:
if self.dev.i... | This function reads all available data from a connection, handling both string and byte data types to prevent errors, and returns the aggregated data. It uses a loop to receive data in chunks, ensuring type consistency by encoding the initial data if necessary. | def flush(self,timeout=0,buffer=256):
self._check()
dat = ''
while self.has_data(timeout):
chunk = self.recv(buffer)
# handle the case where we get binary rubbish and prevent TypeError
if isinstance(chunk, bytes) and not isinstance(dat, bytes): dat = da... |
def send(self,cmd):
"""Send command, appending newline if not present"""
if hasattr(cmd,'encode'): cmd = cmd.encode()
if not cmd.endswith(CRLF): cmd += CRLF
self.send_raw(cmd)
def recv_raw(self,size):
"""Receive exactly 'size' bytes"""
self._check()
parts = []
... | This function sends a command to receive a binary response. It checks for errors using a 4-byte header, verifies the data length, and returns the binary data. If an error is detected or the length is incorrect, it raises a RuntimeError. | def ask_bin(self,cmd):
"""Send a request which returns a binary response, returned in Bytes"""
self.send(cmd)
head = self.recv_raw(4)
# is it an error message?
if head == b'ERR:': raise RuntimeError(self.recv().strip())
datalen = unpack('<L',head)[0]
data = self.r... |
def flush(self,timeout=0,buffer=256):
self._check()
dat = ''
while self.has_data(timeout):
chunk = self.recv(buffer)
# handle the case where we get binary rubbish and prevent TypeError
if isinstance(chunk, bytes) and not isinstance(dat, bytes): dat = da... | The main task of the code is to send a command, receive a response, and return it as Unicode. It first flushes pending data, sends the command, and checks if the response starts with 'ERR:', raising a RuntimeError with the error message if so. Otherwise, it returns the stripped response. | def ask(self,cmd):
"""Send followed by receive, returning response in Unicode"""
# check if there's any response waiting on the line
self.flush()
self.send(cmd)
resp = self.recv().strip()
if resp.startswith('ERR:'):
raise RuntimeError(resp[4:].strip())
... |
def connect_sqlite(
database_path: str = env.sqlite_db_path,
) -> tuple[Connection, Cursor]:
"Connect to the SQLite database."
db_connection: Connection = sqlite3.connect(database_path)
db_cursor: Cursor = db_connection.cursor()
# Create SQL tables if they don't exist
db_cursor.execute(
... | The main task of the code is to execute a Delphi method process using an SQLite database and preloaded beliefs data. It connects to the specified database, loads belief weights from a CSV file, and runs the Delphi method for a given topic and number of rounds if the design is set to "delphi". Otherwise, it raises an er... | def main(sqlite_db_path: str, topic: str, rounds: int, beliefs: str, design: str):
"The entry point for the script."
# Connect to the SQLite database
db_connection, db_cursor = connect_sqlite(sqlite_db_path)
# Load beliefs from CSV
names_weights_beliefs: pd.DataFrame = read_names_weights_beliefs(env... |
def is_game_over(board):
if board.score == 10 or board.score == -10:
return True
else:
return False
def generate_states(board):
result = []
if board.cur_player == "w": ## If we wanna move w
temp_board = deepcopy(board)
temp_board.cur_player = "b"
temp_board.parent... | This code implements the minimax algorithm for a game, recursively evaluating all possible future moves. It alternates between maximizing and minimizing players, choosing the optimal next move by comparing scores of child states. The function returns the best score and corresponding board state, handling terminal state... | def minimax(board, depth, max_move):
curboard = deepcopy(board)
is_terminal = is_game_over(board)
if depth == 0 or is_terminal:
return board.score
if board.min_or_max == 1 : ## assume this level is max
child_board = generate_states(board)
##for i in child_board:
## ... |
def head(lst):
return lst[0]
def cons(item, lst):
return [item] + lst
def generateNewStates(currState):
return (generatetop(currState) + generateleft(currState) +
generateright(currState) + generatedown(currState))
def tail(lst):
return lst[1:] | This function performs a depth-limited search in a state space to find a path to a goal state. It recursively explores unexplored states, avoids revisiting nodes via the 'visited' set, and backtracks when exceeding the maximum depth. If the goal is found, it returns the path; otherwise, it continues searching until all... | def statesearch(unexplored, goal, path,visited):
if unexplored == []:
return []
elif goal == head(unexplored):
return cons(goal, path)
elif len(path) > MAX_DEPTH:
path = path[1:] ## if depth is beyond our thought, we will backtrack
return statesearch(generateNewStates(head(pa... |
def is_goal(cur):
if calculate_h(cur) == 1:
for elem in cur[2]:
if elem == 'X':
return True
else:
return False
def print_board(self):
for i in range(len(self)):
for j in range(len(self)):
print(self[i][j], end=' ')
print()
def finish_it... | This code implements a heuristic search algorithm (likely A*) to solve a Rush Hour puzzle. It explores states from a priority queue (`frontier`), checks if a state is the goal, reconstructs and prints the solution path if found, and recursively continues searching. It tracks explored states and total moves, returning `... | def rushhour_blocking_heuristic():
global explored_state
## result = generate_next_states(initial_state)
if frontier.empty():
print("cannot find a solution omg")
## actually it is impossible to run program here though in Python... but I will following algorithms anyway.
else:
## ... |
def evaluate_board(board):
## you won = +10
## enemy won = -10
## else board value = number of your pawns - number of opponent's pawns
num_w = 0
num_b = 0
for row in board.cur_board:
for elem in row:
if elem == "w":
num_w = num_w + 1
elif elem == "... | The code implements a minimax algorithm for Hexapawn, determining the optimal moves for the specified starting player. It initializes a game board, evaluates positions, and recursively explores possible moves to maximize the start player's winning chances within the given number of moves, ultimately printing the result... | def hexapawn(input_board, size, start_player, num_moves): ## start player means we want this player to win
start_board = Board(input_board, start_player, num_moves, size, "w", 1)
start_board.score = evaluate_board(start_board)
a,b = minimax(start_board, num_moves,True)
print_board(b.cur_board)
re... |
def analyze_num_of_trucks(start):
letters = ["X","-"]
for row in start:
for elem in row:
if elem not in letters:
letters.append(elem)
return len(letters)-2
def calculate_h(cur):
if design_button == 0:
## Blocking method, calculate f by simply add the number of... | The code implements a heuristic-based solution for the Rush Hour puzzle. It initializes a state with the given heuristic, determines the number of trucks, adds the initial state to a priority queue (frontier), prints the board, and returns the result of a blocking heuristic function. The global `design_button` stores t... | def rushhour(heuristic, start):
global design_button
design_button = heuristic
num_truck = analyze_num_of_trucks(start)
initial_state = State(0,0,calculate_h(start),start,num_truck,None)
frontier.put((initial_state.f, initial_state))
print_board(start)
return rushhour_blocking_heuristic() |
def get_db_cursor(db_file_name=os.path.join(output_path_data, "ineo.db"), table_name="tools_metadata"):
"""
Get a cursor to the database SQLite3 file which is used to track the changes in the harvested files.
"""
# init db and check if the table exists
conn = init_check_db(db_file_name, table_name)
... | This function tracks changes in JSON files by comparing MD5 hashes between the current and previous batches. It updates a database with file names, hashes, and timestamps, appending new IDs to a list if changes are detected. If no previous batch exists, files are always added. The function maintains a record of changes... | def process_list(ids: list, folder_name, db_file_name, table_name, diff_list, current_timestamp,
previous_batch_dict=None):
"""
This function tracks changes in json files, get a canon file form it, and records those changes in a JSON Lines file, and maintains a record of the changes in a databa... |
def store_solr_response(base_query: str, solr_url: str, username, password, parsed_datasets_directory: str):
"""
Store the list of records from fetch_solr_records into individual JSON files.
"""
"""
Saves individual datasets as separate JSON files
Args:
parsed_datasets_directory (str): Path... | The main task of the code is to download and process Codemeta JSON files and Rich User Content (RUC) from GitHub, compare current and previous data batches using MD5 hashes to identify new/changed entries, and save unique IDs to JSON files. It also includes a placeholder for future deletion logic based on absence thres... | def harvest(threshold: int = 3, debug: bool = False) -> Tuple:
"""
This script downloads the latest Codemeta JSON files and Rich User Content (RUC) from Github,
threshold: int : The number of iterations after which a file is considered absent.
TODO: The threshold is implemented, but need test
"""
... |
def Event_Execute(self, request):
self.clock += 1
self.events.append({"id":request.id, "name":request.interface + "_execute", "clock" : self.clock})
def Propagate_Execute(self, request):
self.clock += 1
self.events.append({"id": request.id, "name": request.interface + "_propagate_execute... | This code processes incoming requests by logging them, performing sanity checks, executing or propagating actions based on the request type and flags, and returning appropriate responses. It handles "query," "deposit," and "withdraw" interfaces, ensuring valid transactions and triggering event responses when necessary. | def HandleRequest(self, request, propagate):
msg = {"id": request.id, "interface": request.interface}
if request.interface != "query":
msg["money"] = request.money
self.recvMsg.append(msg)
response = None
# sanity check
if request.interface != "query"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.