dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def load_from_file(self,fh):
for line in fh:
line = line.rstrip()
if not line:
continue
info=line.split()
if (info[0]=='D'):
for i in range(1,len(info)):
self.Diseases.append(Disease(info[i]))
elif(in... | This code initializes a Bayesian network by loading data from an opened file object, setting up disease, symptom, and exam structures, and preparing probabilistic inference components. It creates a Bayesian network using the loaded data, initializes prior disease probabilities, and prepares nodes for evidence propagati... | def __init__ (self,fh):
# Place here your code to load problem from opened file object fh
# and use probability . BayesNet () to create the Bayesian network .
self.Diseases=list()
self.Symptoms=list()
self.Exams=dict()
self.Measurements=list()
self.propagation_pro... |
def update_points_display(self):
# Method to update the points display.
self.output_text.insert(tk.END, f"Current Points: {self.points}\n")
def update_player_points(self, points, player_name):
sql = "UPDATE player_data SET points = %s WHERE player_name = %s"
print("Updating points for player:... | This method retrieves an "educate person" outcome, displays it in a text widget, awards 10 points, updates the UI points display, saves the new score to PostgreSQL, and triggers a question retrieval. It handles gameplay feedback, scoring, and data persistence in a turn-based system. | def educate_person(self):
outcome = self.current_actions['educate person'] #retrieves the outcome when a player selects"educate person"
self.output_text.insert(tk.END, outcome + "\n") #inserts the outcome into the widget and makes sure the response is printed on an new line.
self.points += 10 #... |
def update_points_display(self):
# Method to update the points display.
self.output_text.insert(tk.END, f"Current Points: {self.points}\n")
def update_player_points(self, points, player_name):
sql = "UPDATE player_data SET points = %s WHERE player_name = %s"
print("Updating points for player:... | The main task of the code is to handle the "ignore person" action in a game or application. It retrieves the corresponding outcome message, displays it in the output text area, adds 5 points to the player's score, updates the points display, and triggers the next question. The function manages scoring, UI updates, and ... | def ignore_person(self):
outcome = self.current_actions['ignore person']
self.output_text.insert(tk.END, outcome + "\n")
self.points += 5 # Add points for ignoring
self.update_points_display() # Update the points display
self.update_player_points(self.points, self.player_name)
... |
def update_points_display(self):
# Method to update the points display.
self.output_text.insert(tk.END, f"Current Points: {self.points}\n")
def update_player_points(self, points, player_name):
sql = "UPDATE player_data SET points = %s WHERE player_name = %s"
print("Updating points for player:... | This function handles a "respond with violence" action in a game or application by inserting the outcome text into a display, adding zero points to the player's score, updating the points display, and triggering the next question without rewarding points for violent responses. | def respond_with_violence(self):
outcome = self.current_actions['respond with violence']
self.output_text.insert(tk.END, outcome + "\n")
self.points += 0 # No points for violence
self.update_points_display() # Update the points display
self.update_player_points(self.points, sel... |
def ask_for_name(self):
return simpledialog.askstring("Player's Name", "Enter your name:")
def insert_player_data(self, player_name, character_name, points):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") #formats date and time into a string
sql = "INSERT INTO player_data (player_name,... | The code resets points, collects and stores a player's name, records the selected character, updates the UI with player info, and triggers the next question retrieval. | def select_character(self, character):
self.points = 0 # Reset points to zero when a new character is selected
player_name = self.ask_for_name()
if player_name:
self.player_name = player_name # Store player name as an instance variable
self.insert_player_data(player_name, character, sel... |
def get_direction(a, b):
"""
Gets a unit vector pointing from b to a
"""
difference = (a[0] - b[0], a[1] - b[1])
length = (difference[0]**2 + difference[1]**2)**0.5
return (difference[0]/length, difference[1]/length)
def angle(a, b):
"""
returns the angle between two unit vectors
"""... | The code approximates the Traveling Salesman Problem (TSP) using a minimum spanning tree (MST), ensuring the solution is no more than twice the optimal length. It constructs a graph from MST edges, traverses it by selecting adjacent points based on directional angles to avoid backtracking, and returns a cleaned path of... | def travelling_salesman_from_edges(points, min_span_edges):
"""
Provides an approximation of the travelling salesman problem
based on the minimum spanning tree. This is guaranteed to be
no more than twice the length of the actual solution.
"""
# graph maps points to a list of adjacent points
... |
def map_to_cylinder(source, output_size):
width, height = source.size
out_width, out_height = output_size
quads = []
prev_y = 0
for y in range(out_height):
bbox = (0, y, out_width, y+1)
new_y = math.asin((y+1)/out_height*2 - 1) / math.pi * height + height/2
quad = (
... | The code transforms an input image into a cylindrical projection, applies color conversion, saves the result as 'transformed.png', converts the image to byte data, encodes it using a 6-bit word scheme, and writes the encoded data to a cartridge file. The process involves resizing, mapping, filtering, color conversion, ... | def main():
WIDTH = int(DIAMETER * math.pi)
HEIGHT = DIAMETER
source = PIL.Image.open(sys.argv[1])
target = map_to_cylinder(source, (WIDTH, HEIGHT))
# target = target.filter(PIL.ImageFilter.GaussianBlur(1))
target = convert_colors(target, COLORS)
target.save('transformed.png')
data = ... |
def hundreds_tens_units(prefix, n:int)->str:
if n == 10:
return 'icumi'
h = n//100
t = (n%100)//10
u = (n%10)
str = ''
if u > 0:
str = units(prefix,u)
if (t>0) or (h>0):
str = (' n\'' if (str[0:1] in vowels) else ' na ') + str
if t > 0:
t_str = te... | This function converts a numerical value into its English word representation, breaking it into trillions, billions, millions, thousands, and hundreds. It adjusts prefixes (e.g., 'mi' to 'i') and appends appropriate connectors ('n\'' or 'na ') based on vowel checks to ensure correct formatting. The result is a concaten... | def rw_spell_number(prefix, n:int)->Union[str,None]:
tr = (n//1000_000_000_000)%1000
bi = (n%1000_000_000_000)//1000_000_000
mi = (n%1000_000_000)//1000_000
th = (n%1000_000)//1000
hu = (n%1000)
if prefix == 'mi':
prefix = 'i'
str = ''
if hu > 0:
hu_str = hundreds_tens_un... |
def down(self):
self.y += 1
self.draw_cursor()
def up(self):
self.y -= 1
self.draw_cursor()
def right(self):
self.x += 1
self.draw_cursor()
def left(self):
self.x -= 1
self.draw_cursor() | This code handles player input for movement and chess moves. It captures keyboard inputs (j/k/l/h) to navigate, records positions (x/c) for moves, and sends moves (m) via an API. The function processes key presses, updates player position, and interacts with a chess board API to execute moves, returning response detail... | def handle_player(self):
from_pos = 0
to_pos = 0
while True :
#with term.cbreak():
val = term.inkey(timeout=1)
info((self.x,self.y))
if val == u"j":
info("down")
self.down()
elif val == u"k":
... |
def setup_robot(objects, springs):
global n_objects, n_springs
n_objects = len(objects)
n_springs = len(springs)
allocate_fields()
print('n_objects=', n_objects, ' n_springs=', n_springs)
for i in range(n_objects):
x[0, i] = objects[i]
for i in range(n_springs):
s = spri... | The code's main task is to either plot and save optimization loss trajectories for different robot configurations (with/without toi) or perform optimization and forward pass with visualization, depending on the 'task' input. It uses pickle to store loss data for analysis. | def main():
setup_robot(*robots[robot_id]())
if task == 'plot':
ret = {}
for toi in [False, True]:
ret[toi] = []
for i in range(5):
losses = optimize(toi=toi, visualize=False)
# losses = gaussian_filter(losses, sigma=3)
pl... |
def _check_file(file_path, ending):
return file_path.endswith(ending) and os.path.isfile(file_path)
def _throw_value_error(information):
raise ValueError(information)
def tokenize_data(self, verse_data):
"""Tokenizes passed in verse data
Uses nltk word_tokenize to tokenize sentences into... | The code initializes a system to process text data using GloVe vectors, either by loading an existing cosine similarity matrix or creating one from scratch. It loads GloVe word embeddings, tokenizes and converts text into vectors, computes a cosine similarity matrix for Bible verses, and saves the matrix as a pickle fi... | def initialize(self, load_matrix=True, matrix_path=None, create_matrix=False):
if create_matrix:
print(' - Loading GloVe File...')
if self._check_file(self.glove_file, '.txt'):
with open(self.glove_file, encoding='utf-8-sig') as f:
for line in list(f.r... |
def _check_file(file_path, ending):
return file_path.endswith(ending) and os.path.isfile(file_path)
def _throw_value_error(information):
raise ValueError(information)
def initialize(self, load_matrix=True, matrix_path=None, create_matrix=False):
if create_matrix:
print(' - Loading Gl... | This code initializes a class by loading Bible verses from a JSON file and setting up a similarity matrix. It checks if the input Bible file is valid, processes verse data, and either generates a test similarity matrix or initializes the matrix using provided parameters. The method handles both testing and production e... | def __init__(self, bible_file, glove_file, matrix_path=None, _testing=False, initialize=True):
self.glove_file = glove_file
self.glove_words = {}
if self._check_file(bible_file, '.json'):
self.bible_data = json.load(
open(bible_file, encoding='utf-8-sig'))
... |
def end_headers(self):
self.send_header("Access-Control-Allow-Origin", self.headers['Origin'])
self.send_header("Access-Control-Allow-Credentials", "true")
self.send_cookie()
super().end_headers()
def handleError(self):
self.send_response(422)
self.send_header("Content-Ty... | This code authenticates a user by parsing email/password from a request, validating them against a database, and setting a session if successful. It reads the request body, checks email existence, verifies the password, and responds with 201/Created on success or error handlers on failure, storing the user ID in sessio... | def handleAuthenticateUser(self):
length = int(self.headers["Content-Length"])
request_body = self.rfile.read(length).decode("utf-8")
print("raw request body: ", request_body)
parsed_body = parse_qs(request_body)
print("Parsed body: ", parsed_body)
user_email = ... |
def handle401(self):
self.send_response(401)
self.end_headers()
def end_headers(self):
self.send_header("Access-Control-Allow-Origin", self.headers['Origin'])
self.send_header("Access-Control-Allow-Credentials", "true")
self.send_cookie()
super().end_headers()
def handleN... | The main task of the code is to retrieve a specific place by ID from the database if the user is authenticated. It checks for user login status, queries the database for the place, returns a JSON response with the place data if found, or triggers a 401 Unauthorized error if unauthenticated and a 404 Not Found error if ... | def handleRetrievePlace(self, place_id):
if "userId" not in self.sessionData:
print("user is not logged in")
self.handle401()
return
db = PlacesDB()
# qurey the db for the place with id place_id
place = db.getOnePlace(place_id)
if pl... |
def handle401(self):
self.send_response(401)
self.end_headers()
def end_headers(self):
self.send_header("Access-Control-Allow-Origin", self.headers['Origin'])
self.send_header("Access-Control-Allow-Credentials", "true")
self.send_cookie()
super().end_headers()
def handleN... | This function updates a user's place information in the database after verifying authentication. It retrieves the existing place data, parses incoming form data, updates the place details, and returns a success response. If the user isn't logged in or the place isn't found, it handles errors accordingly. | def handleUpdatePlace(self, member_id):
if "userId" not in self.sessionData:
print("user is not logged in")
self.handle401()
return
db = PlacesDB()
place = db.getOnePlace(member_id)
if place != None:
length = int(self.headers["C... |
def handle401(self):
self.send_response(401)
self.end_headers()
def end_headers(self):
self.send_header("Access-Control-Allow-Origin", self.headers['Origin'])
self.send_header("Access-Control-Allow-Credentials", "true")
self.send_cookie()
super().end_headers()
def handleN... | This code deletes a place from the database if the user is authenticated. It checks if the place exists, deletes it if found, and returns a 200 response with the place data. If the user isn't logged in or the place isn't found, it returns 401 or 404 errors respectively. | def handleDeletePlace(self, place_id):
if "userId" not in self.sessionData:
print("user is not logged in")
self.handle401()
return
db = PlacesDB()
# query the db for the place with id place_id
place = db.getOnePlace(place_id)
if place != Non... |
def load_session(self):
self.load_cookie()
#check if session ID cookie exists
if "sessionId" in self.cookie:
#load session from session store using session ID
sessionId = self.cookie["sessionId"].value
self.sessionData = SESSION_STORE.getSessionData(sessionId... | This code handles HTTP GET requests by routing based on the URL path. It splits the path to determine the collection (e.g., "places") and optional member ID. If the collection is "places", it retrieves specific or all places depending on the ID. Otherwise, it returns a not-found response. The method uses `handleRetriev... | def do_GET(self):
self.load_session()
# ingredients for an HTTP reponse?
# status code (require), headers (optional), body (optional)
print("the request path is: ", self.path)
parts = self.path.split("/")
collection = parts[1]
if len(parts) > 2 :
memb... |
def load_session(self):
self.load_cookie()
#check if session ID cookie exists
if "sessionId" in self.cookie:
#load session from session store using session ID
sessionId = self.cookie["sessionId"].value
self.sessionData = SESSION_STORE.getSessionData(sessionId... | This code handles POST requests by routing them to specific methods based on the URL path. It loads a session, checks the request path, and invokes corresponding handlers for creating places, users, or authenticating sessions. If the path is unrecognized, it triggers a not-found response. | def do_POST(self):
self.load_session()
print("the post path is: ", self.path)
if self.path== "/places":
self.handleCreatePlace()
elif self.path == "/users":
self.handleCreateUser()
elif self.path == "/sessions":
self.handleAuthenticateUser()... |
def load_session(self):
self.load_cookie()
#check if session ID cookie exists
if "sessionId" in self.cookie:
#load session from session store using session ID
sessionId = self.cookie["sessionId"].value
self.sessionData = SESSION_STORE.getSessionData(sessionId... | This code handles PUT requests by updating a specific 'place' resource if a member ID is provided in the URL path, otherwise returning a 'Not Found' response. It splits the request path to identify the collection ('places') and member ID, then delegates to update or error handling methods. | def do_PUT(self):
self.load_session()
print("the request path is: ", self.path)
parts = self.path.split("/")
collection = parts[1]
if len(parts) > 2 :
member_id = parts[2]
else:
member_id = None
if collection == "places":
if m... |
def load_session(self):
self.load_cookie()
#check if session ID cookie exists
if "sessionId" in self.cookie:
#load session from session store using session ID
sessionId = self.cookie["sessionId"].value
self.sessionData = SESSION_STORE.getSessionData(sessionId... | This code handles HTTP DELETE requests by determining the resource collection (e.g., "places") and member ID from the request path. If the collection is "places" and a valid member ID exists, it deletes the corresponding place using `handleDeletePlace()`. Otherwise, it returns a "Not Found" response via `handleNotFound... | def do_DELETE(self):
self.load_session()
print("the request path is: ", self.path)
parts = self.path.split("/")
collection = parts[1]
if len(parts) > 2 :
member_id = parts[2]
else:
member_id = None
if collection == "places":
i... |
def name_to_path(name):
if not os.path.exists(training_data_directory):
os.makedirs(training_data_directory)
training_data_path = os.path.join(training_data_directory, f'{name}.jsonl')
return training_data_path
def openai_check_finetune(jobname):
if dsp.settings.force_reuse_cached_compilation a... | The main task of the code is to either load an existing OpenAI fine-tuned model from a file or create a new one using `openai_finetune_`, save the result to disk, and return the job name and model. It checks for pre-existing data, avoids redundant processing, and ensures persistence of results for future use. | def openai_finetune(name, target):
print(name)
training_data_path = name_to_path(name)
training_data_path += '.model'
# if path + stuff exists, load the tuple from it
try:
with open(training_data_path) as f:
jobname, ft = ujson.loads(f.readline())
if openai_check_finetu... |
def printStudents(students):
idColumnWidth = max(3, max([len(str(student["studentID"])) for student in students]))
columnWidth = max(16, max([len(student["studentName"]) for student in students] + [len(student["dob"].strftime("%d %B %y")) for student in students]))
row = "{0:<" + str(idColumnWidth) + "... | The code provides a menu-driven interface for managing student records associated with a tutor, allowing users to view, add, remove students, or return to the previous menu. It interacts with a database to fetch, modify, or delete student data based on user selections. | def editStudents(tutor):
while True:
menu = """\n{0} students menu :
1) View students
2) Add students
3) Remove students
4) Up one menu
""".format(tutor)
menuChoice = userInput.chooseFromList(int, menu, [1, 2, 3, 4, 5])
if menuChoice == 1:
cursor.execute("SELECT... |
def get_SP_root(Vq, Eq):
'''
Returns the ID of the central node by finding a node with minimal eccentricity
This node will be the SP-tree root
O(V)
'''
central_node = (None, float('inf'))
for v in Vq.values():
node = v
ecc = eccentricity(node, Eq)
if ecc < central_n... | The function constructs a tree structure based on the input type. For 'SP', it generates a tree rooted at a specific node. For 'MinMsg', it evaluates multiple possible trees starting from each vertex, estimates message cardinality for each, and returns the tree with the minimal expected message count, optimizing for ef... | def get_tree(type, Vq, Eq, adj_in, adj_out, stat_v, stat_e, stat_joins):
if type == 'SP':
u_r = get_SP_root(Vq, Eq)
tree, vidMap, eidMap = generateTree_BFS(u_r, Vq, Eq, adj_in, adj_out, stat_v, stat_e, stat_joins)
return tree
elif type == 'MinMsg':
src_out_stats, trg_in_stats, e... |
def setObs(self, lcobs):
self.lcobs = lcobs
self.name = self.lcobs.objId.unique()[0]
self.outlier_rejection()
self.filterlist = self.lcobs.fid.unique()
self.nobs = len(self.lcobs)
self.nnights = len(self.lcobs.night.unique())
gobs = self.lcobs.query('fid == 1')
... | This code processes light curve observations by fitting a model, generating corrected photometry plots, phased light curves, and optionally periodograms if 'long' is True. It returns a dictionary of visualizations for analysis. | def __call__(self, lcobs, photoffsets=None, outfile=None, long=False):
self.setObs(lcobs)
self.photoffsets = photoffsets
self.fit_model()
figs = {}
figs['corrphot'] = self.vis_corr_photometry()
figs['phased'] = self.plot_phased()
if long:
self.print_to... |
def efactors(n):
def f(x):
return x**2 + 1
x = randint(0, n)
y = x
d = 1
while d == 1:
x = f(x) % n
y = f(f(y)) % n
d = gcd(abs(x-y), n)
return d
def invm(m, a):
g, x, _ = gcde(a, m)
if g != 1:
raise Exception(f'Inverse of {a} modulo {m} does no... | The function `ecrack` decrypts an RSA ciphertext `c` using the public key `(n, e)` by first factoring `n` into primes `p` and `q`, computing Euler's totient function φ(n) = (p-1)*(q-1), finding the modular inverse `d` of `e` modulo φ(n), and finally decrypting `c` with the private key `(n, d)` via the `rsaDec` function... | def ecrack(n, e, c):
p = efactors(n)
q = n // p
d = invm((p - 1) * (q - 1), e)
return rsaDec(n, d, c) |
def prime(d):
p = randint(1 << (d - 1), 1 << d)
while not fermat(p, 100):
p = randint(1 << (d - 1), 1 << d)
return p
def randint(n, m):
if n >= m:
raise Exception('n must be smaller than m')
rand = randbelow(m)
while rand < n:
rand = randbelow(m)
return rand
def gc... | The code generates RSA cryptographic keys by selecting two distinct primes p and q of size approximately s/2, computing modulus n = p*q, Euler's totient φ(n), choosing a public exponent e coprime to φ(n), and determining the private exponent d as the modular inverse of e. It returns the public key (n, e) and private ke... | def rsaKey(s):
p = prime(s // 2)
q = prime(s // 2)
while q == p:
q = prime(s // 2)
n = p * q
phi_n = (p - 1) * (q - 1)
e = randint(2, phi_n)
while gcd(e, phi_n) != 1:
e = randint(2, phi_n)
d = invm(phi_n, e)
return (n, e, d) |
def egKey(s):
p, a = pair(s)
x = randbelow(p - 1)
while x < 1:
x = randbelow(p - 1)
y = expm(p, a, x)
return (p, a, x, y)
def egEnc(p, a, y, m):
if m < 0 or m >= p:
raise Exception('m is outside range: 0 <= m < p')
k = randbelow(p - 1)
while k < 1:
k = randbelow... | The main task of the code is to demonstrate ElGamal encryption and decryption. It generates keys using `egKey`, encrypts a message `m` with `egEnc`, and decrypts the ciphertext with `egDec`, printing the original message, encrypted values, and decrypted result to verify correctness. | def main():
m = 50
p, a, x, y = egKey(100)
print(f'message: {m}')
c1, c2 = egEnc(p, a, y, m)
print(f'encrypt: c1 {c1}, c2 {c2}')
print("decrypt: ", egDec(p, x, c1, c2)) |
def rsaKey(s):
p = prime(s // 2)
q = prime(s // 2)
while q == p:
q = prime(s // 2)
n = p * q
phi_n = (p - 1) * (q - 1)
e = randint(2, phi_n)
while gcd(e, phi_n) != 1:
e = randint(2, phi_n)
d = invm(phi_n, e)
return (n, e, d)
def rsaEnc(n, e, m):
return expm(n,... | The code demonstrates RSA encryption and decryption. It sets parameters (message `m`, modulus length `s`), generates RSA keys (n, e, d), encrypts the message, and decrypts the ciphertext, printing results. The task verifies RSA functionality with key generation, encryption, and decryption steps. | def main():
# Increase recursion limit if needed.
sys.setrecursionlimit(2000)
print('Max word size:', sys.maxsize, 'bits.')
print('Recursion limit', sys.getrecursionlimit())
m = 27
s = 2000
print('Message:', m, 'Modulus length:', s)
n, e, d = rsaKey(s)
print('Modulus:', n, '\nExpo... |
def YoutubeLookup():
global youtubeID
name = str(sys.argv[1])
print(name)
url = "https://youtube-v2.p.rapidapi.com/search/"
querystring = {"query": name, "lang": "en", "country": "us"}
headers = {
"X-RapidAPI-Key": "KEY",
"X-RapidAPI-Host": "youtube-v2.p.rapidapi.com"
}
... | The main task of the code is to search for a YouTube video using `YoutubeLookup()`, convert it with `YoutubeConvert()`, and then play the converted video using `play()`. This sequence automates the process of finding, converting, and playing a YouTube video. | def main():
YoutubeLookup()
YoutubeConvert()
play() |
def is_surrounded(self, snake):
# izdvajanje zmija iz drugih timova
other_teams = []
# kom ce timu pripadati , koji su opkolili
u_teams = []
for s in self.snakes:
if s.Team != snake.Team:
other_teams.append(s)
first_pos = False
secon... | The function processes incoming game moves by receiving client data, updating snake direction, checking if a snake is surrounded, removing/adding snakes accordingly, moving snakes, handling food/surprise effects, checking deaths, and determining game over if only one team remains. | def process_received_move(self):
while True:
received = self.net.client.recv(2048).decode()
snake = self.snakes[self.TurnCounter]
temp = received.split(";")
snake.Direction = int(temp[0])
print(int(temp[0]))
cant_move, new_team = self.is_s... |
def is_surrounded(self, snake):
# izdvajanje zmija iz drugih timova
other_teams = []
# kom ce timu pripadati , koji su opkolili
u_teams = []
for s in self.snakes:
if s.Team != snake.Team:
other_teams.append(s)
first_pos = False
secon... | This code handles key press events to control a snake's movement in a multiplayer game, checks if the snake is surrounded to trigger removal and replacement, updates direction based on input, moves the snake, checks for food collisions, and sends game state data over the network. | def keyPressEvent(self, event):
if not self.GAME_OVER:
snake = self.snakes[self.TurnCounter]
if snake.Team != int(self.net.id):
return
cant_move, new_team = self.is_surrounded(snake) # poziva logiku opkoljivanja
if cant_move:
prin... |
def is_surrounded(self, snake):
# izdvajanje zmija iz drugih timova
other_teams = []
# kom ce timu pripadati , koji su opkolili
u_teams = []
for s in self.snakes:
if s.Team != snake.Team:
other_teams.append(s)
first_pos = False
secon... | This function handles a snake's timeout logic by checking if it's surrounded. If surrounded, the snake is removed, and a new one is added for the team that trapped it. It then moves the snake, checks for food collisions, handles deaths, and triggers game over if only one team remains. | def timeout(self):
snake = self.snakes[self.TurnCounter]
# if snake.Team == self.net.id:
cant_move, new_team = self.is_surrounded(snake) # poziva logiku opkoljivanja
if cant_move:
self.snakes.remove(snake) # brisemo tu zmiju
print("tim koji je opkolio: " + str(n... |
def square_height(self):
return self.contentsRect().height() / Board.HEIGHTINBLOCKS
def draw_square(self, painter, x, y, color):
# color
# color = QColor(0x228B22)
# painting rectangle
painter.fillRect(x + 1, y + 1, self.square_width() - 2,
self.square_h... | This code handles the painting of game elements in a Qt application, rendering snakes (with team-specific colors and head highlights), food, walls, and special effects. It uses QPainter to draw each component based on their positions, ensuring visual representation of the game state during the paint event. | def paintEvent(self, event):
# creating painter object
painter = QPainter(self)
# getting rectangle
rect = self.contentsRect()
# board top
boardtop = rect.bottom() - Board.HEIGHTINBLOCKS * self.square_height()
# drawing snake
for snake in self.snakes:
... |
def Network_firing_rates(Network_Output,duration):
PC_monitor_t=Network_Output["PC_output_t"]
PC_monitor_i=Network_Output["PC_output_i"]
PV_monitor_t=Network_Output["PV_output_t"]
PV_monitor_i=Network_Output["PV_output_i"]
SST_monitor_t=Network_Output["SST_output_t"]
SST_monitor_i=Network_Output... | This function computes and prints statistical measures of neuronal activity from a network simulation, including average/max firing rates, coefficient of variation squared (CV²), and synchrony values for three populations (PC, PV, SST). It uses input data and configuration parameters to calculate these metrics and outp... | def give_stats(Network_Output,main_conf):
import warnings
warnings.filterwarnings("ignore")
[Max_fr,Ave_fr]=Network_firing_rates(Network_Output,main_conf['simulation_duration'])
[PC_CV_average,PV_CV_average,SST_CV_average]=cv_squared(Network_Output)
[PC_synchrony,PV_synchrony,SST_synchrony]=network_... |
def get_user_rooms(user_id: str, org_id: str):
"""
A utility function that retrieves all the rooms linked to a user from the dm_rooms collection
Args:
collection: dm_rooms
user_id (str): a unique identifier used as a query param to filter the collection
org_id (str): uniquely identif... | The function `sidebar_emitter` structures and returns sidebar data for a user's organization, including joined rooms and starred rooms. It fetches user rooms, filters starred rooms, and constructs a dictionary with plugin-specific details like event type, plugin ID, and room data for display in a sidebar interface. | def sidebar_emitter(org_id:str, member_id:str, group_room_name:str = None) -> dict:
"""Function structures data for the sidebar
Args:
org_id(str): org used to extract data
member_id(str): id of user logged in
Returns:
A dict mapping keys to the data fetched. Example
... |
def _create_folder_params(self, path, name):
params = {"name": name, "path": path}
return params
def _create_upload_api_params(self, path: str, filename) -> Dict:
params = {
"appname": "explorer",
"path": path,
"offset": 0,
}
return params
def ... | This function uploads a file to Filecloud, creates a target folder (or "Failed" if marked), and attaches metadata from KVP. It handles ZIP-extracted PDFs, checks upload status, and logs success/failure. Metadata is added via separate calls if KVP data exists. | def upload_file(
self,
filename,
file_data: zipfile.ZipExtFile,
kvp: List[Dict] | None,
is_failed: bool = False,
):
"""
Upload file to Filecloud and add metadata based on KVP
Parameters
----------
filename
filename ... |
def addComboRow(self, txt, actionsList, layout):
elms = [ self.addLabel(txt), self.addComboBox(actionsList) ]
layout.addRow( elms[0], elms[1] )
return elms
def menuAddSections( self, layout, isSubMenu=False ):
row = 1 if isSubMenu else 0
sectionsCountTxt = layout.itemAt(row, QFormLayout.FieldRo... | This code initializes a GUI settings interface for configuring a pie menu system. It creates a scrollable form with a section selector, default menu entries, and a save button. The layout manages dynamic submenu creation, action bindings, and settings persistence, allowing users to customize pie menu sections and assoc... | def __init__(self, actionsList, parent=None):
super(Settings, self).__init__(parent)
self.setGeometry(0, 0, 300, 500)
self.setMinimumSize(400, 500)
self.setWindowTitle("Pie Menu Settings")
self.submenuLeftMargin = 20
# Main layout, contains only QScrollArea
self.base = QVBoxLayout()
... |
def addLabel(self, label):
label = QLabel( str(label) )
label.setStyleSheet( "QLabel {font-size: 12px;}" )
return label
def addComboRow(self, txt, actionsList, layout):
elms = [ self.addLabel(txt), self.addComboBox(actionsList) ]
layout.addRow( elms[0], elms[1] )
return elms
def menuAddSections(... | This code adds a submenu section to a form layout when `val` is 2. It creates a `QGroupBox` with a `QFormLayout`, adds a label, combo box (linked to section updates), and a line. The group is inserted at a calculated position in the form. If `val` is not 2, it removes the next row. The combo box triggers `menuAddSectio... | def addSubMenu( self, val ):
index = self.sender().sectionIndex
pos = self.settingsFormLayout.getWidgetPosition(self.sender())
if val != 2:
self.settingsFormLayout.removeRow(pos[0] + 1)
else:
subMenu = QGroupBox()
subMenuLayout = QFormLayout()
subMenuLayout.setAl... |
def initUI(self):
self.layout = QVBoxLayout()
self.titleLabel = QLabel(f"Monitoring device: {self.mac_address}", self)
self.layout.addWidget(self.titleLabel)
self.grillTempLabel = QLabel("Grill Temp: Loading...", self)
self.layout.addWidget(self.grillTempLabel)
self.set... | This code initializes a class with MAC address, user, and database attributes, sets up data lists for plotting, initializes the UI, loads MAC addresses, updates data, and dynamically adds a new MAC address to the list if not present, ensuring the UI reflects changes. | def __init__(self, mac_address, user, db):
super().__init__()
self.mac_address = mac_address
self.user = user
self.db = db
# Initialize data lists for plotting
self.x_data = []
self.y_data = []
self.initUI() # Initialize the UI before ... |
def extract_sensor_data(self, idxstrt, idxstp, check_lick=True, filter=False):
""" Function to extract probability thresholded sensor data from ReachMaster. Data has the option for it to be
coarsely filtered.
"""
self.k_length = self.kinematic_block[self.kinematic_block.columns[3:6]].va... | This function segments and filters kinematic data from body parts (nose, limbs, digits) using normalized coordinates and probability thresholds. It extracts positions, applies preprocessing, computes principal components for motion analysis, and calculates endpoint errors to analyze movement accuracy and variability in... | def segment_and_filter_kinematic_block(self, cl1, cl2, coarse_threshold=0.3, preprocess=True):
""" Function to segment, filter, and interpolate positional data across all bodyparts,
using start and stop indices across
whole-trial kinematics. """
self.k_length = self.kinematic_block[... |
def total_reward_zone_trips(self):
""" Function to calculate the number of trips to a reward zone location within a trial block.
"""
self.reward_zone_sensor = np.asarray(self.block_exp_df['RW'].values[0])
self.total_rewarded_trials = find_peaks(self.reward_zone_sensor, height=1, distance... | This method processes trial data by segmenting kinematic and sensor data, handling missing stop times with defaults, and compiling results into a concatenated DataFrame for all trials. It initializes trial parameters, filters data blocks, extracts relevant information, and aggregates trial-specific data into a single s... | def get_preprocessed_trial_blocks(self):
self.total_reward_zone_trips()
self.calculate_number_of_speed_peaks_in_block()
for ix, sts in enumerate(self.trial_start_vectors):
self.trial_index = sts - 50
try:
stp = self.trial_stop_vectors[ix]
i... |
def total_reward_zone_trips(self):
""" Function to calculate the number of trips to a reward zone location within a trial block.
"""
self.reward_zone_sensor = np.asarray(self.block_exp_df['RW'].values[0])
self.total_rewarded_trials = find_peaks(self.reward_zone_sensor, height=1, distance... | The function processes experimental data to generate a dataframe summarizing reaching behavior. It segments kinematic and sensor data per trial, classifies trial types (successful, tug-of-war, unsuccessful), handles edge cases, and compiles results into a concatenated pandas DataFrame. Outlier detection and CSV output ... | def get_reach_dataframe_from_block(self):
""" Function that obtains a trialized (based on reaching start times)
pandas dataframe for a provided experimental session. """
self.total_speeds = []
self.left_hand_speeds = []
self.right_hand_speeds = []
self.left_hand_raw_s... |
def findRecord(self,input_ID: str):
"""
Updates the self.record and the self.found_loc variable.
Args:
input_ID (str): name of the company
Returns:
_type_: _description_
"""
# check for the binary search, if data found return pointer
... | The main task of the code is to delete a database record by locating it via `findRecord`, overwriting it with default (empty) values while retaining the primary key name to maintain binary search integrity, and returning `True` if successful. It ensures the database is open, calculates the record's position, and writes... | def deleteRecord(self,name):
"""
if db is open, it uses findRecord to locate the record. It then uses writeRecord to overwrite it with default (empty) values. Keeps the name the same though, otherwise binarySearch will break.
Args:
name(str): primary key for the database to find the ... |
def get_event(event_path):
'''loads the event json as a dict'''
event_filename = os.path.basename(event_path)
event_ds_path = os.path.join(event_path, event_filename + '.dataset.json')
event_met_path = os.path.join(event_path, event_filename + '.met.json')
cwd = os.getcwd()
event_object = {}
... | The main task of the code is to process an event by applying depth, magnitude, alert level, and polygon filters. If the event passes, it calculates displacement tracks, generates AOI parameters with specified time frames, and submits AOI creation jobs for long-term analysis. The function also handles dynamic thresholds... | def main(event_path, depth_filter=None, mag_filter=None, alertlevel_filter=None, polygon_filter=None, slack_notification=None, water_filter=False, dynamic_threshold=False, create_aoi_version='master', days_pre_event=30, days_post_event=30, distance_from_land=50):
'''runs the filters on the input event. If it passes... |
def _are_db_relations_ready(self) -> bool:
"""Check if the needed database relations are established.
Returns:
If the needed relations have been established.
"""
# mypy fails do detect this stored value can be False
if not self._stored.db_name: # type: ignore
... | The main task of this code is to configure a Kubernetes pod using Pebble based on application configuration, ensuring database readiness and container connectivity. It executes a setup script if the configuration is valid, the unit is a leader, or S3 parameters have changed. It then applies the updated configuration la... | def _config_changed(self, event: HookEvent) -> None:
"""Configure pod using pebble and layer generated from config.
Args:
event: Event triggering the handler.
"""
self.model.unit.status = MaintenanceStatus("Configuring service")
if not self._are_db_relations_ready():... |
def get_ftp_path_list(self, category='standard', product='hourly', list_version=None, start_datetime=None,
end_datetime=None, ext=HDF_EXT):
# download from FTP to local
# if 'ftp' not in globals():
# ftp = FTP(self.ftp_address, user=self.user, passwd='anonymous')
... | The main task of the code is to retrieve raster data from an FTP server based on specified parameters (category, product, date range), process it into GeoTIFF format, and optionally save it locally or to S3. It handles parallel downloads, coordinate-based data extraction, directory management, and supports filtering ba... | def get_raster_data(self, category='standard', product='hourly', list_version=None, start_datetime=None,
end_datetime=None, ext=HDF_EXT, convert_to_gtiff=True,
list_band_filter=['//Grid/monthlyPrecipRate'],
pick_part=True,
x... |
def update_mini_batch(self, mini_batch, eta):
# Updates weights and biases using SGD and backpropagation for each mini batch
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x, y in mini_batch:
# Calculate gradient in... | (The main task of the code is to implement Stochastic Gradient Descent (SGD) for training a neural network. It iterates over epochs, splits training data into mini-batches, updates weights using `update_mini_batch`, and evaluates performance via MSE and test accuracy. Training halts early if the error drops below a thr... | def SGD(self, training_data, epochs, mini_batch_size, eta,
error_target=0.001, test_data=None):
if test_data: n_test = len(test_data)
n = len(training_data)
for j in range(epochs):
time1 = time.time()
random.shuffle(training_data)
mini_batches = [... |
def _create_cells(self) -> None:
self._cells = []
for x in range(self._num_cols):
column = []
for y in range(self._num_rows):
cell_top_left = Point(
x=self._x1 + x * self._cell_size_x,
y=self._y1 + y * self._cell_size_y,
... | This code initializes a maze structure by creating a grid of cells, setting up entrance/exit points, breaking walls recursively to generate paths, and resetting cell visitation status. It uses parameters like grid dimensions, cell sizes, and a random seed to configure the maze, preparing it for traversal or visualizati... | def __init__(
self,
x1: int,
y1: int,
num_rows: int,
num_cols: int,
cell_size_x: int,
cell_size_y: int,
win: Optional[Window] = None,
seed: Optional[int] = None,
) -> None:
self._cells: List[List[Cell]] = []
self._x1 = x1
... |
def get_credentials_from_file():
file_name = '../config.ini'
config = ConfigParser()
config.read(file_name)
account_section_name = config.sections()[0] #the name of the section can be any name
account_list = list(config[account_section_name])
user = config[account_section_name][account_list[0]... | The code automates Facebook login and posts content to specified groups. It retrieves credentials, initializes a Chrome driver, navigates to Facebook, logs in, reads group lists from files, merges them, and uses `post_to_groups` to publish content to the combined groups. The script closes the browser afterward. | def post():
user, pwd = get_credentials_from_file()
options = define_chrome_options()
driver = webdriver.Chrome("../chromedriver.exe", options=options)
with driver:
driver.maximize_window()
driver.get("http://www.facebook.com")
# time.sleep(3)
login(driver, pwd, user)
... |
def login(self) -> None:
"""Ask for credentials and send login request to the server."""
self.request_credentials()
self.server.connect(self.server_address)
self.send_login_message()
def await_incoming_messages(self) -> None:
"""Creates a thread to display any incoming encrypted messages."""
thr... | The code's main task is to establish a server connection by logging in the user and managing bidirectional message communication, handling both incoming and outgoing messages asynchronously. | def connect_to_server(self) -> None:
"""Logs user in to the server and transmits incoming/outbound messages."""
self.login()
self.await_incoming_messages()
self.await_outgoing_messages() |
def get_search_books(title_keyword):
index_pos = 1
results = pull_api(title_keyword)
for x in range(5):
try:
title = results['items'][x]['volumeInfo']['title']
except:
title = 'NA'
try:
author = results['items'][x]['volumeInfo']['authors']
except:
author = 'NA'
try:
... | The code provides a menu-driven interface for managing a reading list, allowing users to search for books, save selected titles to a list, view saved books, or exit. It repeatedly displays options, processes user input, and interacts with functions to retrieve search results, save entries, and display the reading list. | def run():
while True:
print(f""" Create A Reading List
____________________________________________________
press 1: ONLY BROWSE
press 2: BROWSE and SAVE TO READING LIST
Press 3: VIEW READING LIST
Press 4: EXIT
__________________________________________... |
def create_proxy_pool(self):
if PROXY_POOL:
proxy_pool = PROXY_POOL.split(',')
for proxy in proxy_pool:
ip, port, un, password = proxy.split(':')
address = 'http://{}:{}'.format(ip, port)
self.proxy_pool.append((address, un, password))
def ... | The code initializes a spider by validating required parameters, setting up API and parser components, processing event/venue IDs, fetching venue data, retrieving city configurations, and creating authentication sessions with a callback. It ensures proper setup for scraping events and venues while handling dependencies... | def init(self, callback):
if not hasattr(self, 'page_slug'):
raise Exception('page_slug is a required spider argument')
if hasattr(self, 'event_ids') and not hasattr(self, 'venue_id'):
raise Exception('venue_id is required if event_ids is set')
self.ng_api = NgAPI(logger... |
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank... | This function implements Kruskal's algorithm to find a Minimum Spanning Tree (MST) of a graph. It sorts edges by weight, uses Union-Find to detect cycles, and selects edges connecting disjoint sets until the MST contains all vertices. The result is a list of edges forming the MST. | def kruskalMST(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.g... |
def get_results(postal_code4: Literal[1000, 9999], km_radius: Literal[1,2,5,10,15,30,50,100,None]=1, publication_date: Literal["now-1d","now-3d", "now-5d", "now-10d", "now-30d", "no_preference"] ="no_preference" , offering_type: Literal["buy", "rent", "all"]="all", start_index: int=0, page_size: int=100):
base_url ... | The code retrieves real estate listings from Funda based on postal code, radius, and date parameters, processes the results, and stores them in a PostgreSQL database. It uses pagination to handle large datasets, fetching 100 entries at a time with a 5-second delay between requests, while dynamically updating the total ... | def cli():
global CONNECTION
CONNECTION = utils.get_database_connection(
db_name="funda",
db_user=os.environ.get("USER"),
db_password=os.environ.get("PASSWORD"),
db_host=os.environ.get("HOST")
)
utils.db_setup("funda", funda_schema, CONNECTION)
parser = argparse.A... |
def last_block(self):
return self.chain[-1]
def proof_of_work(self, block):
"""
Function that tries different values of nonce to get a hash
that satisfies our difficulty criteria.
"""
block.nonce = 0
computed_hash = block.compute_hash()
while not computed... | The main task of the code is to add pending transactions to the blockchain by creating a new block, performing Proof of Work, validating the block's index, and updating the blockchain state. It checks for sufficient power, constructs the block with transactions and metadata, computes the proof, verifies the index seque... | def mine(self, owner, index):
"""
This function serves as an interface to add the pending
transactions to the blockchain by adding them to the block
and figuring out Proof Of Work.
"""
if not self.unconfirmed_transactions and self.power < 10:
if self... |
def writerr(text=''):
# Only send text to stdout if the tool isn't piped to pass output to something else,
# or If the tool has been piped to output the send to stderr
if sys.stdout.isatty():
sys.stdout.write(text+'\n')
else:
sys.stderr.write(text+'\n')
def dictToParams(params: dict) ->... | The main task of the code is to process and output URLs by replacing specific regex patterns in paths with predefined values, then writing the normalized URLs (with or without parameters) to a specified file or STDOUT. It tracks input/output line counts, handles errors, and provides feedback on data reduction. | def processOutput():
global linesFinalCount, linesOrigCount, patternsGUID, patternsInt, patternsCustomID, patternsLang
try:
# If an output file was specified, open it
if args.output is not None:
try:
outFile = open(os.path.expanduser(args.output), 'w')
exc... |
def paramsToDict(params: str) -> list:
'''
converts query string to dict
'''
try:
the_dict = {}
if params:
for pair in params.split('&'):
# If there is a parameter but no = then add a value of {EMPTY}
if pair.find('=') < 0:
... | This code processes URLs by normalizing their host, path, and parameters, filtering out unwanted content, and mapping them into a structured dictionary (urlmap) that groups URLs by host and patterns, avoiding duplicates based on parameters. It handles edge cases like port removal, fragment inclusion, and error logging. | def processUrl(line):
try:
parsed = urlparse(line.strip())
# Set the host
scheme = parsed.scheme
if scheme == '':
host = parsed.netloc
else:
host = scheme + '://' + parsed.netloc
# If the link specifies port 80 or 443... |
def processUrl(line):
try:
parsed = urlparse(line.strip())
# Set the host
scheme = parsed.scheme
if scheme == '':
host = parsed.netloc
else:
host = scheme + '://' + parsed.netloc
# If the link specifies port 80 or 443... | The main task of the code is to process input (from stdin or a file) by detecting encoding, reading lines, counting them, and passing each line through `processLine` and `processUrl` functions. It handles errors during input reading and encoding detection, logging issues with colored error messages. The global variable... | def processInput():
global linesOrigCount
try:
if not sys.stdin.isatty():
for line in sys.stdin:
processUrl(processLine(line))
else:
with open(os.path.expanduser(args.input), 'rb') as f:
result = chardet.detect(f.read()) # or readline if t... |
def writerr(text=''):
# Only send text to stdout if the tool isn't piped to pass output to something else,
# or If the tool has been piped to output the send to stderr
if sys.stdout.isatty():
sys.stdout.write(text+'\n')
else:
sys.stderr.write(text+'\n')
def getConfig():
'''
Try ... | The main task of the code is to de-clutter a list of URLs by parsing command-line arguments, applying filter rules (e.g., excluding keywords, extensions, or specific patterns), and processing input URLs (from file or stdin) to remove duplicates or irrelevant entries based on configurable parameters. It outputs the clea... | def main():
global args, urlmap, patternsSeen, patternsInt, patternsCustomID, patternsGUID, patternsLang
# Tell Python to run the handler() function when SIGINT is received
signal(SIGINT, handler)
# Parse command line arguments
parser = argparse.ArgumentParser(
description='ur... |
def _query_add(self, target: str, user: User) -> None:
if target == "message":
details: Tuple[str, str, int] = self._new_message_details()
# attempt to create a new message in the specified group.
# deal with the exceptions appropriately
try:
self... | This function processes user queries by splitting the input, checking the first keyword (ADD/REMOVE/GET/HELP), and delegating to corresponding methods like _query_add or _query_get, passing relevant parameters and the user object for handling. | def _det_query(self, query: str, user: User) -> None:
query = query.split()
# feed the valid query to the proper handling function
if query[0].upper() == "ADD":
self._query_add(query[1].lower(), user)
elif query[0].upper() == "REMOVE":
self._query_remove(query[... |
def handle_waiting_room_page(self, ele_verbose=3, attr_verbose=1):
# i, tries = 0, 6
# while self.is_wait_host_page() and i < tries:
t0 = time.time()
wait_duration = self.zoom_meeting_duration_min
is_waiting = self.is_wait_host_page(ele_verbose, attr_verbose)
while is_wai... | This code handles waiting room logic in a meeting application. It checks for waiting room status, manages "Removed by Host" popups, handles recording notifications, and disconnects audio. The function returns a boolean indicating if the user remains in the waiting room, while also managing UI elements and timing with c... | def handle_waiting_room(self, ele_verbose=3, attr_verbose=1, verbose=0, always_print_checking=False):
# add support for: please wait host will let you in soon
self.custom_wait(3)
waiting_room = self.handle_waiting_room_page(ele_verbose, attr_verbose)
# add support for: Removed by Host
... |
def handle_passcode(self):
enter_passcode = self.enter_passcode()
if enter_passcode:
self.action_with_web_driver_wait(By.ID, ZOOM_JOIN_BTN_ID)
self.custom_wait(3)
err_element, _ = self.get_element_and_attribute(By.XPATH, ZOOM_INVALID_PASS_XPATH, 'passcode_invalid', ''... | The code automates joining a Zoom meeting via a browser by opening the link, handling CAPTCHA, inputting user details, and managing errors like invalid links, unstarted meetings, or removal by the host. It captures screenshots at key steps, checks browser compatibility, and retries joining if the meeting isn't started,... | def join_meeting_link(self, url, is_opened=False):
if not is_opened:
self.open_url(url)
self.custom_wait()
self.capture_ss(ss_name='zoom_meeting_link.png', force=SS_FORCE)
self.custom_wait()
# press escape to avoid popup of zoom
pag.press('esc')
try:
... |
def handle_passcode(self):
enter_passcode = self.enter_passcode()
if enter_passcode:
self.action_with_web_driver_wait(By.ID, ZOOM_JOIN_BTN_ID)
self.custom_wait(3)
err_element, _ = self.get_element_and_attribute(By.XPATH, ZOOM_INVALID_PASS_XPATH, 'passcode_invalid', ''... | The main task of the code is to join a Zoom meeting by entering a meeting ID, check if registration is required, handle basic registration or passcode if needed, and then join the meeting via the generated link. It includes error handling, screenshot captures, and conditional logic based on registration requirements. | def join_meeting_id(self, register=True):
self.open_url(ZOOM_MEETING_URL)
self.custom_wait()
try:
print("Entering Zoom Meeting ID!")
self.action_with_web_driver_wait(By.ID, ZOOM_INPUT_MEETING_ID, action='keys', keys=self.zoom_meeting_id)
self.capture_ss(ss_nam... |
def join_meeting_link(self, url, is_opened=False):
if not is_opened:
self.open_url(url)
self.custom_wait()
self.capture_ss(ss_name='zoom_meeting_link.png', force=SS_FORCE)
self.custom_wait()
# press escape to avoid popup of zoom
pag.press('esc')
try:
... | The code automates attending a Zoom meeting by joining via URL or ID, capturing attendance halfway through, monitoring for host removal or meeting end, and logging duration. It handles errors, waits for specified intervals, and exits the meeting upon completion or interruption, returning success/failure status. | def start_bot(self):
try:
is_joined, attendance_taken = False, False
if self.zoom_meeting_url:
is_joined = self.join_meeting_link(self.zoom_meeting_url)
elif is_joined is not None and not is_joined and self.zoom_meeting_id:
is_joined = self.joi... |
def userOpt(question):
posOpt = posOpt = ["y", "yes", "true"]
return str(input("\n"+question)).lower() in posOpt
def predForm(predArr, allMent):
token = [[] for i in range(len(predArr))]
label = [[] for i in range(len(predArr))]
for i in range(len(predArr)):
for dic in predArr[i]:
for k, v in dic.i... | The code performs named entity recognition (NER) to extract antibody (AB) and/or antigen (AG) names from scientific abstracts. It prompts the user to select entities (AB, AG, or both), whether to list all mentions or unique names, and GPU usage. It processes input IDs, loads a pre-trained model, predicts entities, and ... | def nerOutput(ab_id):
posOpt = ["y", "yes", "true"]
#Ask for user's output options
abagOpt = str(input('''\nPlease choose the entity/entities for NER:
Type 1 for AB only
Type 2 for AG only
Type 3 for both AB and AG
Enter a number (1, 2, or 3): '''))
while abagOpt not in ["1", "2", "3"]:
a... |
def gf_poly_mul(p1, p2, field):
"""
Multiply two polynomials in the Galois Field of characteristic 2.
"""
m = len(p1)
n = len(p2)
result = np.zeros(m + n - 1, dtype=int)
for i in range(m):
for j in range(n):
result[i+j] ^= gf_mul(p1[i], p2[j], field)
return result.tol... | The code decodes a binary BCH code with t-error correction capability by calculating syndromes, determining error positions via polynomials, and correcting errors in the codeword. It returns the original message if no errors are detected or after fixing up to t errors, otherwise raises an exception for uncorrectable er... | def bch_decode(codeword, t):
"""
Decode binary data using a BCH code with t-error correction capability.
"""
n = 2**t - 1
k = n - t
field = ffield.FField(t)
gen = [1] # generator polynomial
# calculate generator polynomial using roots of unity
for i in range(1, 2*t):
root = ... |
def get_norm_coord(self, P):
vec = self.p_(P)
xs_norm = vec[0] / self.hx
ys_norm = vec[1] / self.hy
return np.array([xs_norm, ys_norm])
def get_screen_x_coord(self, xs, width):
return np.floor(((xs + 1) / 2) * width + 0.5)
def get_screen_y_coord(self, ys, height):
return ... | The code converts normalized coordinates of a point P to screen coordinates based on given width and height by first normalizing P, then mapping its x and y components to pixel positions using separate functions, finally returning the result as an integer array. | def get_screen_coord(self, P, width, height):
P_ = self.get_norm_coord(P)
i = self.get_screen_x_coord(P_[0], width)
j = self.get_screen_y_coord(P_[1], height)
return np.array([int(i), int(j)]) |
def length_filter(e_miRbase_path):
e_miRbase = pickle.load(open(e_miRbase_path, 'rb'))
unvalids_file = open('unvalids.txt', 'a')
consensus_file = open('consensus.fasta', 'r')
consensus = {line.lstrip('>').rstrip('\n'):next(consensus_file).rstrip('\n') for line in consensus_file
if line... | The main task of the code is to filter and process small RNA sequencing data by aligning reads to a genome/transcriptome, filtering BAM files using samtools, and generating aligned haplotypes. It leverages tools like Bowtie and miRBase for alignment and validation, ultimately refining clusters for downstream analysis o... | def main_clusters_filter_seqmap(filt_bycount_bam, path_to_emiRbase, path_to_bowtie, path_to_genome, path_to_transcriptome, path_to_miRs_bed, path_to_samtools):
length_filter(path_to_emiRbase)
write_aligned_haplotypes(path_to_bowtie=path_to_bowtie,
path_to_genome=path_to_genome,
... |
def length_filter(e_miRbase_path):
e_miRbase = pickle.load(open(e_miRbase_path, 'rb'))
unvalids_file = open('unvalids.txt', 'a')
consensus_file = open('consensus.fasta', 'r')
consensus = {line.lstrip('>').rstrip('\n'):next(consensus_file).rstrip('\n') for line in consensus_file
if line... | The main task of the code is to process miRNA data by filtering miRBase entries by length, aligning haplotypes using Bowtie against genome/transcriptome indexes, and filtering BAM files with samtools. It integrates tools for alignment, filtering, and analysis of RNA-seq data to identify and refine miRNA clusters. | def main_clusters_filter_bowtie(filt_bycount_bam, path_to_emiRbase, path_to_bowtie, path_to_genome_index, path_to_transcriptome_index, path_to_miRs_bed, path_to_samtools):
length_filter(path_to_emiRbase)
write_aligned_haplotypes(path_to_bowtie=path_to_bowtie,
path_to_genome_index=pa... |
def generate_float(float_string):
""" Converts string float to float and returns it. """
# If number is negative, strips it out before processing.
is_negative = False
if float_string[0] == '-':
is_negative = True
float_string = float_string[1:]
# Edge case when - doesn't have ano... | The function `conv_num` converts a string representing a number (integer, hexadecimal, or float) into a base-10 integer or float. It validates the input by checking for correct formatting (e.g., single decimal point, no misplaced negatives). If valid, it delegates to helper functions: `generate_float` for decimals, `ge... | def conv_num(num_str):
""" Takes a string int, hex, or float, converts it to base 10, then returns it as a int or float. """
if not type(num_str) is str:
return None
point_count = num_str.count('.')
negative_count = num_str.count('-')
negative_index = num_str.find('-')
# Returns None i... |
def lookForContainer(self, id: str) -> bool:
for containerList in self.containers:
for container in containerList:
if container.getId() == id:
return True
return False
def popContainer(self) -> 'list[Container]':
if not self.isEmpty():
... | The code removes a container with a specified ID from a stack structure by temporarily storing other containers, searching for the target container, and restoring the remaining containers while returning the removed one. | def removeContainer(self, id: str) -> 'list[Container]':
if not self.lookForContainer(id):
return None
tempStack = []
found = False
while not found:
containerList = self.popContainer()
if len(containerList) == 2:
if containerList[0].g... |
def __import_database_config(self):
print_msg("Loading Database Config: {0}".format(self.__db_config_path))
# Parse the database config file
with open(self.__db_config_path) as yaml_file:
db_config_data = yaml.load(yaml_file, Loader=yaml.FullLoader)
# Extract the database inf... | The main task of the code is to initialize and manage a MySQL database connection by importing configuration, establishing a connection, setting up the database structure, and running continuously. It registers a shutdown handler to ensure proper cleanup, ensuring the database connection is closed upon program exit. | def start(self):
print_msg("Starting Database Manager")
atexit.register(self.stop)
self.__import_database_config()
self.__db_connection = MySQLDatabaseConnection(
self.__db_address,
self.__db_user,
self.__db_password,
self.__db_name)
... |
def _to_ascii(self, string):
for search, replace in self.replacements:
string = string.replace(search, replace)
string = unidecode(string)
return string
def user_name(self):
pattern = self.random_element(self.user_name_formats)
username = self._to_ascii(
... | The code generates an ASCII-compatible company email by concatenating the user name and domain name, then converting the result to ASCII using the `_to_ascii` method. This ensures the email address contains only ASCII characters for compatibility with systems that do not support Unicode. | def ascii_company_email(self):
return self._to_ascii(
self.user_name() + '@' + self.domain_name()
) |
def contains(self, user):
return self.was_in_queue(user) and self.get_user_queue(user).is_visible
def was_in_queue(self, user):
return self.get_user_queue(user) is not None
def get_user_queue(self, user):
return UserQueue.query.filter_by(queue_id=self.id, member_id=user.id).first() | This method adds a user to a queue, updating their existing entry if they're already in the system or creating a new entry. It tracks queue statistics, manages user visibility, and timestamps arrivals. If the user was previously in the queue, it updates their position and checks if they've been waiting over 5 minutes. ... | def add_member(self, user, name_printed):
if self.contains(user):
return
self.last_index += 1
if self.was_in_queue(user):
was_user = self.get_user_queue(user)
was_user.name_printed = name_printed
was_user.index_in_queue = self.last_index
... |
def getSDSSfields(ra, dec, size): # all in degree
delta = size
ra_max = ra + (delta / np.cos(abs(np.radians(dec))))
ra_min = ra - (delta / np.cos(abs(np.radians(dec))))
dec_max = dec + delta
dec_min = dec - delta
querry = """
SELECT
fieldID,
... | The main task of the code is to retrieve and process astronomical data from the SDSS (Sloan Digital Sky Survey) for a specified object, using its coordinates (ra, dec) and defined parameters (size, bands). It creates a temporary directory to store intermediate FITS files, organizes the data into a structured repository... | def sdssget(objName, ra, dec, size, bands, repository):
fields = getSDSSfields(ra, dec, size)
folder = repository + 'tmp'
if os.path.isdir(folder):
xcmd('rm -rf ' + folder, True)
xcmd('mkdir ' + folder, True)
if not os.path.isdir(repository + objName):
xc... |
def get_changes_from_last_sent(self):
"""Gets the changes between the last updated version (since you
can't have called send() without first update()) and the last
sent update"""
files = os.listdir(self.path)
files.sort(key=lambda x: int(x.split(".")[0]), reverse=True)
... | The main task of the code is to send emails by retrieving changes since the last send, handling errors, logging changes, updating the system state, and triggering a push action. | def send(self):
"""Sends the emails"""
changes, error = self.get_changes_from_last_sent()
if error:
return ERROR
print("sent")
print(changes)
self.just_sent()
self.update()
self.push() |
def get_download_url(arch, channel="stable", package="main", scheme="https"):
version = get_channel_latest_version(channel=channel, scheme=scheme)
url = constants.DOWNLOAD_URL[package].format(scheme=scheme, version=version, arch=arch)
return url
def _download_latest_info_file(path, channel, scheme):
url... | The main task of the code is to download Mikrotik update packages for specified architectures, handling path customization, mirroring, and automatic unzipping. It constructs download URLs, manages file paths (including directory structures for mirrors), ensures correct file extensions, and optionally unzips ZIP files, ... | def download_file(arch, path="./", channel="stable", package="main", force=False, scheme="https", mirror=False,
unzip=True):
"""
Downloads the Mikrotik update package for a given Mikrotik device architecture.
:param arch: the update's target architecture (i.e. mipsbe, arm, mmips, x86)
... |
def load_fasttext_embedding_model(f_fasttext_model_file, e_fasttext_model_file):
if os.path.exists(f_fasttext_model_file):
f_model = fasttext.load_model(f_fasttext_model_file)
if os.path.exists(e_fasttext_model_file):
e_model = fasttext.load_model(e_fasttext_model_file)
embedding_model = em... | The main task of the code is to train a neural network for cross-lingual alignment between English and Romanian using FastText embeddings. It initializes models, evaluates initial performance, trains via gradient descent, optimizes alignment with active sets, and tests accuracy across thresholds. The final embedding we... | def main():
# f_fasttext_vec_file = 'wiki.en.align.vec'
# e_fasttext_vec_file = 'wiki.ro.align.vec'
f_fasttext_model_file = 'en-ro-bpe-16K-en.bin'
e_fasttext_model_file = 'en-ro-bpe-16K-ro.bin'
f_fasttext_model_file = 'en_embedding_fasttext_model.bin'
e_fasttext_model_file = 'ro_embedding_fast... |
def load_fasttext_embedding_model(f_fasttext_model_file, e_fasttext_model_file):
if os.path.exists(f_fasttext_model_file):
print('exist embedding src file')
#f_model = fasttext.load_model(f_fasttext_model_file)
if os.path.exists(e_fasttext_model_file):
print('exist embedding trg file')
... | The code evaluates the performance of an alignment model using embedding models on a dataset. It loads training/test data, initializes an embedding model, computes alignment scores before initialization, and tests alignment with BPE processing, outputting metrics like accuracy. | def main():
emalgo = EmAlgo()
active_set = ActiveSet(30)
train_dataset = AlignDataset(parameters.f_train_filename, parameters.e_train_filename)
test_dataset = AlignDataset(parameters.f_test_filename, parameters.e_test_filename)
print('loading embedding model...')
embedding_model = load_f... |
def _setup_socket(self):
"""
Little abstraction/modulation for which was used in testing
FIXME We have got to use a better flow
"""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.bind(("", self.src_port))
time_limit = self.connect_try_t... | This code manages a UDP communication thread, handling data transmission, buffer management, and message processing. It stores incoming frames, distributes them, checks for missing data, sends packets when buffer space allows, processes incoming commands, and sends heartbeats to maintain connectivity. The loop continue... | def run(self) -> None:
"""
Starts the mainloop of the thread
"""
# This will wait until both prove they are connected
self._setup_socket()
while self.alive:
# Fixme we still have a bug where every 40th frame gets dropped
self.store_incoming() # m... |
def get_initial_conditions():
'''
Asks the user for the initial altitude, speed and amount of fuel and returns those three in a list
Parameter:
None
Return:
lists: (list) - a list containing initial altitude, speed and amount of fuel (in that order)
'''
# asks the user for the in... | The main task of the code is to simulate a manual spaceship landing by allowing user input for thrust control, tracking altitude, speed, and fuel levels, updating the spacecraft's status in real-time, and reporting landing outcomes. It also lets users restart the simulation, save data history, or plot results after eac... | def main():
'''
Controls the entire spaceship simulation in manual mode
Parameter:
None
Return:
None
'''
print("Hello, there!!! Welcome to my Spaceship simulator!!")
# greets the user at the start of the game
keep_going = True
landing_attempts = 1
# the land... |
def get_places():
"""Convert input file to list"""
places = []
in_file = open(FILENAME, "r")
for line in in_file:
parts = line.strip().split(",")
if parts[3] == "v":
visited_status = True
else:
visited_status = False
new_place = Place(name=parts[0]... | The code implements a travel tracker program that allows users to load, view, add, mark as visited, and save a list of places. It provides a menu-driven interface for managing places, with data persistence through file operations. | def main():
"""Program to get and list users visited and unvisited places"""
print("Travel Tracker 1.0 - by Rhys Simpson")
places = get_places()
print("{} places loaded from {}".format(len(list(places)), FILENAME))
choice = input(MENU).upper()
while choice != "Q":
if choice == "L":
... |
def preprocess(src):
img = cv2.resize(src, (input_imgW, input_imgH)).astype(np.float32)
img = img * 0.00392156
img = img.transpose(2, 0, 1)
img_input = img.copy()
return img_input
def get_engine_from_bin(engine_file_path):
print('Reading engine from file {}'.format(engine_file_path))
with op... | The code loads an image, preprocesses it, and uses a TensorRT engine for pose detection inference. It processes outputs to extract bounding boxes and keypoints, then visualizes results by drawing boxes, labels, and skeleton connections on the original image, saving the annotated output as 'test_result_tensorRT.jpg'. | def main():
engine_file_path = 'yolov8pos_relu_zq.trt'
input_image_path = 'test.jpg'
orig_image = cv2.imread(input_image_path)
orig = cv2.cvtColor(orig_image, cv2.COLOR_BGR2RGB)
img_h, img_w = orig.shape[:2]
image = preprocess(orig)
with get_engine_from_bin(engine_file_path) as engine, eng... |
def complementDecayVals(oList,coList, tidx=-1, tau=0.1, stau=0.0, tresh=0.0, decaying=True): #updated for repetition 26320
oL = decayVals(oList,tau=tau,tresh=tresh,decaying=decaying)
coL = InversdecayVals(coList, tau=tau, stau=stau, tidx = tidx, tresh=tresh, decaying=decaying)
#if type(oList).__module__ != 'numpy':
... | The function processes two lists (oList and coList) by identifying maximum values and applying decay or complement operations based on conditions. It returns the index of the selected element along with modified lists, rounded to specified precision. The logic differs for 'queue=True' (focusing on coList maxima and dec... | def maxComplReadoutVals(oList, coList, tau=0.1, tresh=0.0, stau=0.01, accdig=10, queue=True):
decay = 1 - tau
subinc = 1 + stau #**
idx=-1
lmax = 0
oL = list(oList)
coL = list(coList)
oLo = list(oL)
coLo = list(coL)
if queue:
maxval = max(coL)
print('maxval=', maxval)
maxidxs = [i for i in range(len(coL... |
def section_header(text):
log()
time = get_timestamp()
time_str = dim('(' + time + ')')
header = bold_yellow_underline(text)
print(header + ' ' + time_str, file=sys.stderr, flush=True)
def explanation(text, indent_size=4):
text = ' ' * indent_size + text
terminal_width, _ = get_terminal_size... | The function filters SAM alignment files by retaining pairs with correct orientation and insert size within specified bounds, marking invalid pairs with a "ZP:Z:fail" tag. Valid alignments are written to output files, while invalid ones are flagged for exclusion by Polypolish. It returns the total count of filtered ali... | def filter_sams(in1, in2, out1, out2, alignments, low, high, correct_orientation):
section_header('Filtering SAM files')
explanation('Read alignments that are part of a good pair (correct orientation and insert '
'size) pass the filter and are written unaltered to the output file. Read '
... |
def section_header(text):
log()
time = get_timestamp()
time_str = dim('(' + time + ')')
header = bold_yellow_underline(text)
print(header + ' ' + time_str, file=sys.stderr, flush=True)
def explanation(text, indent_size=4):
text = ' ' * indent_size + text
terminal_width, _ = get_terminal_size... | (The code calculates low and high insert size thresholds for a read set by analyzing properly aligned paired reads, determining the correct orientation (either user-specified or auto-detected), and computing percentiles from sorted insert sizes. It returns these thresholds and the identified orientation for filtering r... | def get_insert_size_thresholds(alignments, correct_orientation, low_percentile, high_percentile):
section_header('Finding insert size thresholds')
explanation('Read pairs with exactly one alignment per read are used to determine the '
'orientation and insert size thresholds for the read set.')
... |
def parse_args():
description = 'R|' + get_ascii_art() + '\n' + \
'Polypolish insert size alignment filter v' + __version__ + '\n' + \
'github.com/rrwick/Polypolish'
parser = MyParser(description=description, formatter_class=MyHelpFormatter, add_help=False)
input_args = ... | The main task of the code is to filter paired-end alignments based on insert size thresholds, outputting filtered results to specified files. It parses input parameters, loads alignments, calculates size thresholds, filters alignments using these thresholds, and reports the number of alignments before and after filteri... | def main():
args = parse_args()
check_inputs(args)
start_time = starting_message(args)
alignments, before_count = load_alignments(args.in1, args.in2)
low, high, correct_orientation = get_insert_size_thresholds(alignments, args.orientation,
... |
def fit_points(x2, t2, x, t):
mcs = []
for i in range(len(x2)-1):
mc = linear_fit(x2[i:i+2], t2[i:i+2])
mcs.append(mc)
return mcs
def fit_legs(x2, x, t):
mcs = []
x2 = np.hstack((0, x2, np.max(x)+1))
point = (0, 0)
for i in range(len(x2)-1):
ind = np.logical_and(x >= ... | The code fits a travel time model to seismic data using different methods based on input parameters (mode, ttpicks, n). It processes x and t data, applies fitting functions (fit_points, fit_legs, fit_ndmodel), plots the resulting model curves, calculates RMS error, and returns the fitted model for analysis. | def fit_model(x, t, n=None, ttpicks=None, mode=None):
x = np.abs(x)
if ttpicks and mode == 't':
x2, t2 = zip(*ttpicks)
mcs = fit_points(x2, t2, x, t)
elif ttpicks and mode == 'r':
x2, _ = zip(*ttpicks)
mcs, x2 = fit_legs(x2, x, t)
else:
assert n is not None
... |
def plot(self, mode):
modes = ['first_call', 'new_shot', 'update_stream', 'update_wiggles',
'update_picks']
assert mode in modes
mind = modes.index(mode)
xlim = self.ax.get_xlim()
ylim = self.ax.get_ylim()
if mind < 2:
self.fig.suptitle('shot ... | This code handles keyboard events in a plotting application, modifying parameters like normalization, clipping, polarity, and trace visibility. It updates plots based on key presses for data adjustments, saves picks, zooms, fits lines, and manages shot configurations, enabling interactive seismic data visualization and... | def keypress(self, event):
if event.inaxes != self.ax:
return
print('You pressed ' + event.key)
if event.key == 'k':
print(_key_doc)
elif event.key in 'gb':
factor = 1.2 if self.opt.normalize else 2
if event.key == 'g':
self... |
def get_pairs_from_paths(images_path, segs_path, mode="train", ignore_non_matching=False):
""" Find all the images from the images_path directory and
the segmentation images from the segs_path directory
while checking integrity of data """
acceptable_img_formats = [".jpg", ".jpeg", ".png", ".bm... | The code evaluates a segmentation model's performance by calculating metrics like frequency-weighted IoU, mean IoU, and class-wise IoU. It loads model weights from checkpoints, processes input images and annotations, compares predicted segmentation maps with ground truth, and aggregates per-class true positives, false ... | def evaluate(model=None, inp_images=None, annotations=None, inp_images_dir=None, annotations_dir=None,
checkpoints_path=None):
""" evaluate """
n_classes = model.n_classes
input_height = model.input_height
input_width = model.input_width
output_height = model.output_height
output_wi... |
def ask_question(self):
if len(self.questions) == 0:
# first question is given by human to request a general discription
question = FIRST_QUESTION
else:
if self.model in VALID_CHATGPT_MODELS:
chatgpt_messages = prepare_chatgpt_message(
... | This method conducts a multi-round conversation by generating questions and answers, storing them, and displaying progress based on the specified print mode. It supports "chat" (console output) or "gradio" (interface updates) modes, trimming inputs/outputs and tracking tokens. It returns collected questions, answers, a... | def chatting(self, n_rounds, print_mode):
if print_mode == "chat":
print("--------Chat Starts----------")
for i in tqdm(range(n_rounds), desc="Chat Rounds", disable=print_mode != "bar"):
question = self.ask_question()
# print('Raw: {}'.format(question))
q... |
def obter_nome_exercitos(m):
'''
obter_nome_exercitos: mapa -> tuplo
obter_nome_exercitos(m) devolve um tuplo ordenado com duas cadeias de caracteres correspondendo aos nomes dos exercitos do mapa
'''
if len(m["exercito1"])>0 and len(m["exercito2"])>0: #Verifica se o exercito contem unida... | The function identifies and returns a sorted tuple of enemy units adjacent to a given unit in a maze, based on the order of reading the maze, by checking neighboring positions and filtering units from the opposing army. | def obter_inimigos_adjacentes(m,u):
'''
obter_inimigos_adjacentes: mapa x unidade -> tuplo unidades
obter_inimigos_adjacentes(m, u) devolve um tuplo contendo as unidades inimigas adjacentes a unidade u de acordo com a ordem de leitura do labirinto
'''
exercitos=obter_nome_exercitos(m)
exercit... |
def obter_unidades_exercito(m,e):
'''
obter_unidades_exercito: mapa x str -> tuplo unidades
obter_unidades_exercito(m, e) devolve um tuplo contendo as unidades do mapa pertencentes ao exercito indicado pela cadeia de caracteres e, ordenadas em ordem de leitura do labirinto
'''
unidades=[]
... | The function `calcula_pontos` calculates the total score of an army by summing the health points (vida) of all its units in a given map. It returns 0 if the army has no units. The score is computed by iterating through each unit in the specified army and accumulating their health values, regardless of which of the two ... | def calcula_pontos(m,e):
'''
calcula_pontos: mapa x str -> int
Funcao auxiliar que recebe um mapa e uma cadeia de caracteres correspondente ao nome de um dos exercitos do mapa e devolve a sua pontuacao. A pontuacao dum exercito e o total dos pontos de vida de todas as unidades do exercito
'''
pon... |
def eh_labirinto (maze):
#Verifica se o maze e um tuplo
if not isinstance(maze,tuple):
return False
#Verifica se o maze tem o numero minimo de tuplos
if len(maze)<3:
return False
for tuplo in range(len(maze)):
#Verifica se os elementos do maze sao tuplos
if not isinstance(maze[... | The function checks if all positions in the given set 'conj' are valid within the maze 'maze'. It first verifies that 'maze' and 'conj' are valid structures. Then, it iterates through each position in 'conj' to ensure they belong to 'maze' using a helper function. Returns True if all positions are valid, otherwise Fals... | def eh_mapa_valido(maze,conj):
#Verifica os argumentos
if not(eh_labirinto(maze)==True and eh_conj_posicoes(conj)==True):
raise ValueError("eh_mapa_valido: algum dos argumentos e invalido")
#Verifica se os elementos do conjunto sao validos atraves de uma funcao auxiliar
for elem in conj:
if... |
def obter_todas_unidades(m):
'''
obter_todas_unidades: mapa -> tuplo
obter_todas_unidades(m) devolve um tuplo contendo todas as unidades do mapa, ordenadas em ordem de leitura do labirinto
'''
exercito1=()
exercito2=()
if len(m["exercito1"])>0: #Verifica se o exercito cont... | The function checks if a given position on the map is occupied by any unit by comparing it with the positions of all units in the map. It returns True if the position matches a unit's location, otherwise False. | def eh_posicao_unidade(m,p):
'''
eh_posicao_unidade: mapa x posicao -> booleano
eh_posicao_unidade(m, p) devolve True apenas no caso da posicao p do mapa estar ocupada por uma unidade
'''
for unidade in obter_todas_unidades(m):
if [obter_pos_x(p),obter_pos_y(p)]==obter_posicao(unidade):
... |
def obter_todas_unidades(m):
'''
obter_todas_unidades: mapa -> tuplo
obter_todas_unidades(m) devolve um tuplo contendo todas as unidades do mapa, ordenadas em ordem de leitura do labirinto
'''
exercito1=()
exercito2=()
if len(m["exercito1"])>0: #Verifica se o exercito cont... | The function simulates a complete battle turn by sequentially moving and attacking each unit in the map according to the maze's reading order. Units move first, then attack adjacent enemies if present. If an attack defeats an enemy, the enemy is removed from the map and the units list. The process repeats until all uni... | def simula_turno(m):
'''
simula_turno: mapa -> mapa
Funcao auxiliar que modifica o mapa fornecido como argumento de acordo com a simulacao de um turno de batalha completo, e devovle o proprio mapa. Iste e,seguindo a ordem de leitura do labirinto, cada unidade(viva) realiza um unico movimento e um ataque de aco... |
def eh_labirinto (maze):
#Verifica se o maze e um tuplo
if not isinstance(maze,tuple):
return False
#Verifica se o maze tem o numero minimo de tuplos
if len(maze)<3:
return False
for tuplo in range(len(maze)):
#Verifica se os elementos do maze sao tuplos
if not isinstance(maze[... | This function checks if a given position in a maze is free, i.e., not on a wall and not occupied by any position in a provided set. It first validates inputs, then verifies the position's validity within the maze and ensures it does not conflict with positions in the set. | def eh_posicao_livre(maze,conj,posicao):
#Verifica argumentos
if not(eh_labirinto(maze)==True and eh_posicao(posicao)==True and eh_conj_posicoes(conj)==True and eh_mapa_valido(maze,conj)==True):
raise ValueError("eh_posicao_livre: algum dos argumentos e invalido")
#Verifica se a posicao pertence ao ma... |
def eh_labirinto (maze):
#Verifica se o maze e um tuplo
if not isinstance(maze,tuple):
return False
#Verifica se o maze tem o numero minimo de tuplos
if len(maze)<3:
return False
for tuplo in range(len(maze)):
#Verifica se os elementos do maze sao tuplos
if not isinstance(maze[... | The main task of the code is to convert a maze structure into a string representation, where walls are denoted by '#', paths by '.', and positions in the provided set 'conj' are marked with 'O'. It validates inputs, iterates through the maze columns, constructs the string row by row, and replaces specified positions wi... | def mapa_str (maze,conj):
#Verifica argumentos
if not(eh_labirinto(maze)==True and eh_conj_posicoes(conj)==True):
raise ValueError("mapa_str: algum dos argumentos e invalido")
if not eh_mapa_valido(maze,conj):
raise ValueError("mapa_str: algum dos argumentos e invalido")
n=0 #Utilizad... |
def obter_tamanho(m):
'''
obter_tamanho: mapa -> tuplo
obter_tamanho(m) devolve um tuplo de dois valores inteiros correspondendo o primeiro deles a dimensao Nx e o segundo a dimensao Ny do mapa
'''
return (m["dim"][0],m["dim"][1])
def eh_posicao_unidade(m,p):
'''
eh_posicao_unidade: mapa... | The function `mapa_para_str` converts a map structure into a string representation. It iterates through each position in the map, appending characters based on the type of position: units are represented by their external character, walls and exterior limits as `#`, and corridors as `.`. Each row is joined with newline... | def mapa_para_str(u):
'''
mapa_para_str: mapa -> str
mapa_para_str(u) devolve uma cadeia de caracteres que representa o mapa como descrito no primeiro projeto, neste caso, com as unidades representadas pela sua representacao externa
'''
mapa=''
#Percorre todas as posicoes de uma linha antes ... |
def obter_exercito(u):
'''
obter_exercito: unidade -> str
obter_exercito(u) devolve a cadeia de carateres correspondente ao exercito da unidade
'''
return u[3]
def obter_nome_exercitos(m):
'''
obter_nome_exercitos: mapa -> tuplo
obter_nome_exercitos(m) devolve um tuplo ordenado com duas... | The code identifies all valid corridor positions adjacent to enemy units, excluding those occupied by units, and returns them as a list of unique positions. | def obter_objetivos(source):
enemy_side = tuple(filter(lambda u: u != obter_exercito(source), obter_nome_exercitos(mapa)))[0]
target_units = obter_unidades_exercito(mapa, enemy_side)
tup_com_repetidos = \
tuple(adj
for other_unit in target_units
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.