dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def cloneSolution(self, sol: Solution):
cloned = copy.deepcopy(sol)
return cloned
def InitializeOperators(self, rm, sm, top):
rm.Initialize()
sm.Initialize()
top.Initialize()
def FindBestRelocationMove(self, rm):
for originRouteIndex in range(0, len(self.sol.routes)):
... | This code performs a local search algorithm using random relocation, swap, and two-opt moves to iteratively improve a solution's cost. It initializes a best solution, applies selected operators to generate moves, and updates the solution if the move reduces the cost. If no improvement is found, penalties are applied, a... | def LocalSearch(self, operator):
random.seed(1)
self.bestSolution = self.cloneSolution(self.sol)
terminationCondition = False
localSearchIterator = 0
rm = RelocationMove()
sm = SwapMove()
top = TwoOptMove()
while terminationCondition is False:
... |
def find_nearest_node_to_depot(self):
dist = self.distanceMatrix[0]
min = 100000000
for c in self.customers:
if dist[c.ID] < min:
min_node = c
min = dist[c.ID]
return min_node, min
def find_less_distant_node(self,multiplier,multiplier2):
... | The code implements a nearest neighbor heuristic to assign unrouted nodes to vehicle routes in a vehicle routing problem. It initializes 14 routes, iteratively selects the nearest node to add to each route, updates route costs, loads, and node attributes, and applies multipliers to balance route distribution. The metho... | def ApplyNearestNeighborMethod(self):
modelIsFeasible = True
self.sol = Solution()
for i in range(0, 14):
self.sol.routes.append(Route(self.depot, self.capacity))
self.sol.routes[i].ID = i
# j = 0
self.list_of_last_nodes = [r.last_node for r in self.sol.... |
def ApplyNearestNeighborMethod(self):
modelIsFeasible = True
self.sol = Solution()
for i in range(0, 14):
self.sol.routes.append(Route(self.depot, self.capacity))
self.sol.routes[i].ID = i
# j = 0
self.list_of_last_nodes = [r.last_node for r in self.sol.... | The main task of the code is to solve an optimization problem by first applying the nearest neighbor heuristic to generate an initial solution, then performing a local search with a specified parameter (2) to refine the solution. The improved solution is reported twice during execution before being returned. | def solve(self):
self.ApplyNearestNeighborMethod()
# self.MinimumInsertions()
# self.geteasysol()
self.ReportSolution(self.sol)
self.LocalSearch(2)
self.ReportSolution(self.sol)
return self.sol |
def pre_interface(self) -> None:
"""
print some "log", just for fun...
:return:
"""
time_a = 0.06
infos = ["init...", "reading config...", "dependency checking...", "accessing devices..."]
for info in infos:
UiUtils.sprint(info)
time.sleep... | The code initializes a system with configuration, dependency checks, device management, and utility tools. It sets up default paths and names, initializes UI interfaces based on config settings, and enters a loop to run the main functionality. Exceptions are caught, errors are displayed, and the system prompts for relo... | def __init__(self) -> None:
self.config = Config()
self.dependency_check = DependencyCheck()
self.devices = DeviceGetter().devices
self.shot_utils = ShotUtils()
self.default_save_path = self.config.default_save_path
self.default_name_base = self.config.default_name_base
... |
def intVal(self):
operand = ''
while self.current is not None and self.current.isdigit():
operand += self.current
self.nextChar()
return int(operand)
def negativeInt(self):
if self.current == '-' and self.expression[self.index + 1].isdigit():
self.nex... | This function processes an expression string to generate tokens for integers and arithmetic operators. It identifies digits, negative integers, and operators (+, -, *, /, %), skips whitespace, and returns corresponding Token objects. If no valid token is found, it returns an EOF token. | def exprToToken(self):
while self.current is not None:
if self.current.isdigit():
return Token('Integer', self.intVal())
if self.current == '-' and self.expression[self.index + 1].isdigit():
return Token('Integer', self.negativeInt())
if self... |
def build_wct_model(self):
img = Input(self.img_shape, name='in_img')
kernel_size = 3
skips = []
vgg_model = VGG19(include_top=False,
weights=self.backbone_weight,
input_tensor=Input(self.img_shape),
input_sha... | The code initializes a neural network model for image reconstruction using a pre-trained backbone (e.g., ImageNet weights). It sets hyperparameters like image size, learning rate, and loss weights, constructs a WCT (Weighted Content Transfer) model, defines a reconstruction pipeline, and compiles the model with Adam op... | def __init__(
self,
image_size=256,
lr=1e-3,
show_interval=25,
gram_loss_weight=1.0,
checkpoint_path="PST/checkpoints/wtc2.h5",
backbone_weight="imagenet",
):
self.image_size = image_size
self.lr = lr
self.show_interval = show_interval
... |
def _create_clusters(self,centroids):
cluster = [[] for _ in range(self.k)]
for idx,sample in enumerate(self.x):
centroid_idx = self._closest_centroid(sample,centroids)
cluster[centroid_idx].append(idx)
return cluster
def plot(self):
fig,ax = plt.subplots(figsize... | This code implements the K-Means clustering algorithm. It initializes centroids randomly, iteratively assigns data points to clusters, updates centroids, and stops when convergence is reached. The function returns cluster labels for the input data. | def predict(self,x):
self.x = x
self.n_samples , self.n_features= x.shape
random_samples_idxs = np.random.choice(self.n_samples,self.k,replace = False)
self.centroids = [self.x[idx] for idx in random_samples_idxs]
for _ in range(self.max_iters):
self.clusters =... |
def _most_common_label(self,y):
counter = Counter(y)
most_common = counter.most_common(1)[0][0]
return most_common
def _best_criteria(self,x,y,feat_idx):
best_gain = -1
split_idx,split_thresh = None,None
for feat_idx in feat_idx:
x_column = x[:,feat_idx]
... | This function recursively builds a decision tree by selecting the best feature/threshold to split data, creating left/right subtrees until stopping conditions (max depth, single class, or min samples) are met, then returning a node with split details or a leaf node with the most common label. | def _grow_tree(self,x,y,depth = 0):
n_samples,n_features = x.shape
n_labels = len(np.unique(y))
if (depth >= self.max_depth or n_labels ==1 or n_samples < self.min_samples_split):
leaf_value = self._most_common_label(y)
return Node(value = leaf_value)
feat_idx =... |
def _select_individuals_with_roulette_method(population):
selected_individuals = generate_empty_population()
roulette_slices = _calculate_a_roulette_slice_for_each_individual(population)
for i in range(0, POPULATION_SIZE):
selected_individuals[i] = _select_single_individual_with_roulette_method(population, r... | This function selects individuals from a population for reproduction based on the configured natural selection method (roulette, tournament, or uniform). It routes the request to the corresponding internal method and raises an error if no valid method is set. | def select_individuals_to_reproduction(population):
if NATURAL_SELECTION_METHOD == NaturalSelectionMethods.ROULETTE:
return _select_individuals_with_roulette_method(population)
if NATURAL_SELECTION_METHOD == NaturalSelectionMethods.TOURNAMENT:
return _select_individuals_with_tournament_method(population)... |
def determine_fishy_lock_path(database_pathname: str) -> Path:
return Path(database_pathname).with_name("FISHy.lck")
def create_database(database_pathname):
with sqlite3.connect(database_pathname) as connection:
if should_drop_table:
connection.execute(f"DROP TABLE IF EXISTS {TABLE_NAME}")
... | The main task of the code is to run a database indexer that ensures exclusive execution by creating a lock file. It checks if another instance is running via a lock file, creates the database, and indexes files if no conflict exists. If the lock exists, it exits to prevent concurrent runs. | def main():
global unlink_fishy_path
logging.getLogger().setLevel(logging.DEBUG)
if len(sys.argv) != 2:
logging.debug("Pass DB pathname as parameter")
return
database_pathname = sys.argv[1]
fishy_lock_path = determine_fishy_lock_path(database_pathname)
try:
if fishy_l... |
def alpha_shape_3D(self,pos, alpha,z_weight=1):
"""
Compute the alpha shape (concave hull) of a set of 3D points.
Parameters:
pos - np.array of shape (n,3) points.
alpha - alpha value.
return
outer surface vertex indices, edge indices, and triangle ind... | The main task of the code is to compute the surface area and volume of a 3D concave hull generated from input point cloud data using an alpha shape algorithm. It constructs triangular faces, calculates their planar equations, and integrates tetrahedral volumes based on orientation and distance from external points. The... | def computeSurfaceVolumeConcav(self,data,alpha,show=False,z_weight=1):
[as_v,as_e,as_t,as_pin]=self.alpha_shape_3D(data,alpha,z_weight=z_weight)
polygons=[]
point_inside=[]
for t in as_t:
polygons.append([data[t[0]],data[t[1]],data[t[2]]])
for pin in as_... |
def random_code(fmt: str, num: int) -> Callable[[], str]:
codes = {idx: fake.last_name() for idx in range(num)}
idx = 0
def random_code_closure():
nonlocal idx, codes
idx = (idx + 1) % num
return codes[idx]
return random_code_closure
def random_price(
_global: bool,
... | The main task of the code is to generate synthetic financial data by creating random security codes, open/close prices, and timestamps, then setting up a callback with these generated data elements for further processing or simulation. | def preprocess(self) -> None:
code_handle = random_code('', self.num)
codes = [code_handle() for _ in range(self.num)]
open_handle = random_price(
True, self.basevalue, self.term, self.rate, self.sigma, self.nper_per_year, codes, False)
close_handle = random_price(
... |
def _recreate_menu(self):
menu_items = [
{
"viewclass": "OneLineIconListItem",
"icon": "git",
"text": f"{stage_id}",
"height": dp(56),
"on_release": lambda x=stage_id, y=stage: self.set_item(x, y),
} for stag... | The code sets the current quest and updates the interface by recreating the menu, updating fields, and recreating stages. It assigns the provided `Quest` object to `current_quest` and triggers internal methods to refresh UI elements and data associated with the quest. | def set_quest(self, quest: Quest):
self.current_quest = quest
self._recreate_menu()
self._update_fields()
self._recreate_stages() |
def SetRoutedFlagToFalseForAllCustomers(self):
for i in range(0, len(self.customers)):
self.customers[i].isRouted = False
self.customers[i].isTabuTillIterator= -1
def ApplyNearestNeighborMethod(self, itr):
modelIsFeasible = True
insertions = 0
bicl = []
bi... | The code implements a heuristic algorithm for solving a vehicle routing problem (VRP). It iterates 20 times, each time applying the nearest neighbor method to generate initial routes, performing local searches to optimize them, and updating the best solution if the current one has a lower cost. The final best solution ... | def solve(self):
file1 = open("sol_8180070.txt","w")
random.seed(101)
o = 0
for i in range(20):
self.SetRoutedFlagToFalseForAllCustomers()
self.sol = Solution()
for j in range(25):
rt = Route(self.depot, self.capacity)
... |
def seven_minute_workout():
"""
Guides the user through the classic seven minute workout.
:return:
"""
read("Seven Minute Workout, here we go!")
exercises = ["jumping jacks", "wall sit", "push ups", "sit-ups"\
"step ups", " air squats", "chair dips", "plank" \
"... | The code's main task is to parse command-line arguments for workout selection and rounds, then execute the chosen workout routine for the specified number of rounds. It uses argparse to handle input, offers mutually exclusive workout options, and triggers corresponding functions like seven_minute_workout() or core_work... | def main():
"""
Parses the command line options for the number of rounds and the selected workout.
Guides the user through the selected workout for the selected number of rounds.
:return:
"""
parser = argparse.ArgumentParser(description='Select a workout.', epilog="Kill your workout.")
parse... |
def display_message(self, msg):
font = pygame.font.SysFont("comicsansms", 72, True)
text = font.render(msg, True, (255, 255, 255))
self.gameDisplay.blit(text, (400 - text.get_width() // 2, 240 - text.get_height() // 2))
self.display_credit()
pygame.display.update()
self.c... | This code runs a multiplayer car racing game loop, handling player input, network communication, collision detection, and rendering. It updates the game state by sending player position data, renders cars and obstacles, checks for collisions or out-of-bound conditions, displays win messages, and synchronizes gameplay b... | def run_car(self):
self.gameDisplay = pygame.display.set_mode((self.display_width, self.display_height))
pygame.display.set_caption("Player" + " " + str(self.player + 1))
while not self.crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
... |
def detIfContact(self):
if self.ballorstrike == "strike":
val = .80 + (((1 * self.batter.contact) - self.pitcher.knine) / 200)
else:
val = .55 + ((self.batter.contact - self.pitcher.knine) / 200)
rand = r.randint(0, 100)
if rand < val * 100: # contact
... | This function determines if a swing results in contact or a strike/ball. It calculates a probability value based on batter/pitcher attributes, compares it to a random number, and updates game state: calling detIfContact() for a swing or incrementing strikes/balls. It triggers a walk if 4 balls or an out if 3 strikes, t... | def detIfSwing(self):
if self.ballorstrike == "strike":
val = .68 + ((self.batter.eye - 50) / 150)
else:
val = .27 + 0 + ((self.pitcher.knine - self.batter.eye) / 150)
rand = r.randint(0, 100)
if rand < val * 100:
self.detIfContact()
else:
... |
def pitch(self):
# adjust pitcher energy
self.pitcher.energy -= .85 + (pow((75-self.pitcher.stamina), 3)/100000)
# adds to pitch count
if self.pitchingTeam == self.home:
self.hPC += 1
else:
self.aPC += 1
# if (self.balls == 0) & (self.strikes == ... | The main task of the code is to simulate a baseball game by managing innings, outs, and pitching changes. It progresses through each half-inning (top/bottom), tracks outs, switches pitchers when energy is low, and advances the game state until the maximum innings are reached, the half-inning completes, or scores are ti... | def startGame(self):
self.inning = 1
self.half = 0
self.outs = 0
self.batter = self.battingTeam.batter
self.pitcher = self.pitchingTeam.pitcher
while (self.inning < (self.games * 9) + 1) | (self.half == 1) | (self.aScore == self.hScore):
toPrint = "\n--- "
... |
def is_connected(self):
return self.__conn_state is not ConnectionState.DISCONNECTED
def __recv_to_buffer(self, timeout):
readable, _, xlist = select.select([self.__sock], [], [self.__sock], timeout)
if len(readable):
more = self.__sock.recv(4096)
#When the controller sto... | The main task of the code is to receive and process packets from a connected buffer based on a specified command. It continuously checks for valid packet headers, unpacks data, and returns the relevant packet content if the command matches. If not, it skips packets. The function handles timeouts, ensures sufficient buf... | def __recv(self, command, binary=False):
while self.is_connected():
try:
self.__recv_to_buffer(DEFAULT_TIMEOUT)
except RTSITimeoutException:
return None
# unpack_from requires a buffer of at least 3 bytes
while len(self.__buf) >= 3... |
def is_connected(self):
return self.__conn_state is not ConnectionState.DISCONNECTED
def __recv_to_buffer(self, timeout):
readable, _, xlist = select.select([self.__sock], [], [self.__sock], timeout)
if len(readable):
more = self.__sock.recv(4096)
#When the controller sto... | The function retrieves buffered data packages from a connection, handling exceptions and returning the next available data package or None if unavailable. It buffers multiple received packages and returns them sequentially, adhering to a specified buffer limit if provided. | def get_output_data_buffered(self, binary = False, buffer_limit = None):
"""Recieve the next data package.
If muliple packages has been received they are buffered and will
be returned on subsequent calls to this function.
Returns None if no data is available.
"""
if self... |
def addnode(self, coordinates):
self.nodelist[coordinates[0]][coordinates[1]] = 1
def connect_new_nodes(self):
while True:
selected_node = list(self.empty_nodes())
selected_one_away = random.choice(self.one_away(selected_node))
if not self.connection_check(selected_no... | The code generates a filled grid structure by starting at a specified point, iteratively connecting new nodes and updating their types until the total filled area reaches a predefined percentage of the grid's total size, at which point the process stops. | def generate(self):
self.addnode(self.starting_point)
self.nodetypes[self.starting_point[0]][self.starting_point[1]] = 2
self.done = False
# drawn = 0
while not self.done:
self.connect_new_nodes()
self.createtypes()
# self.drawall()
... |
def drawgrid(self):
for i in range(1, self.h + 1):
pygame.draw.line(self.screen, DARK_GREY, (i * self.margin, self.margin),
(i * self.margin, self.w * self.margin), self.grid_line_width)
for j in range(1, self.w + 1):
pygame.draw.line(self.screen, DAR... | The code's main task is to render a visual interface by clearing the screen with a black background, drawing a grid, adding lines, and placing circles, likely for a game or graphical application. | def drawall(self):
self.screen.fill(BLACK)
self.drawgrid()
self.drawlines()
self.drawcircles() |
def _select_print(self, x):
self.screen.clear()
self.screen.border(0)
self.screen.addstr(1, 2, self.help_message[0])
self.screen.addstr(2, 2, self.help_message[1])
partn = 0
i = 0
if 'blockdevices' not in self.blkinfo:
raise Exception('Wrong lsblk jso... | The code implements a curses-based interactive interface for selecting and managing disk partitions. It allows navigation (up/down), ejecting, mounting, unmounting, and power-off operations on partitions. The loop quits on 'q', 'Esc', or 'Ctrl+g', returning the selected mountpoint if Enter is pressed, otherwise an empt... | def select(self):
sel = None
x = 0
# quit when pressed `q` or `Esc` or `Ctrl+g`
while x not in (ord('q'), curses.ascii.ESC,
curses.ascii.BEL, curses.ascii.NL):
self._select_print(x)
x = self.screen.getch()
if x in (ord('j'), cur... |
def train_rank_based(df):
tally_average_playcounts(df)
build_title_dictionary(df)
def train_content_based(df):
tfidf_df = df.copy()
tfidf_df = assemble_text_features(tfidf_df)
pickle.dump(tfidf_df, open('../music-recommendations/Models/songs_with_text_feature.pkl', 'wb'))
tfidf = build_song_tfi... | The main task of the code is to load a dataset from a pickle file and train three distinct recommendation models: rank-based, content-based, and collaborative filtering. The `main()` function orchestrates this workflow by sequentially invoking training functions for each model type, using the same dataset for all. This... | def main():
df = pickle.load(open('Data/playbacks.pkl', 'rb'))
train_rank_based(df)
train_content_based(df)
train_collaborative_filtering(df) |
def first_layerr(test_input, hash):
K.clear_session()
first_layer = load_model(os.path.join(os.path.dirname(__file__), 'first_layer.hdf5'))
out = first_layer.predict(test_input)
out1 = out[0, :, :, :]
bla = first_layer.layers[0].get_weights()[0]
plt.plot(bla.flatten())
plt.savefig(static_fil... | The code processes the input data through three sequential layers using a provided hash, likely for a neural network or data transformation pipeline. Each layer applies specific operations to the test input, modifying it iteratively. The main task is to execute these three layers in sequence to generate a prediction or... | def three_layer_predict(_hash, test_input):
first_layerr(test_input, _hash)
second_layerr(test_input, _hash)
third_layerr(test_input, _hash) |
def static_filepath(filepath):
return os.path.join(basepath, filepath)
def three_layer_predict(_hash, test_input):
first_layerr(test_input, _hash)
second_layerr(test_input, _hash)
third_layerr(test_input, _hash)
def complete_predict(out, test_input):
complete_layer = get_model()
complete_layer.l... | This code processes an audio file to predict a digit. It resamples, pads, and chops the audio, generates a spectrogram, and uses a neural network to predict the digit from the spectrogram, returning the result with a hash identifier. | def digit_predict(filename, _hash):
global basepath
basepath = App.config['STORAGE_DIR']
K.clear_session()
# graph = tf.get_default_graph()
sample_rate, samples = wavfile.read(filename)
if len(samples.shape) > 1:
samples = samples[:,0]
resampled = signal.resample(samples, int(8000 / ... |
def verifyCredentials(username, password):
if not UserExist(username):
return generateReturnDictionary(301, 'Invalid username'), True
correct_pw = verifyPW(username, password)
if not correct_pw:
return generateReturnDictionary(302, 'Invalid password'), True
return None, False
def gener... | This code handles a POST request to process a user's deposit transaction. It validates user credentials, checks if the deposit amount is positive, deducts 1 unit from the amount, updates the user's and bank's account balances, and returns a success or error response accordingly. | def post(self):
postedeData = request.get_json()
username = postedeData['username']
password = postedeData['password']
money = postedeData['amount']
retJson, error = verifyCredentials(username, password)
if error:
return jsonify(retJson)
if money =... |
def verifyCredentials(username, password):
if not UserExist(username):
return generateReturnDictionary(301, 'Invalid username'), True
correct_pw = verifyPW(username, password)
if not correct_pw:
return generateReturnDictionary(302, 'Invalid password'), True
return None, False
def cashW... | This code handles a money transfer request by validating user credentials, checking sender's balance, verifying recipient existence, and updating account balances. It deducts funds from the sender, adds them to the recipient, and transfers 1 unit to the bank, returning appropriate JSON responses for success or errors. | def post(self):
postedeData = request.get_json()
username = postedeData['username']
password = postedeData['password']
to = postedeData['to']
money = postedeData['amount']
retJson, error = verifyCredentials(username, password)
if error:
return json... |
def verifyCredentials(username, password):
if not UserExist(username):
return generateReturnDictionary(301, 'Invalid username'), True
correct_pw = verifyPW(username, password)
if not correct_pw:
return generateReturnDictionary(302, 'Invalid password'), True
return None, False
def cashW... | This code handles a POST request to add a loan to a user's account. It retrieves JSON data containing username, password, and loan amount, verifies credentials, updates the user's cash and debt balances by adding the loan amount, and returns a success response if valid. | def post(self):
postedeData = request.get_json()
username = postedeData['username']
password = postedeData['password']
money = postedeData['amount']
retJson, error = verifyCredentials(username, password)
if error:
return jsonify(retJson)
cash = ca... |
def verifyCredentials(username, password):
if not UserExist(username):
return generateReturnDictionary(301, 'Invalid username'), True
correct_pw = verifyPW(username, password)
if not correct_pw:
return generateReturnDictionary(302, 'Invalid password'), True
return None, False
def cashW... | This code processes a payment request by verifying user credentials, checking sufficient cash balance, updating user's cash and debt, and returning JSON responses for success or errors. | def post(self):
postedeData = request.get_json()
username = postedeData['username']
password = postedeData['password']
money = postedeData['amount']
retJson, error = verifyCredentials(username, password)
if error:
return jsonify(retJson)
cash = ca... |
def check_flip(self, pos):
if (pos[0] > self.icon1_coords[0]) and (pos[0] < (self.icon1_coords[0]+self.icon1_s)):
if (pos[1] > self.icon1_coords[1]) and (pos[1] < (self.icon1_coords[1]+self.icon1_s)):
self.notes_flip()
def check_solve(self, pos):
if (pos[0] > self.icon2_coord... | The code handles mouse click events on a grid-based interface. It adjusts the mouse position by offsets, validates if the click is within the grid bounds, and determines the selected tile's coordinates. It returns `True` if valid, otherwise `False`, after checking for flip, solve, and theme actions. | def clicked(self):
pos = list(pygame.mouse.get_pos())
self.check_flip(pos)
self.check_solve(pos)
self.check_theme(pos)
pos[0] -= self.offw
pos[1] -= self.offh
if (pos[0] < 0) or (pos[0] > self.side):
return False
if (pos[1] < 0) or (pos[1] > s... |
def calculate_relative_start_date(dt, duration, partial_start_percentage, units):
offset = round(duration * (partial_start_percentage/100))
if units == 'days':
relative_start_date = date_by_adding_business_days(dt, offset)
return relative_start_date
if units == 'weeks':
return dt + d... | The code processes a CSV project schedule to calculate task start dates based on dependencies, constructs a timeline with metadata (project details, costs, durations), and outputs the structured data as a JavaScript file for visualization. | def build_timeline(filename, timeline_name):
DAY_RATE = 1500
#consume the csv
#filename = sys.argv[1]
chart_html_page = 'timeline.html'
df = pd.read_csv(filename)
units = df['units'][0]
project_start_date = parse(df['start_date'][0])
df['start_date'] = project_start_date
#
# ... |
def drift(self, pos):
assert pos >= self.linear_min
assert pos <= self.linear_max
p = np.copy(self.linear_zeros)
p[0, 3:7] = pos
self.linear_state = pos
self.linear.move_joint_position(p, 1.0)
time.sleep(0.01)
def primitive(self, id, mag=1.5 * np.pi, verbose=False... | This code tests motion control by applying a sequence of drift positions, executing 30 random primitive actions with fixed magnitude at each drift, then returning to a central position. It iterates through 5 drift steps, simulating motion testing under varying offsets. | def test_motion(self):
num_drifts = 5
for j in range(num_drifts):
self.drift(self.linear_range *
(j / (num_drifts - 1)) + self.linear_min)
for i in range(30):
id = np.random.randint(0, 9)
# mag = np.random.random_sample()
... |
def decimal_conversion(convertFrom, numberSystem):
try:
convertedNumber = ""
floatNumber = "." in convertFrom
convertFrom = float(convertFrom)
currentNumber = math.floor(convertFrom)
print("\nWhole Digits: ")
while currentNumber != 0:
remainder = currentN... | This code is a menu-driven number converter program that allows users to convert numbers between decimal, binary, octal, and hexadecimal bases. It prompts the user to select a base, choose a conversion type, and inputs a number to convert, using helper functions to perform the conversions. The program exits when the us... | def main():
print("\n\t\tNumber Converter Program\n")
print("\t\t[1] Decimal")
print("\t\t[2] Binary")
print("\t\t[3] Octal")
print("\t\t[4] Hexadecimal")
print("\t\t[5] Exit Program")
select = input("\nSelect Base Number: ")
if select == "5":
print("Thank You for using our pro... |
def decimal_conversion(convertFrom, numberSystem):
try:
convertedNumber = ""
floatNumber = "." in convertFrom
convertFrom = float(convertFrom)
currentNumber = math.floor(convertFrom)
print("\nWhole Digits: ")
while currentNumber != 0:
remainder = currentN... | The code provides a menu-driven interface for converting numbers between decimal, binary, octal, and hexadecimal systems. Users select a conversion option (e.g., decimal to binary), input the number, and the program uses helper functions to perform the conversion and display the result. It supports 12 conversion direct... | def number_system_converter():
print("1. Decimal to Binary")
print("2. Decimal to Octal")
print("3. Decimal to Hexadecimal")
print("4. Binary to Decimal")
print("5. Binary to Octal")
print("6. Binary to Hexadecimal")
print("7. Octal to Decimal")
print("8. Octal to Binary")
print("9. ... |
def fmt_value(val, options=None, desc=None, optarr=[]):
if type(val) != str:
if type(val) == bool:
val = str(val).lower()
elif desc and desc.enum_type:
val = desc.enum_type.values_by_number[val].name
val = str(val)
else:
val = '"%s"' % val.encode('unicode_... | The code parses a descriptor (likely from Protocol Buffers) into a formatted string representation, handling nested messages, enums, fields, and extensions. It recursively processes elements, constructs code blocks for each component, and returns the generated output with proper syntax, including message/enum definitio... | def parse_msg(desc, scopes, syntax):
out = ''
is_msg = isinstance(desc, DescriptorProto)
if is_msg:
scopes = list(scopes)
scopes[0] += '.' + desc.name
blocks = OrderedDict()
for nested_msg in (desc.nested_type if is_msg else desc.message_type):
blocks[nested_msg.nam... |
def init_test_game(self):
self.players_dict = {
"Uri": Player("Uri", Rahamim()),
"Salay": Player("Salay", Haim()),
"Tal": Player("Tal", FieldBarvaz()),
"Roee": Player("Roee", Lital()),
}
self.print_players()
def round(self):
for curr_playe... | The code manages a game loop where players compete in rounds until only one remains. It initializes the game, processes each round, ends rounds, and declares the winner when all other players are eliminated. | def game_manager(self):
# self.enter_menu()
self.init_test_game()
# self.rand_players()
while len(self.players_dict) > 1:
self.round()
self.end_round()
print(f"{list(self.players_dict.keys())[0]} is the Winner!!!!!!!! heydad!!!") |
def scatter(self, inputs, kwargs, device_ids):
return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim, chunk_sizes=self.chunk_sizes)
def replicate(self, module, device_ids):
return replicate(module, device_ids)
def parallel_apply(self, replicas, inputs, kwargs):
return parallel_apply(replicas, input... | This code implements distributed data parallelism by scattering inputs across devices, replicating the model on each device, processing in parallel, and gathering outputs. It checks device availability, handles single/multi-device cases, and returns aggregated results for efficient multi-GPU training. | def forward(self, *inputs, **kwargs):
if not self.device_ids:
return self.module(*inputs, **kwargs)
inputs, kwargs = self.scatter(inputs, kwargs, self.device_ids)
if len(self.device_ids) == 1:
return self.module(*inputs[0], **kwargs[0])
replicas = self.replicate(self.module, self.device_ids... |
def load_images(self):
pieces = ['wP', 'wR', 'wN', 'wB', 'wQ', 'wK', 'bP', 'bR', 'bN', 'bB', 'bQ', 'bK']
for piece in pieces:
IMAGES[piece] = pygame.transform.scale(pygame.image.load("images/" + piece + ".png"),
(SQUARE_SIZE, SQUARE_SIZE))
d... | This code runs a chess game loop using Pygame, handling user input (mouse clicks and quit events), updating the game state by selecting/moving pieces, and rendering the chessboard. The loop maintains a consistent frame rate and continues until the user exits. | def run(self):
# Game loop
running = True
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Chess")
clock = pygame.time.Clock()
# self.load_images()
while running:
# Handle events
self.load_images()
... |
def parse_arguments(args):
opt = {}
print('=> Reading config file and command line arguments')
config = ConfigParser()
config._interpolation = configparser.ExtendedInterpolation()
config.read(args.config)
# figure out which model we're working with
if args.option is not None:
confi... | The main task of the code is to train a deep learning model for a specific task, using GPU acceleration, optimizer configuration, and TensorBoard logging. It initializes the model, loads or sets up training data, resumes from checkpoints if specified, and iteratively trains the model while adjusting the learning rate a... | def main():
# get arguments and modify config file as necessary
args = parser.parse_args()
opt = parse_arguments(args)
# set gpu
print('=> setting gpu to {}'.format(opt['gpu']))
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = opt['gpu']
# tensorboard ... |
def normpath(path):
if path in normpath_cache:
return normpath_cache[path]
ret = os.path.normpath(path)
if os.name == 'nt':
ret = ret.lower().replace('\\', '/')
normpath_cache[path] = ret
return ret
def joinpath(cwd, path):
return path if path[0] == '/' else '%s/%s' % (cwd, p... | This function builds a target by recursively processing its dependencies, checking if it's up-to-date based on timestamps, creating necessary directories, and either enqueuing the task for parallel execution or running it immediately. It handles both regular and dependency-file (d-file) dependencies, ensuring correctne... | def build(target, options):
if target in visited or target in completed:
return
if target not in rules:
visited.add(target)
completed.add(target)
return
rule = rules[target]
visited.update(rule.targets)
if target in enqueued:
return
# Recursively handle t... |
def normpath(path):
if path in normpath_cache:
return normpath_cache[path]
ret = os.path.normpath(path)
if os.name == 'nt':
ret = ret.lower().replace('\\', '/')
normpath_cache[path] = ret
return ret
def joinpath(cwd, path):
return path if path[0] == '/' else '%s/%s' % (cwd, p... | This code parses command-line options for a build system, initializes a build context with rules from specified files, manages parallel execution using threads, builds targets according to defined rules, cleans stale outputs, and writes build state to make.db files. It handles error checking, progress tracking, and gra... | def main():
# Parse command line
parser = OptionParser(usage='%prog [options] target1_path [target2_path ...]')
parser.add_option('-c', dest='clean', action='store_true', default=False, help='clean before building')
parser.add_option('-f', dest='files', action='append', help='specify the path to a rules... |
def calcOddEven(self, roles):
"""If the score is odd then the score -= 5 otherwise += 10
Args:
roles ([type]): [description]
"""
if (roles[0] + roles[1]) & 1: # bitwise
self.score -= 5
else:
self.score += 10
def calcDouble(self, roles):
... | The main task of the code is to execute a series of calculation methods (`calcOddEven`, `calcDouble`, and `checkZero`) sequentially using the provided `roles` tuple as input. The `calcOverall` function acts as a utility to orchestrate these computations, likely preparing data or validating states for further processing... | def calcOverall(self, roles):
"""Utility function that runs all of the calculations
Args:
roles (tuple): contains both role values and can be indexed
"""
self.calcOddEven(roles)
self.calcDouble(roles)
self.checkZero() |
def get_contour_paths(self):
"""Get contour paths for all levels.
Returns the collection of contours as paths.
Also removes contour points outside of bounds and return as a
collection of numpy arrays.
Returns
-------
contour_paths : list
List of lis... | The code generates and visualizes laser contours for the Bay area by plotting contour and activity paths, saving figures as SVGs. It includes debug modes for detailed analysis, checks containment of activity paths, and creates a composite 'proof' visualization with layered patches and activity lines, outputting final p... | def laser_contours(self):
"""Laser contours for the entire Bay area.
"""
contour_paths, contour_vertices = self.get_contour_paths()
print("plotting contour vertices")
for cv, contour_level in enumerate(contour_vertices):
contour_fig = plt.figure(figsize=self.S.figs... |
def request_qanary_endpoint_for_question(logger, conf_qanary, question):
"""
request to Qanary endpoint that is defined within the configuration with a given question
Args:
conf_qanary ([type]): [description]
question ([type]): [description]
Returns:
[type]: [description]
"... | The main task of the code is to evaluate predefined tests by querying a Qanary system, validating results using SPARQL templates, and executing a custom validation function. It logs progress, measures execution time, and aggregates results for each test, including graph IDs and validation outcomes, returning structured... | def evaluate_tests(logger, conf_qanary, configuration_directory, validation_sparql_templates, custom_module, tests):
"""
evalute all tests defined in the configuration file, here only the request to the Qanary system is executed
Args:
logger ([type]): [description]
conf_qanary ([type]): [de... |
def create_printable_string(str):
return pprint.pformat(str, indent=20)
def determine_if_custom_module_is_callable(logger, custom_module):
"""
checks if the custom module contains a methode 'validate' with the demanded number of parameters
Args:
logger ([type]): [description]
custom_mod... | The main task of the code is to load test configurations from a JSON file, execute validation tests using a custom module (or a dummy module if unspecified), and export test results to JSON and Excel files. It logs configuration details, runtime, and results, handling SPARQL templates and test definitions specified in ... | def main(logger, sheet_name, configuration_directory, outdir, filename_prefix):
start = datetime.datetime.now()
test_configuration_file = configuration_directory + "/qanary-test-definition.json"
test_configuration = {}
with open(test_configuration_file) as json_file:
test_configuration = json.l... |
def _step(self):
self.live_points = self._live_points()
self.dead_points = self._dead_points()
to_live, to_die = set(), set()
for point in self.live_points:
neighbors = self.neighbors(point)
live_neighbors = len({neighbor for neighbor in neighbors if self.val(neighbor)})
if self._two_few_neighbors(l... | The main task of the code is to update the simulation state by processing live and dead points. The `tick` method calls `_step()` to determine which points should live or die, then iterates through these lists to apply the changes using `live()` and `die()` methods, effectively advancing the simulation's state in each ... | def tick(self):
to_live, to_die = self._step()
for point in to_live:
self.live(point)
for point in to_die:
self.die(point) |
def _step(self):
#self.live_points, self.dead_points = self._live_points(), self._dead_points()
self.live_points, self.dead_points = self._this_frame()
to_live, to_die = set(), set()
for point in self.live_points:
live_neighbors = self.neighbors(point)
if self._two_few_neighbors(live_neighbors):
to... | This code updates the game state by processing live and dead cells. It calls `_step()` to determine which points should survive or die, then applies these changes by invoking `live()` for surviving points and `die()` for dying points, effectively advancing the simulation to the next state. | def tick(self):
to_live, to_die = self._step()
for point in to_live:
self.live(point)
for point in to_die:
self.die(point) |
def self_plays(self):
self.self_moves(self.start_cell)
if self.board_solved():
if not self.user_solves:
print()
print("Here's the solution!")
self.show_board()
else:
print("No solution exists!")
def update_board(self, new_cu... | The main task of the code is to handle user interaction in a knight's tour game. It checks if the board is solved or if the user reached a dead end, displaying appropriate messages. If unsolved, it lets the user make moves iteratively until completion or termination, tracking visited cells and updating the board state ... | def user_plays(self):
self.self_plays()
if self.board_solved():
self.visited_cells.clear()
self.update_board(self.start_cell)
else:
return
while True:
self.show_board()
if self.board_solved():
print("What a grea... |
def user_sets_board_dimensions(self):
while True:
try:
numbers = input("Enter your board dimensions: ")
self.rows, self.columns = (
int(d) for d in re.match(self.input_matcher, numbers).groups()
)
if not (self.rows >... | The code's main task is to execute a game or puzzle-solving process by first setting up the board dimensions and start cell via user input, then determining whether the user or the program will solve the puzzle. If the user solves it, their moves are handled through `user_plays`; otherwise, the program autonomously sol... | def run(self):
self.user_sets_board_dimensions()
self.user_sets_start_cell()
self.user_or_self_solves()
if self.user_solves:
self.user_plays()
else:
self.self_plays() |
def netInitialisation(noInputs, noOutputs, noHiddenNeurons):
net = []
hiddenLayer = [Neuron([random() for i in range(noInputs + 1)]) for h in range(noHiddenNeurons)]
net.append(hiddenLayer)
hiddenLayer2 = [Neuron([random() for i in range(noInputs + 1)]) for h in range(noHiddenNeurons)]
net.append(hi... | The main task of the code is to train a neural network on provided training data and evaluate its accuracy on test data. It processes numerical inputs by converting string values to floats, initializes a neural network with determined input/output dimensions, trains it using specified parameters, and computes accuracy ... | def run(trainData, testData, learningRate, noEpochs):
test = []
train = []
for line in testData:
testline = []
for string in line[:-1]:
string = float(string)
testline.append(string)
testline.append(line[-1])
test.append(testline)
for line in train... |
def listen(self) -> None:
message_type = self.receive_type()
self.route(message_type)
def send_public_key(self) -> None:
self.send(MessageType.PUBLIC_KEY.value[0])
self.send_bytes(self.public_key.exportKey())
logger.debug(f"Sent public key {self.public_key.exportKey()}")
def send... | This code initializes a secure socket connection as either a server or client. It sets up a socket, binds/listens (server) or connects (client), exchanges RSA public keys, sends a session key, and starts a receiver thread for data handling. Key storage is performed if not reusing keys. The function logs connection esta... | def init_connection(self, ip: str, port: int, as_server: bool) -> None:
if as_server:
self.server = socket.socket()
self.server.bind((ip, port))
self.server.listen(1)
self.conn, _ = self.server.accept()
self.listen()
self.send_public_key()
... |
def send(self, data: bytes) -> int:
if self.conn:
return self.conn.send(data)
else:
logger.error("Couldn't sent data, because there is no client connection")
def send_mode(self, mode: str) -> None:
mode_in_bytes = bytes(mode, 'utf-8')
self.send_bytes_with_rsa(mode... | The function `send_file` securely transmits a file over a network using specified encryption modes (e.g., ECB/CBC). It encrypts the file name with RSA, sends the file size, reads and encrypts the file in chunks, pads data for AES compatibility, updates a progress bar, and logs transmission details. It handles file erro... | def send_file(self, file_path: str, mode: str, progressbar: QProgressBar = None) -> None:
self.send(MessageType.FILE.value[0])
self.send_mode(mode)
cipher = self.get_cipher_to_encrypt(mode)
file_name = os.path.basename(file_path)
file_name_in_bytes = bytes(file_name, 'utf-8')
... |
def send(self, data: bytes) -> int:
if self.conn:
return self.conn.send(data)
else:
logger.error("Couldn't sent data, because there is no client connection")
def send_mode(self, mode: str) -> None:
mode_in_bytes = bytes(mode, 'utf-8')
self.send_bytes_with_rsa(mode... | This function encrypts provided text using AES in specified modes (ECB/CBC), pads data if required, sends encrypted bytes, and logs encryption details. It converts text to bytes, applies padding for block ciphers, encrypts using the retrieved cipher, transmits results, and records debug/info logs for tracking encryptio... | def send_text(self, text: str, mode: str) -> None:
self.send(MessageType.TEXT.value[0])
self.send_mode(mode)
cipher = self.get_cipher_to_encrypt(mode)
text_in_bytes = bytes(text, 'utf-8')
if mode in ["ECB", "CBC"]:
text_in_bytes = pad(text_in_bytes, AES.block_size)... |
def shrink_poly(vertices, coef=0.3):
'''shrink the text region
Input:
vertices: vertices of text region <numpy.ndarray, (8,)>
coef : shrink ratio in paper
Output:
v : vertices of shrinked text region <numpy.ndarray, (8,)>
'''
x1, y1, x2, y2, x3, y3, x4, y4 = vertices
r1 = min(cal_distance(x1,y1,x2,... | This function generates score and geometry ground truth maps for text regions in an image. It processes input vertices and labels, scales them, creates binary masks, calculates rotated bounding box parameters (distances and angles), and outputs tensors for score_map, geo_map, and ignored_map. Ignored regions are marked... | def get_score_geo(img, vertices, labels, scale, length, ignore=True):
'''generate score gt and geometry gt
Input:
img : PIL Image
vertices: vertices of text regions <numpy.ndarray, (n,8)>
labels : 1->valid, 0->ignore, <numpy.ndarray, (n,)>
scale : feature map / image
length : image length
Output:
... |
def extract_vertices(lines):
'''extract vertices info from txt lines
Input:
lines : list of string info
Output:
vertices: vertices of text regions <numpy.ndarray, (n,8)>
labels : 1->valid, 0->ignore, <numpy.ndarray, (n,)>
'''
labels = []
vertices = []
for line in lines:
vertices.append(list(map(int,li... | This code processes image and ground truth data for text detection, applying transformations like scaling, rotation, and cropping. It ensures image-GT file consistency, generates score/geometry maps, and returns transformed images with these maps for model training. | def __getitem__(self, index):
with open(self.gt_files[index], 'r') as f:
lines = f.readlines()
vertices, labels = extract_vertices(lines)
img = Image.open(self.img_files[index])
#check that things match
img_addr = self.img_files[index]
gt_addr = self.gt_files[index]
img_split = img_addr.split('_')... |
def autoaddr(self):
for i in (32, 63):
try:
if self.i2c.readfrom(i, 1):
return i
except:
pass
raise Exception('I2C address detect error!')
def setcmd(self, cmd):
self.RS=0
self.send(cmd)
self.send(cmd<<4)... | This code initializes an I2C LCD display controller, configuring its function mode, display settings, and entry mode. It sets up control registers (BK, RS, E), sends initialization commands (0x33, 0x30, 0x20), configures display parameters (0x28, 0x0C, 0x06, 0x01), and prepares a 16-character buffer for text display. I... | def __init__(self, i2c, addr = 0x27):
self.i2c=i2c
self.buf = bytearray(1)
self.BK, self.RS, self.E = 0x08, 0x00, 0x04
self.ADDR = addr if addr else self.autoaddr()
self.setcmd(0x33)
sleep_ms(5)
self.send(0x30)
sleep_ms(5)
self.send(0x20)
s... |
def getCodeWords(self, msgrange, codewords):
codewords.clear()
for i in range(msgrange):
c = CRTCode(self.basis)
c.encode(i)
codewords.append(c)
return codewords
def CRT(vals, basis):
mm = 1
ans = 0
for i in range(len(basis)):
mm *= basis[i... | The code decodes a message using the Chinese Remainder Theorem (CRT), checking if the result fits within a specified range. If not, it identifies the closest codeword with the minimum Hamming distance and updates the message accordingly. The function returns True upon successful decoding, either via direct CRT computat... | def decode(self, m, msgrange):
assert len(self.basis) == len(self.vals)
codewords = [] # list of CRTCode class objects
codewords = self.getCodeWords(msgrange, codewords)
crtans = CRT(self.vals, self.basis)
if crtans < msgrange:
m.setInt(crtans)
return Tru... |
def get_producer(self, otio_item, audio_track=False):
"""
Get or create a producer element. Will prevent duplicates.
:param otio_item: OTIO object to base producer on
:param audio_track: If item stems from an audio track or not
:type audio_track: `bool`
:return: producer... | This function assembles an XML playlist structure from a track, handling media items, transitions, and nested tracks. It creates playlist entries for clips, gaps, and transitions, inserts audio/video elements appropriately, and recursively processes nested tracks. It also applies supported time effects and manages elem... | def assemble_track(self, track, track_index, parent):
playlist_e = et.Element(
'playlist',
id=track.name or 'playlist{}'.format(track_index)
)
self.playlists.append(playlist_e)
# Transitions use track elements as children
element_type = 'track'
#... |
def create_profile_element(self):
profile_e = et.Element(
'profile',
decsription='automatic'
)
return profile_e
def update_profile_element(self, profile_element, profile_data):
if isinstance(profile_data, otio.opentime.RationalTime):
fractional = self... | The code generates an MLT XML structure from OTIO data by creating a profile element, constructing tracks based on input type (Timeline/Track/Clip), assembling the timeline, inserting producers, transitions, playlists, and the profile into a root element, then rendering the XML with proper formatting. | def create_mlt(self):
profile_e = self.create_profile_element()
if self.profile_data:
self.update_profile_element(profile_e, self.profile_data)
if isinstance(self.input_otio, otio.schema.Timeline):
tracks = self.input_otio.tracks
if self.input_otio.global_sta... |
def dynamic_reaction_rr(self, status):
out = self.weight - self.dynamic_reaction_fr(0)
if status == 0:
return out
elif status == 1:
self.plot_graph_show(self.d, out, 'distance from rear axle [m]', 'reaction on rear axle [N]')
elif status == 2:
self.plot_graph_save(self.d, out, 'distance from rear axle ... | This function calculates the maximum potential braking torque for the rear axle using dynamic reaction, multiplication factors (u, r), and returns or visualizes the results based on the input status: returning values, plotting graphs, saving images, or printing outputs. | def max_potential_braking_torque_rr(self, status):
out = self.dynamic_reaction_rr(0) * self.u * self.r
if status == 0:
return out
elif status == 1:
self.plot_graph_show(self.d, out, 'distance from rear axle [m]', 'max potential torque without tire-slip on rear axle [Nm]')
elif status == 2:
self.plot_gr... |
def max_potential_braking_torque_fr(self, status):
out = self.dynamic_reaction_fr(0) * self.u * self.r
if status == 0:
return out
elif status == 1:
self.plot_graph_show(self.d, out, 'distance from rear axle [m]', 'max potential torque without tire-slip on front axle [Nm]')
elif status == 2:
self.plot_g... | This function calculates the maximum real braking force for the front axle by adjusting the potential braking torque values based on thresholds (self.tbf and 0), then returns, plots, saves, or prints the results depending on the input 'status' | def max_real_braking_force_fr(self, status):
out = self.max_potential_braking_torque_fr(0)
for i in range(0, len(out)):
if out[i] >= self.tbf:
out[i] = self.tbf / self.r
elif out[i] <= 0:
out[i] = 0
else:
out[i] = out[i] / self.r
if status == 0:
return out
elif status == 1:
self.plo... |
def generate_directory(self):
params = 'l = '+str(self.l[self.i])+'\nh = '+str(self.h[self.i])+'\nr = '+str(self.r[self.i])+'\ntbf = '+str(self.bff[self.i])+'\ntbb = '+str(self.bfb[self.i])+'\nu = '+str(self.u[self.i])+'\nm = '+str(self.m[self.i])
self.work_dir = os.path.join(self.filepath, self.name[self.i])
os.... | This function generates simulation data by iterating through velocity values, calculating braking forces and motion parameters (acceleration, velocity, distance), and saving results to CSV files. It simulates deceleration dynamics, updates physical variables, and resets counters for each velocity iteration, producing t... | def generate_data(self):
for v_w in self.v:
ff, fb, fn = 0, 0, 0
self.generate_directory()
v = v_w
self.d = self.l[self.i] * (-0.25)
while self.d < self.l[self.i] - 0.2:
path = os.path.join(self.work_dir, 'data', str('{0:.2f}'.format(self.d)) + '.csv')
with open(path, 'w') as f:
csv_wr = c... |
def max_potential_braking_torque_rr(self, status):
out = self.dynamic_reaction_rr(0) * self.u * self.r
if status == 0:
return out
elif status == 1:
self.plot_graph_show(self.d, out, 'distance from rear axle [m]', 'max potential torque without tire-slip on rear axle [Nm]')
elif status == 2:
self.plot_gr... | This function calculates the maximum real braking force on the rear axle by adjusting potential braking torque values. It limits values exceeding a threshold (tbb) and scales all values by a radius factor (r). Depending on the 'status' input, it returns results, plots graphs, saves images, or prints values for analysis... | def max_real_braking_force_rr(self, status):
out = self.max_potential_braking_torque_rr(0)
for i in range(0, len(out)):
if out[i] >= self.tbb:
out[i] = self.tbb / self.r
elif out[i] <= 0:
out[i] = 0
else:
out[i] = out[i] / self.r
if status == 0:
return out
elif status == 1:
self.plot... |
def max_real_braking_force_fr(self, status):
out = self.max_potential_braking_torque_fr(0)
for i in range(0, len(out)):
if out[i] >= self.tbf:
out[i] = self.tbf / self.r
elif out[i] <= 0:
out[i] = 0
else:
out[i] = out[i] / self.r
if status == 0:
return out
elif status == 1:
self.plo... | This function calculates the maximum real braking force by summing front and rear axle values, then handles output based on status: returns the value, displays a graph, saves it as an image, or prints individual elements. | def max_real_braking_force_net(self, status):
out = self.max_real_braking_force_fr(0) + self. max_real_braking_force_rr(0)
if status == 0:
return out
elif status == 1:
self.plot_graph_show(self.d, out, 'distance from rear axle [m]', 'max braking torque without tire-slip on rear axle [N]')
elif status == ... |
def max_real_braking_force_net(self, status):
out = self.max_real_braking_force_fr(0) + self. max_real_braking_force_rr(0)
if status == 0:
return out
elif status == 1:
self.plot_graph_show(self.d, out, 'distance from rear axle [m]', 'max braking torque without tire-slip on rear axle [N]')
elif status == ... | The code calculates deceleration by dividing the maximum real braking force (from `max_real_braking_force_net`) by mass (`self.m`). Depending on the `status` input, it either returns the deceleration value, plots a graph of deceleration vs. distance, saves a graph of braking torque, or prints the deceleration values. T... | def deceleration(self, status):
out = self.max_real_braking_force_net(0) / self.m
if status == 0:
return out
elif status == 1:
self.plot_graph_show(self.d, out, 'distance from rear axle [m]', 'deceleration [m/s^2]')
elif status == 2:
self.plot_graph_save(self.d, out, 'distance from rear axle [m]', 'max... |
def load_plugins_from_DB(self):
try:
connection = get_config_db()
connection.row_factory = sqlite3.Row
cur = connection.cursor()
cur.execute("SELECT * FROM plugins")
plugins = cur.fetchall()
for plugin in plugins:
self.plu... | This code initializes a plugin system for a Flask application by loading plugins from a database, ensuring their presence, registering them, and updating checks. It sets the plugin directory, imports plugins, and configures the app's plugin path for dynamic extension management. | def __init__(self, app: Flask, plugins_dir=str):
self.app = app
self.plugins_dir = plugins_dir
self.def_plugins_dir = "plugins"
self.plugins: Dict[str, Plugin] = {}
self.load_plugins_from_DB()
self.remove_missing_plugins()
self.app.plugin_path = plugin_path
... |
def mask_image(img, mask_top_width=145, x_offset=20, y_offset=40, dst_offset=200):
imshape = img.shape
# Calculate mask height
img_y_mid = imshape[0] * 0.5
mask_height = int(img_y_mid * 1.25)
img_x_mid = int(imshape[1] * 0.5)
top_left = [img_x_mid - mask_top_width * 0.5, mask_height]
top_rig... | The function processes an undistorted image to generate a binary representation, applies perspective transformation to warp the binary image, and returns the warped result. Debug mode enables visualization of the binary and warped images. | def binary_wrap_img(undist, overdrive=False, debug=False):
src, dst = mask_image(undist)
binary, color_binary = image_process(undist, overdrive)
img_size = (undist.shape[1], undist.shape[0])
warped = perspective_transform(binary)
if debug:
f = plt.figure()
f, (ax1, ax2) = plt.subp... |
def check_file_exists(xml_file):
if not os.path.isfile(xml_file):
print(f"File {xml_file} does not exist")
return False
return True
def list_entries(xml_file):
# parse the xml file into an ElementTree objects
tree = ET.parse(xml_file)
# get the root of the tree
root = tree.getroo... | This script parses command-line arguments to update an XML file's GlideinBenchmark entries, enabling, disabling, or removing them based on flags. It supports listing entries, checking statuses, and handling global entries. The XML is modified accordingly, with priority given to removal over disable/enable actions. | def main():
# parse the command line arguments
parser = argparse.ArgumentParser(
prog="GlideinBmk Factory Parser",
description="Update the xml file with the given entry names and run_bmk_value",
)
parser.add_argument(
"-d",
"--disable",
action="store_true",
... |
def MLE(self):
if self.tag_loc is None:
#self.Z_MLE=np.array([ [0], [0] ])
#return
self.recalculate_dis(self.pathloss_loc['lon'],self.pathloss_loc['lat'])
self.distance=self.distance_temp.copy()
#print(self.distance)
A=[]
b=[]
... | The code implements a particle swarm optimization (PSO) algorithm to estimate a location using BLE data. It initializes particles, iterates through optimization steps, validates positions, updates particle positions, and returns the best estimated location and distances in JSON format. | def estimate(self):
self.MLE()
#generate swarm
for k in range(0,self.Number_Of_Swarm,1):
particle=Particles(self.Confined_Area_Radius, self.Z_MLE)
self.swarm.append(particle)
#start timer
#t = time.time()
step = 0
middle=(int)(len(self.... |
def MLE(self):
A=[]
b=[]
for index in range(0,len(self.distance),1):
ref = self.distance[index]
num_ref = ref[0]
for k in range(0,len(self.distance),1):
temp = self.distance[k]
num = temp[0]
A1 = 2*(self.node_loc... | The code implements a particle swarm optimization (PSO) algorithm to estimate coordinates. It initializes a swarm of particles based on MLE results, iterates through optimization steps to update particle positions, and returns the best estimated latitude/longitude from the swarm's optimal solution after completing iter... | def estimate(self):
self.tmp=0
self.MLE()
#generate swarm
for k in range(0,self.Number_Of_Swarm,1):
particle=Particles(self.Confined_Area_Radius, self.Z_MLE)
self.swarm.append(particle)
step = 0;
while step < self.Iteration:
step = st... |
def defaultSessionIfNotSet(session_attributes:dict):
"""Returns a session with default information for this skill if session_attributes is empty."""
global default_session
for key, value in default_session.items():
if key not in session_attributes:
#print(key+" not found! Setting to "+s... | This function resumes playback of the last episode a user was listening to by retrieving stored session data. It checks if a previous episode exists; if not, it prompts the user to specify another. If an episode exists, it fetches the episode details and initiates playback with the saved progress offset. The function m... | def handleResumeIntent(intent,session):
session_attributes = session['attributes'] if 'attributes' in session else {}
session_attributes = defaultSessionIfNotSet(session_attributes)
lp=getLastPlaying(session['user']['userId'])
if lp == None:
return build_response(session_attributes,build_speechl... |
def defaultSessionIfNotSet(session_attributes:dict):
"""Returns a session with default information for this skill if session_attributes is empty."""
global default_session
for key, value in default_session.items():
if key not in session_attributes:
#print(key+" not found! Setting to "+s... | This function handles playing the latest radio episode by retrieving the first item from AIO.getRadioEpisodes(), updating the session with the episode as 'lastPlayed', and returning a response to start playback with the episode's URL and name. It ensures session attributes are initialized, sets playback to end after th... | def handlePlayLatestIntent(intent, session):
session_attributes = session['attributes'] if 'attributes' in session else {}
session_attributes = defaultSessionIfNotSet(session_attributes)
should_end_session=True
e=AIO.getRadioEpisodes()[0]
session_attributes.update({'lastPlayed':e})
return build_... |
def defaultSessionIfNotSet(session_attributes:dict):
"""Returns a session with default information for this skill if session_attributes is empty."""
global default_session
for key, value in default_session.items():
if key not in session_attributes:
#print(key+" not found! Setting to "+s... | The function selects a random episode from combined radio and free episode lists, updates session attributes with the last played episode, and returns a response to start playback with the episode's title and URL, ending the session. | def handlePlayAnyIntent(intent, session):
card_title="Play Random Episode Failed"
session_attributes = session['attributes'] if 'attributes' in session else {}
session_attributes=defaultSessionIfNotSet(session_attributes)
should_end_session=True
e=random.choice(AIO.getRadioEpisodes()+AIO.getFreeEpis... |
def defaultSessionIfNotSet(session_attributes:dict):
"""Returns a session with default information for this skill if session_attributes is empty."""
global default_session
for key, value in default_session.items():
if key not in session_attributes:
#print(key+" not found! Setting to "+s... | This function handles playing an episode by number from either radio or free sources. It retrieves the episode using the provided number, updates session attributes, and returns a response with the play URL. If the episode isn't found, it provides an error message and resets session flags. | def handlePlayByNumberIntent(intent, session):
card_title="Play Episode {} Failed"
session_attributes = session['attributes'] if 'attributes' in session else {}
session_attributes = defaultSessionIfNotSet(session_attributes)
should_end_session = True
if 'EpisodeNumber' in intent['slots'] and 'val... |
def defaultSessionIfNotSet(session_attributes:dict):
"""Returns a session with default information for this skill if session_attributes is empty."""
global default_session
for key, value in default_session.items():
if key not in session_attributes:
#print(key+" not found! Setting to "+s... | The function handles playing an episode by name, checking session attributes to determine the source (Radio/Free), searches for the episode, updates session data with the last played episode, and returns a play response or error if not found. It manages session state, error handling, and constructs appropriate speech/o... | def handlePlayByNameIntent(intent, session):
card_title = "Play Episode: {} Failed"
session_attributes=session['attributes']
session_attributes=defaultSessionIfNotSet(session_attributes)
should_end_session = True
if 'EpisodeName' in intent['slots'] and 'value' in intent['slots']['EpisodeName']:
... |
def savePlaybackOffset(userId, audioToken, offset:int):
"""Writes the current playback timestamp to the DynamoDB table with the name stored in const SESSION_TABLE_NAME."""
global REGION_NAME, SESSION_TABLE_NAME
conn=boto3.resource('dynamodb',region_name=REGION_NAME)
table=conn.Table(SESSION_TABLE_NAME)
... | This Lambda function handles Alexa requests by routing events like Launch, Intent, and SessionEnded to respective handlers. It validates the application ID, processes playback stop events to save user progress, and ensures secure request handling for an Alexa skill. | def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
#Respond to special requests
if event['request']['type'] == "AudioPlayer.PlaybackStopped":
return savePl... |
def get_best_locations(self, df, nums, type): # sourcery skip: avoid-builtin-shadow
max = 0
for i in range(df.shape[0]):
for j in range(df.shape[0]):
td = math.dist(df.iloc[i, 1], df.iloc[j, 1])
if i != j and td > max:
max = td
p... | The main task of the code is to determine optimal locations for departments of varying sizes (big, medium, small) sequentially, ensuring non-overlapping placement. It first identifies best locations for "big" departments, then for "medium" departments avoiding big locations, followed by "small" departments avoiding bot... | def solution(self, department, nums_big, nums_medium, nums_small):
big = self.get_best_locations(
self.prepare_and_fitness_big(department), nums_big, "big"
)
medium = self.get_best_locations(
self.prepare_and_fitness_medium(department, big[2]), nums_medium, "medium"
... |
def get_cash_flow(self):
url = "https://finance.yahoo.com/quote/{tiker}/cash-flow?p={tiker}"
url = url.format(tiker=self.tiker)
return self.scrape_table(url), url
def get_balance_sheet(self):
url = "https://finance.yahoo.com/quote/{tiker}/balance-sheet?p={tiker}"
url = url.form... | The code scrapes financial data (cash flow, balance sheet, income statement) for a given stock ticker, structures the extracted data into a DataFrame with columns for ticker, statement type, row labels, values, and URLs, and appends this data while updating an index counter. It handles exceptions during data insertion ... | def scrap(self,tiker):
self.tiker = tiker
df = self.df
i = self.i
result = {}
result["cash"], url = self.get_cash_flow()
result["balance"], url = self.get_balance_sheet()
result["finance"], url = self.get_financial()
cash = "Cashflow Statement"
bal... |
def _parse_data_string(self, data_string: str) -> List:
"""
Parses data from broker and returns day, timestamp,
generated value from meter.
"""
meter_day, meter_iteration, meter_reading = data_string.split(
self._delimiter)
return [int(meter_day), int(meter_it... | This callback function processes incoming meter data messages by decoding and splitting the payload into commands (START, DATA, END). It logs received data, validates meter readings against thresholds, generates PV values, writes valid records to files, handles file renaming, creates plots, and logs execution times for... | def _callback(self, ch, method, properties, body):
"""
Callback function for receiving meter's value.
"""
logging.info(f"PV: Received message {body}")
data_from_broker = body.decode("utf-8")
command_meter, value = data_from_broker.split("::")
if command_meter == ... |
def _connect_broker(self):
"""
Connects to broker and returns channel.
"""
logging.info("Meter: Connecting to broker: %s", self._broker_host)
try:
self._connection = pika.BlockingConnection(
pika.ConnectionParameters(host=self._broker_host,
... | The main task of the code is to simulate a meter device that connects to a broker, sending "START" signals, generating and transmitting meter data in iterations as "DATA" messages, and concluding with "END" signals, repeating this process daily with a 3-second interval between cycles. It handles keyboard interrupts to ... | def start(self):
"""
Coneects to broker and starts meter simulator.
"""
logging.info("Meter: Connecting to broker: %s", self._broker_host)
channel = self._connect_broker()
if channel is not None:
self._current_day = 0
while True:
d... |
def random_cipher():
return {k: v for k, v in zip(chars, shuffle(chars))}
def sort(s):
s2 = list(s)
s2.sort()
return "".join(s2)
def decode(pattern, cipher):
return multireplace(pattern, cipher)
def to_digit(pattern, cipher):
return alphabet[sort(decode(pattern, cipher))] | The code attempts to decrypt an encoded output by generating random ciphers, decoding patterns using each cipher, and checking if all decoded patterns correspond to valid characters in a predefined alphabet. Once a valid cipher is found, it converts the output into digits using that cipher and returns the resulting int... | def crack(pattern, output):
while True:
cipher = random_cipher()
decoded_patterns = [sort(decode(p, cipher)) for p in pattern]
if np.all([p in alphabet.keys() for p in decoded_patterns]):
print(f"found cipher: {cipher}")
digits = ''.join([to_digit(o, cipher) for o in ... |
def down_sampling(x, size, filters, kernel_size):
new_size = [size[0], size[1]]
if size[0] % 2 != 0:
x = reflection_padding(x, [1, 0])
new_size[0] = size[0] + 1
if size[1] % 2 != 0:
x = reflection_padding(x, [0, 1])
new_size[1] = size[1] + 1
size = new_size
x, size = ... | The code defines a custom convolutional neural network model with downsampling, skip connections, and upsampling layers. It constructs an encoder-decoder architecture, processing input images through alternating downsampling and upsampling stages, incorporating skip connections to retain spatial information. The model ... | def define_model(num_u, num_d, kernel_u, kernel_d, num_s, kernel_s, height, width, inter, lr,
input_channel=32, out_channel=3):
depth = len(num_u)
size = [height, width]
inputs = Input(shape=(height, width, input_channel))
x = inputs
down_sampled = []
sizes = [size]
for i... |
def show_start_screen():
title_font = font.Font(None, 100)
text_1 = title_font.render("Wormy!", True, WHITE, DARKGREEN)
text_2 = title_font.render("Wormy!", True, GREEN)
deg_1 = 0
deg_2 = 0
while True:
SCREEN.fill(BGCOLOR)
rotate_text_1 = transform.rotate(text_1, deg_1)
... | The main task of the code is to initialize a Pygame-based game ("Wormy") by setting up the display, clock, and font, then repeatedly running the game loop and displaying start/game-over screens. It uses global variables for shared resources and relies on external functions (`show_start_screen`, `run_game`, `show_game_o... | def main():
# noinspection PyGlobalUndefined
global CLOCK, SCREEN, BASICFONT
pygame.init()
CLOCK = time.Clock()
SCREEN = display.set_mode((WIDTH, HEIGHT))
BASICFONT = font.Font("freesansbold.ttf", 18)
display.set_caption("Wormy")
show_start_screen()
while True:
run_game()
... |
def goto_pos(pos, wait=0, s_speed=260000):
xyz['old_pos'] = load_pos()
delta = [pos[0]-xyz['old_pos'][0], pos[1]-xyz['old_pos'][1], pos[2]-xyz['old_pos'][2], pos[3]-xyz['old_pos'][3]]
xyz['last_pos'] = [pos[0], pos[1], pos[2], pos[3]]
xyz['logger'].debug(f"goto_pos: cur: {xyz['old_pos']}")
xyz['logg... | The code detects and sets the origin for multiple motors by moving to predefined positions, configuring motor registers to establish origins, disabling limit switches, and updating positional data. It performs iterative motor origin calibration, logs progress, and adjusts system parameters for accurate positioning. | def detect_origin():
xyz['logger'].info(f'detecting origin, please wait...')
goto_pos([2, 2, -2, 30], 100, 100000)
goto_pos([-315, -265, 110, -375], 100, 50000)
for i in range(5):
xyz['logger'].info(f'motor set origin: #{i+1}')
rx = cd_reg_rw(f'80:00:0{i+1}', 0x00b1, struct.pack("<B", 1)... |
def load_pos(mask=0xf):
pos = [None, None, None, None]
#xyz['logger'].info(f'motor read pos')
retry_cnt = 0
while True:
xyz['sock'].clear()
tx_num = 0
rx_num = 0
if mask & 1:
xyz['sock'].sendto(b'\x00'+struct.pack("<H", 0x0100) + struct.pack("<B", 4), ('80:00:... | The main task of the code is to initialize the XYZ system by setting up logging, network sockets, and motor controls. It checks motor enable status via register reads, enables motors, and triggers origin detection if any motor is not properly enabled. | def xyz_init():
xyz['logger'] = logging.getLogger('pnp_xyz')
xyz['sock'] = CDNetSocket(('', 0xcdcd))
xyz['sock_dbg'] = CDNetSocket(('', 9))
_thread.start_new_thread(dbg_echo, ())
xyz['last_pos'] = load_pos()
all_enable = True
for i in range(5):
rx = cd_reg_rw(f'80:00:0{i+1}', 0x... |
def _remove_wall(self, x, y, direc : (int, int)):
cell = self.matrix[x][y]
cell2 = self._get_next_cell(cell, direc)
cell.walls[direc] = False
if cell2 != None:
cell2.walls[tuple(i * (-1) for i in direc)] = False
def _board_is_visited(self):
for l in self.matrix:
... | This function generates a maze using a depth-first search algorithm with backtracking. It starts at the top-left cell, removes walls to connect unvisited neighboring cells, builds a tree structure to track paths, and ensures all cells are visited. The stack enables backtracking when no unvisited neighbors remain, and t... | def generate_maze(self, timeout=0):
self._remove_wall(0, 0, TOP)
self._remove_wall(self.width - 1, self.height - 1, BOTTOM)
current_cell = self.matrix[0][0]
current_cell.visited = True
self.tree = Tree()
self.tree.create_node(tag=f"{current_cell.x},{current_cell.y}",
... |
def init_random_seed(seed: int):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
def create_fsdp_config():
"""Return a dict with configurations required for `model_name` model."""
fsdp_config = {"lr": 1e-3, "epochs": 2}
fsdp_config["criterion"] = torch.nn.CrossEntropyL... | This code benchmarks a model using FSDP (Fully Sharded Data Parallel) across multiple GPUs. It initializes a distributed process group, configures FSDP with options like SSD offload, mixed precision, and auto-wrapping, wraps the model, and runs either a dry run or full benchmark based on flags. The goal is to evaluate ... | def dummy_fsdp(rank, args, world_size):
"""Benchmark a given model using a single process and multiple devices."""
init_method_pgroup = "tcp://localhost:{}".format(RPC_PORT)
torch.distributed.init_process_group(
backend="nccl", rank=rank, world_size=world_size, init_method=init_method_pgroup
)
... |
def plot_equity_curve(self, fname='equity_curve.png'):
""" Plots equity curve to png file
"""
curve = self.get_equity_curve()
buynhold = self.get_buynhold_curve()
xrnge = [curve.index[0], curve.index[-1]]
dotted = pd.Series(data=[100, 100], index=xrnge)
fig, ax = ... | The main task of the code is to generate an HTML report containing equity and return curves, along with performance metrics. It saves plot figures as PNGs, loads a Jinja2 template, combines header data, performance stats, and image URLs into a dictionary, then renders the template with this data to produce the final HT... | def generate_html(self):
""" Returns parsed HTML text string for report
"""
basedir = os.path.abspath(os.path.dirname(__file__))
images = os.path.join(basedir, 'report_templates')
eq_curve = os.path.join(images, 'equity_curve.png')
rt_curve = os.path.join(images, 'return_... |
def low_detail_assign(floors, parameters):
"""Assigns lower detail environments. Additionally, redistributes top floor of remainders then deletes it.
With these, transmission while on the move is not examined."""
values = unpack(floors, parameters)
for i in range(floors):
assign_environs(values... | This function generates a detailed 3D environment model by creating a base structure, adding hallways, and assigning rooms to floors. When 'low_detail' is False, it constructs a high-fidelity model, converts it to an image, and iterates through floors to place rooms using start positions. The process involves initializ... | def enviro_gen(low_detail,floors, **parameters):
"""Generates environment"""
low_detail_assign(floors, parameters)
if low_detail == False:
model_low_detail = represent()[0]
temp_model = base_model_creation()
temp_model = hallway_maker(temp_model)
represent_as_image(temp_model... |
def walk_collections(node):
for item in node:
if item.tag == 'collection':
yield item
for collection in walk_collections(item):
yield collection
def call_flickr(flickr, name, **kwargs):
global api_count, api_calls
api_count = api_count + 1
if not name in a... | This method builds lists of Collection and PhotoSet objects by fetching data from Flickr, checking if they exist in the database, and creating/saving them if they don't. It populates self.collections with Collection instances and self.sets with PhotoSet instances, ensuring database records are up-to-date with Flickr da... | def build_lists(self):
# Build a list of all collections
self.collections = []
for collection in walk_collections(call_flickr(self.flickr, 'collections_getTree').find('collections')):
dbcollection = None
try:
dbcollection = Collection.objects.get(collectio... |
def build_method(prefix, suffix, thing, args):
if type(thing) == PhotoStream:
name = 'Photostream'
elif type(thing) == PhotoSet:
name = 'Photoset'
args['photoset_id'] = thing.set_id
elif type(thing) == Collection:
name = 'Collection'
args['collection_id'] = thing.coll... | The code retrieves domain statistics from Flickr using a specified method, processes each domain to store its name and type ("O") in a dictionary, and then calls a method to fetch referers for each domain. | def get_domains(self, thing):
args = {
'date': self.date
}
method = build_method('stats_get', 'Domains', thing, args)
results = walk_results(self.flickr, method, **args)
for domain in results:
dbdomain = {
'name': domain.attrib['name'],
... |
def build_method(prefix, suffix, thing, args):
if type(thing) == PhotoStream:
name = 'Photostream'
elif type(thing) == PhotoSet:
name = 'Photoset'
args['photoset_id'] = thing.set_id
elif type(thing) == Collection:
name = 'Collection'
args['collection_id'] = thing.coll... | The code retrieves statistics (views, comments, favorites) for a specified 'thing' from Flickr's API using a given date, parses the XML response, and stores the data via `add_stats` method. | def get_stats(self, thing):
args = {
'date': self.date
}
method = build_method('stats_get', 'Stats', thing, args)
result = call_flickr(self.flickr, method, **args).find('stats')
visits = result.attrib['views'] or 0
comments = 0
if 'comments' in result... |
def _clean_attributes(self) -> None:
parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse(self._gpx_file, parser)
xslt = etree.fromstring(utils.get_resource("/xslt/stylesheet.xslt", decode=True))
tree = tree.xslt(xslt)
root = tree.getroot()
# Single occu... | This function modifies a GPX file by applying user-specified settings: cleaning unused nodes, adding XML schemas, simplifying track points to reduce size, and inserting elevation data. It conditionally executes helper methods based on boolean parameters, then sets final attributes and saves the updated GPX file. | def set_gpx_details(self, clean_headers, clean_attributes, elevation, simplify):
"""Set many attributes to a gpx file.
:param clean_attributes: Remove specific unused nodes
:type clean_attributes: bool
:param clean_headers: Add xsd schemas
:type clean_headers: bool
:para... |
def freeslots(self):
frees = {}
slot_number = Dropzone.get_by_id(self.dropzone_key).default_slot_number
if slot_number:
for load in self.loads:
free = slot_number - len(self.slot_mega[load.key.id()])
frees.update({load.key.id(): free})
return f... | This function handles manifest actions (add/delete) based on load status and availability. For 'add', it checks if the load is in WAITING/HOLD status, verifies slot availability, and ensures the jumper is current before adding a manifest. For 'delete', it removes manifests only if the load is in WAITING/HOLD, otherwise... | def manifest_action(self, action, load, registration):
message = {}
slot_size = self.freeslots()
if action == "add":
if load.status in [WAITING, HOLD]:
if slot_size[load.key.id()] > 0:
if registration.current == CURRENT:
mes... |
def check_keydown_events(event,s,screen,ship,bullets):
"""Respond to keypresses."""
if event.key==pygame.K_RIGHT:
ship.moving_right=True
elif event.key==pygame.K_LEFT:
ship.moving_left=True
elif event.key==pygame.K_SPACE:
fire_bullet(s,screen,ship,bullets)
elif event.key==pyg... | The function `check_events` processes user inputs in a Pygame game, handling keyboard presses/releases, mouse clicks, and quit events. It exits the game on QUIT, triggers ship movement/shooting via KEYDOWN/KEYUP, and checks if the play button is clicked (via MOUSEBUTTONDOWN), passing mouse coordinates and game objects ... | def check_events(s,screen,stats,sb,play_button,ship,aliens,bullets):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
elif event.type==pygame.KEYDOWN:
check_keydown_events(event,s,screen,ship,bullets)
... |
def check_fleet_edges(s,aliens):
"""Respond if aliens reach edge"""
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(s,aliens)
break
def check_aliens_bottom(s,screen,stats,sb,ship,aliens,bullets):
"""Check if alien reach bottom"""
screen_rect=... | The function `update_aliens` updates alien behavior in a game. It checks if aliens reach screen edges, updates their positions, detects aliens hitting the bottom of the screen, checks for collisions between the ship and aliens, and triggers a response (via `ship_hit`) if a collision occurs. Parameters include game obje... | def update_aliens(s,screen,stats,sb,ship,aliens,bullets):
"""Check if edge and then update the positions of all aliens in the fleet"""
check_fleet_edges(s,aliens)
aliens.update()
#Look for aliens hitting the bottom of the screen
check_aliens_bottom(s,screen,stats,sb,ship,aliens,bullets)
#Look f... |
def _delete_value_in_brackets(string: str) -> str:
open_bracket = '('
index_bracket = string.find(open_bracket)
index_space_before_bracket = index_bracket - 1
return string[:index_space_before_bracket]
def get_link_on_artist(artist_name: str) -> str:
return _get_rocknation_artist_link(artist_name)
... | This function retrieves the URL of a specific album by an artist. It cleans the album name, fetches the artist's page, searches for the album link in the HTML, and returns it. If not found, it raises an exception or returns None based on the `raise_exception` flag. | def get_link_on_album(artist_name: str, album_name: str, raise_exception=True) -> str:
album_name = _delete_value_in_brackets(album_name)
link_on_artist = get_link_on_artist(artist_name)
html = _get_html(link_on_artist)
link_on_album = _find_link_on_album(html, album_name)
if link_on_album is Non... |
def get_auth_app_urls(self):
"""
Generates the authentication app urls. You can replace it based on
you auth app.
Here, we have login and logout, profile detail and update, password change and reset.
"""
urlpatterns = [
url(r'^login/$', views.accounts.LoginVi... | This code generates Django admin URL patterns by aggregating index, authentication, site-wide (e.g., i18n JS, object shortcuts), and app-specific URLs. It checks dependencies in debug mode, uses registry for views, and returns a urlpatterns list for admin routing. | def get_urls(self):
""" Main method to generate admin urlpatterns """
from django.conf.urls import url, include
from django.contrib.contenttypes import views as contenttype_views
if settings.DEBUG:
self.check_dependencies()
# Admin Index
urlpatterns = [url(r... |
def seed(self, seed=None):
print("setting seed")
self.np_random, seed = seeding.np_random(seed)
print("seed set to:", seed)
return [seed]
def Init(self):
self.window_width = 512
self.window_height = 750
self.reset()
self.x = (sel... | The code initializes a CarGame environment for reinforcement learning, setting up parameters like observation/action spaces, reward tracking, and GUI rendering. It prepares the game state, enables human player interaction if specified, and initializes core components for training or simulation. | def __init__(self, render=True, human_player=True):
super(CarGame, self).__init__()
self.GUI_created = False
self.human_player = human_player
# gym/RL related variables
self.np_random = 0
self.done = False
self.seed... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.