dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def render(self, force=False):
if self.visualizer is not None:
with self.debug_tiles(self.agent.current_level().walkable, color=(0, 255, 0, 128)) \
if self.draw_walkable else contextlib.suppress():
with self.debug_tiles(~self.agent.current_level().seen, color=(255... | The code executes an agent's action in an environment, updates the state, renders visuals, handles interactive features, tracks scores, and determines termination reasons. It processes environment feedback, manages step limits, and returns observations, rewards, and done status while logging end reasons from environmen... | def step(self, agent_action, agent_strategy_log):
agent_strategy_log = agent_strategy_log if not agent_strategy_log is None else 'init'
if self.visualizer is not None and self.visualizer.video_writer is None:
self.visualizer.step(self.last_observation, repr(chr(int(agent_action))))
... |
def broadcast_data(self):
broadcast_tf(self.r, [0, 0, 0], "map", "body_fixed", self.broadcaster_b1)
broadcast_tf([0, 0, 0], self.q, "body_fixed", "base_link1", self.broadcaster_b2)
broadcast_tf(self.rr, self.qr, "map", "reference", self.broadcaster_ref)
msg = std_msgs.msg.Float64MultiArray(data=self.u)
self.... | The code simulates a dynamic system using ROS, applying a control law in a loop. It initializes reference points, updates the system state with `step_dynamics`, broadcasts data periodically, and maintains real-time operation via `rate.sleep()`. The loop runs until shutdown, adjusting system variables like position (`r`... | def spin(self):
bias_count = 0
bias = np.zeros(6)
self.r = np.array([0.0, 0.0, 1.0])
self.q = np.array([0.0, -0.0, 1.0])
self.w = np.array([0.0, -0.0, 0.0])
loop_ctr = 0
self.rr = np.array([1, 0, 1])
for i in range(150):
self.rate.sleep()
update_ref = False
while not rospy.is_shutdown():
... |
def assert_setup(self):
"""
Some profiles require a setup (cloning from git or just creating some files)
Runs the setup_cmd from buff-code/src or whatever the project dir is.
"""
if self.name == "":
buff_log(f"Virtual Project detected", 0)
return 2
if not os.path.exists(self.project_path()):
buf... | The main task of the code is to execute a build process for a project, validate targets, compile the project using a specified command, install dependencies by copying packages to target locations via a lookup table, and recursively trigger build operations for included components. It ensures setup prerequisites are me... | def run_build(self):
"""
Run the build command from project root (buff-code/src/PROJECT_NAME)
"""
if self.assert_setup() == 0:
if self.validate_targets():
return
buff_log(f"Building {self.name}", 0)
self.run_job(self.build_cmd, self.project_path())
self.validate_build()
buff_log(f"Installi... |
def get_ref_seq(msa, refname):
with open(msa) as f:
for name, seq, qual in readfq(f):
if name == refname:
return seq.upper()
break
def update_snps(qseq, rseq):
dels = []
ins = []
snps = []
for qpos, qbase in enumerate(qseq):
ins_aware_po... | The code processes a multiple sequence alignment (MSA) file to identify single nucleotide polymorphisms (SNPs) between sequences and a reference. It skips the reference sequence, compares others to it, removes terminal gaps, generates VCF files for detected variants, and writes them. The main task is to extract and out... | def go(args):
refseq = get_ref_seq(args.msa, args.refname)
if not refseq:
print(args.refname + " not found\n")
sys.exit(1)
with open(args.msa) as f:
for name, seq, qual in readfq(f):
if name == args.refname:
continue
else:
p... |
def weightInitialization():
"""
w and b are Initialized to zero
:return:
"""
# w = Derviative parameter 1
# b = Derviative parameter 2/estimated later
w = np.zeros((1,1))
b = 0
return w,b
def model_predict(w, b, X, Y, learning_rate, no_iterations):
"""
:param w: The first par... | The code trains a logistic regression model using gradient descent on a popcorn dataset to predict edibility based on cooking time. It loads data, initializes weights, iterates to optimize parameters, and plots the sigmoid curve showing the relationship between cooking time and the probability of being edible. | def main():
data = pd.read_csv("popcorn_v3.csv")
data = data.head(25)
X_cap = np.array(data['Cook time(secs)'])
y_cap = np.array(data['edible'])
X = X_cap.reshape(-1, 1)
y = y_cap.reshape(-1, 1)
n_features = X.shape[1]
print('Number of Features', n_features)
w, b = weightInitializati... |
def get_number_list_from_genes(self):
my_list = []
# print(len(self.genes))
for i in range(0, len(self.genes)):
# if it is 0, we will drop it, the list contains indexes of all columns to be dropped
if self.genes[i] == 0:
my_list.append(i)
return my... | The code processes data by removing selected features, performs hyperparameter tuning if enabled, applies bagging or boosting based on the configuration, trains an ensemble classifier, evaluates its performance using metrics like F1 score and AUC, updates feature counts, calculates fitness, and returns the fitness valu... | def process_bagging(self, clf):
x_train, x_test, y_train, y_test = self.x_train, self.x_test, self.y_train, self.y_test
feature_index = self.get_number_list_from_genes()
x_train = np.delete(x_train, feature_index, axis=1)
x_test = np.delete(x_test, feature_index, axis=1)
# TODO: ... |
def updateLine(line):
existingBoxes = getBoxesByYInSpecificHeight(boxes, line)
cursor.setCursorAt(line+2)
print(backround, end="")
isPlayer = False
for i in range(width):
isSomething = False
if(line == player[1] and player[0] == i):
print(playertext, end="")
... | This function simulates a falling box game by updating box positions, handling collisions, rendering the game state, and adding new boxes. It maintains a game loop that moves boxes downward, removes out-of-bound boxes, updates the display based on render mode, and controls box spawning rates while managing game state v... | def boxLogic():
global canMove
global running
global sleepTime
global boxesPerTick
while(running):
time.sleep(sleepTime)
while sleepTime == -1:
time.sleep(0.1)
if(renderMode == 0): os.system("cls")
canMove = False
removeBoxes = []
... |
def _check_client(self, blob_client=None, blob_path=None, sas_url=None):
if blob_client:
return blob_client
if self.blob_client:
return self.blob_client
if not self.blob_client and not blob_path and not sas_url:
return Exception('blob_path or sas_url required.... | This function downloads a blob from a container to a specified destination, applying file type filters (include/exclude), setting metadata, and optionally deleting or moving the blob post-download. It constructs the destination path, checks file extensions against filters, creates necessary folders, and triggers the do... | def download_from_container(self, blob_path: [str, Path], dest: [str, Path], blob_client: str = None,
sas_url: str = None,
delete_after: bool = False,
move_after: [str, Path] = None, ignored_file_types: list = None,
... |
def _populate_i140_forms_from_csv(self) -> None:
self.i140_forms = read_i140_forms_from_csv()
def _populate_form_urls(self) -> None:
form_urls = set()
for page_url in self.page_urls:
r = requests.get(page_url)
soup = BeautifulSoup(r.text, features="html.parser")
... | The main task of the code is to process I-140 form data by populating forms from a CSV, extracting form URLs, downloading PNG files, preparing URLs for scraping, and writing processed forms back to a CSV in chunks. It automates data retrieval, storage, and organization for form-related tasks. | def run(self):
self._populate_i140_forms_from_csv()
self._populate_form_urls()
self._download_png_files()
self._populate_form_urls_to_scrape()
self._write_forms_to_csv(chunk_size=context.chunk_size) |
def adding_to_network():
url = 'http://localhost:8000/api/data'
data = {
'id': MYNAME,
'address': str(MYPORT) + '_' + socket.gethostbyname(socket.gethostname()),
}
headers = {'Content-type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)
... | The main task of the code is to set up a UDP-based peer-to-peer network node. It initializes a socket, joins a network, and provides user interaction to retrieve peer names or initiate communication. The node binds to a random port, listens for network activity, and allows the user to choose between fetching all connec... | def main():
global STATE
global MYPORT
global MYNAME
# global peer_address
address = socket.gethostbyname(socket.gethostname())
# MYPORT = int(input("your_port: "))
MYPORT = random.randint(1,1000)
MYNAME = input("your_name: ")
# MYNAME = "qw"
host = (address, MYPORT)
print(ho... |
def _find_side_files(folder: Path, ext: str, sides: Iterable[str] = ('',)) -> Iterator[Path]:
for side in sides:
yield from folder.glob(f'*{side}*{ext}')
def _find_right_files_for(left_files: Iterator[Path]) -> Sequence[tuple[Path, Optional[Path]]]:
return list(_find_right_files_for_generator(left_files... | This function identifies and pairs files in a specified folder with a given extension. It first locates "left" files using predefined keywords, then finds corresponding "right" files to create pairs. Finally, it validates these pairs to ensure correctness, returning a sequence of (left, right) file path tuples. | def _find_left_and_right_files(folder: Path, ext: str) -> Sequence[tuple[Path, Path]]:
left_files = _find_side_files(folder, ext, constants.LEFT_WORDS)
pairs = _find_right_files_for(left_files)
return _validate_pairs(pairs) |
def eval_true_pred(true_dir, pred_dir):
List_true_txt = glob.glob("%s/*.txt"%true_dir)
List_eval_true_pred = []
for true_txt_path in List_true_txt:
pred_txt_path = os.path.join(pred_dir, os.path.basename(true_txt_path))
Dict_pred_correspond2_true = compare_iou_truth_pred(true_txt_path, pred_txt_path)
... | The main task of the code is to evaluate object detection performance by comparing ground truth and predicted bounding boxes. It calculates IoU, generates statistical tables, counts true/predicted class labels, visualizes class distribution, identifies true/false positives/negatives, and computes precision, recall, and... | def main(
ground_truth_classes_bbox,
pred_classes_bbox,
classes_name,
width_figsize = 12,
height_figsize = 8,
save_dir = None
):
if os.path.exists(save_dir) == False:
os.makedirs(save_dir)
#with open(classes_name, "r") as file:
# classes_name = dict(file.read())
# Calculate IoU between... |
def SMExtractRGBI(self, inputImage):
# convert scale of array elements
src = np.float32(inputImage) * 1./255
# split
(B, G, R) = cv2.split(src)
# extract an intensity image
I = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
# return
return R, G, B, I
def IFMGetFM(s... | The code computes a saliency map by combining weighted conspicuity maps from intensity, color, orientation, and motion features. It extracts feature maps from input image channels, calculates individual conspicuity maps, applies weights, sums them, normalizes, smooths with bilateral filtering, and resizes the result to... | def SMGetSM(self, src):
# definitions
size = src.shape
width = size[1]
height = size[0]
# check
# if(width != self.width or height != self.height):
# sys.exit("size mismatch")
# extracting individual color channels
R, G, B, I = self.SMExtractRGB... |
def format_data(input_data: list):
return np.array([[int(x) for x in line] for line in input_data])
def get_centers(grid) -> list:
low_values = []
for y, line in enumerate(grid):
for x, i in enumerate(line):
results = []
for yy, xx in zip([y, y, y - 1, y + 1], [x - 1, x + 1, ... | The code identifies the three largest craters in a grid by calculating their sizes from center points, then returns the product of these three sizes. | def part_2(input_data):
grid = format_data(input_data)
centers = get_centers(grid)
biggest_craters = [0] * 3
for point in centers:
start_node = Node(point)
size = chart_crater(grid, start_node)
smallest_crater = min(biggest_craters)
if size > smallest_crater:
... |
def showNotRunning(authorMsg):
date = authorMsg.get("date")
yearNo = date.get("year")
monthNo = date.get("month")
dayNo = date.get("day")
yearLeft = yearNo - year
if (yearLeft > 0):
monthLeft = (12 - month) + monthNo # Months left this year + The month num next Ramadan
else:
... | The code calculates current prayer times (sehri/iftar) and remaining durations, adjusts for date transitions if times are outdated, and returns structured time data. It checks if today's date exceeds an end date, recalculates times with date increments, and formats results for display. | def parseTodayTime():
todayKey = {"day": day, "month": month, "year": year}
endYear = endDate.get("year")
endMonth = endDate.get("month")
endDay = endDate.get("day")
if (year > endYear) or ((month == endMonth) and (day > endDay)) or (month > endMonth):
showNotRunning({"date": todayKey, ... |
def getTimeData():
print("\n [\033[92m*\033[37m] Parsing Data\033[92m: \033[37m", end="")
import requests
data = requests.get("https://raw.githubusercontent.com/Toxic-Noob/PersonalRepository/main/ramadan/timeData.json").text
open("timeData.json", "w").write(data)
if not (os.path.exists("time... | The main task of the code is to check if "timeData.json" exists, fetch time data if it doesn't, configure time and district settings, parse today's time, and display the time data. It exits if sourceBanner is true when the file is missing. | def main():
if (not os.path.exists("timeData.json")):
if (sourceBanner):
sys.exit()
getTimeData()
setTime()
setDistrict(customDistrict)
setTimeData()
todayTime = parseTodayTime()
showTimeData(todayTime) |
def owntone_api(method, path):
request_types = {
"get" : requests.get,
"put" : requests.put,
"post" : requests.post,
}
return request_types[method](owntone_server() + path)
def find_currently_play_item(queue, item_id):
for(index, item) in enumerate(queue["items"]):
if item["id"] == ite... | The code fetches the current playback status from an API, retrieves metadata of the playing item, formats it into display lines, and updates a magtag display with the formatted information. | def display_status():
print("refreshing")
status_response = owntone_api("get", "/api/player")
status_json = status_response.json()
current_playing_item_id = status_json["item_id"]
# current_state = status_json["state"]
# current_volume = status_json["volume"]
item = find_currently_play_item(queue(), curr... |
def x(self, delta_t: float = None):
"""
Returns the current position of the molecule if delta_t == None, or the position of the molecule after
time delta_t if delta_t is provided.
"""
if not delta_t:
return self.trajectory.x[self.trajectory.n-1,:]
else:
... | The function calculates a molecule's new position and velocity after a time interval `delta_t` using constant acceleration (defaulting to gravity), then updates the trajectory with these values along with the new time and acceleration. It is used in beamline sections with uniform acceleration, excluding electrostatic l... | def update_trajectory(self, delta_t, a = np.array((0,-g,0))):
"""
Calculates the position of the molecule after time delta_t (s) has passed and updates the trajectory.
This function is used in the parts of the beamline where the acceleration is constant (i.e. everywhere
except the electr... |
def trapezium(n):
sol = 0.0
for j in range(n):
if j/n > 1:
print("you")
sol += (f(j/n)+f((j+1)/n))/2
return sol/n
def exact(a, b): return exp(b)-exp(a)
def MCtrapezium(n, l=100):
sol = 0
for j in range(n):
if U()*l < 1:
x, xx = j/n, (j+1)/n
... | The code compares the convergence rates of standard and Monte Carlo trapezoidal integration methods by plotting log-log error curves against theoretical reference lines. It calculates relative errors for varying interval counts (DTS), plots them, and overlays dashed lines representing expected error decay rates ($\Delt... | def MCtrap_llplot():
DTS = np.floor(np.power(2, np.arange(0, 23, 0.2))).astype(int)
errors = np.array(
[(abs(trapezium(n)-exact(0, 1)))/(exact(0, 1)) for n in DTS])
MCerrors = np.array(
[(abs(MCtrapezium(n, 100)-exact(0, 1)))/(exact(0, 1)) for n in DTS])
plt.plot(np.log(DTS)/np.log(10), ... |
def shift(self, horizontal: int, vertical: int, none_if_out_of_bounds: bool = False, inplace: bool = False):
vertical, horizontal = self._get_validated_shift_positions(horizontal, vertical)
file = FILES[FILES.index(self.file) + horizontal]
rank = self.rank + vertical
if none_if_out_of_bo... | The function generates diagonal coordinates around a position, excluding the current position and coordinates sharing the same row or column. It iterates over ranges to create coordinates via shifts, filters duplicates, and removes non-diagonal positions. | def _get_diagonal_coordinates(self, length: int) -> list["Coordinate"]:
coordinates = set()
for i in range(-length, length + 1):
coordinate = self.shift(i, i)
if coordinate is not None:
coordinates.add(coordinate)
for i in range(-length, length + 1):
... |
def shift(self, horizontal: int, vertical: int, none_if_out_of_bounds: bool = False, inplace: bool = False):
vertical, horizontal = self._get_validated_shift_positions(horizontal, vertical)
file = FILES[FILES.index(self.file) + horizontal]
rank = self.rank + vertical
if none_if_out_of_bo... | The code generates valid knight move coordinates by iterating over possible L-shaped moves (i, j) where |i| + |j| = 3, filtering out coordinates that are too close, share a file/rank/diagonal with the current position, and excluding the current position itself. It returns a set of valid coordinates for knight moves. | def _get_knight_coordinates(self) -> list["Coordinate"]:
coordinates = set()
for i in range(-2, 3):
for j in range(-2, 3):
if abs(i) + abs(j) != 3:
continue
coordinate = self.shift(j, i)
if (
self.distanc... |
def create_PHYS_vertex_file(f):
global g_VertexBufferLenght
global g_min_bounds
global g_max_bounds
f.seek(16,0)
amt2 = unpack("I", f.read(4))[0]
for i in range(amt2):
f.seek(8,1)
n_vertex_buffers = unpack("I", f.read(4))[0]
if n_vertex_buffers != 1:
print("n_vert... | The code processes a binary file to generate a glTF JSON file. It reads input data, creates vertex and node structures, converts nodes to an index format, builds a blank glTF JSON template, populates it with node data, and writes the resulting glTF file ("PHYS_f.gltf") with the structured 3D model information. | def main(argv):
f = open(argv[0], 'rb')
create_PHYS_vertex_file(f)
nodes = create_nodes_array_from_file(f)
from_nodes_array_to_index_file(f, nodes)
json_d = make_blank_gltf_json()
make_gltf_json(json_d, nodes)
f2 = open("PHYS_f.gltf", "w")
json.dump(json_d, f2)
f2.clos... |
def GenerateNewPuzzleString(self):
self.puzzleString=[]
for i in range(self.height):
line="_"*self.width
self.puzzleString.append(line)
def BuildPuzzle(self,puzzleString):
index=0
numbers = ['1','2','3','4','5','6','7','8','9']
self.AllSquares=[]
self.AllNumbers=[]
for y in range(self.height):
fo... | The main task of the code is to generate a new puzzle with predefined constraints (width, height, number ranges, dot placements, and empty cells). It constructs the puzzle, adds numbers and dots, and prints the final result in a structured format. | def GenrateNewPuzzle(self):
self.width = 6
self.height = 9
self.minNumber = 2
self.maxNumber = 7
self.minDotSquares = 2
self.maxDotsSquares = 7
self.minEmptySquares = 8
self.maxEmptySquares = 26
self.GenerateNewPuzzleString()
self.BuildPuzzle(self.puzzleString)
self.AddNumbersToPuzzle()
self.Pr... |
def GenrateNewPuzzle(self):
self.width = 6
self.height = 9
self.minNumber = 2
self.maxNumber = 7
self.minDotSquares = 2
self.maxDotsSquares = 7
self.minEmptySquares = 8
self.maxEmptySquares = 26
self.GenerateNewPuzzleString()
self.BuildPuzzle(self.puzzleString)
self.AddNumbersToPuzzle()
self.Pr... | This code initializes a puzzle object. If the input is ['0'], it generates a new puzzle. Otherwise, it sets the puzzle string, determines its dimensions, constructs the puzzle grid, and defines valid moves for each square. | def __init__(self,puzzleString):
if puzzleString == ['0']:
#print("no puzzle so creating one")
self.GenrateNewPuzzle()
else:
self.puzzleString = puzzleString
self.height = len(puzzleString)
self.width = len(puzzleString[0])
self.BuildPuzzle(self.puzzleString)
self.SetSquareMoves() |
def genegenerator(metnet=None,K=None):
flag = False
while flag == False:
if metnet.KO == None:
gene = tuple(np.random.choice(metnet.M,K))
else:
gene = tuple(np.random.choice(metnet.KO,K))
if len(set(gene)) == len(gene):
... | The code implements a genetic algorithm to evolve a population of individuals, optimizing their fitness through crossover, mutation, and selection. Each individual's gene is evaluated using LP solving, updating matrices (B, C, F) for explored genes. The algorithm tracks average and maximum fitness across generations, m... | def evolve(pop_size:int=None,K:int=None,metnet:MetNet=None,model:Model=None,num_gen:NumGen=None,numpar:int=None,crossprob:float=None,mutrate:MutRate=.7):
B_Matrix = np.zeros([len(metnet.M),len(metnet.M)])
C_Matrix = np.zeros([len(metnet.M),len(metnet.M)])
F_Matrix = np.zeros([len(metnet.M),len(metnet.M)]... |
def get_game_records_files( dir_name):
experience_dir = os.path.join("..", "models",dir_name )
files = os.listdir(experience_dir)
files = [file for file in files if file.startswith("game_record")]
files.sort(key = lambda x: int((x.split("_")[2]).split(".")[0]))
print(files)
return experience_di... | The code visualizes game states from recorded files using Pygame, allowing step-by-step viewing of player actions and game environments. It reads game records, processes each line to extract player data, and renders the game state on-screen. The loop handles pausing, file iteration, and event processing (QUIT, SPACE) t... | def main():
run = True
pause= False
PLAYER_NUM = int(sys.argv[2])
clock = pygame.time.Clock()
models_dir = sys.argv[1]
# exp_dir, files = get_game_records_files("model_100000_pure_collect_seed_reward_3_gamma_0.99")
exp_dir, files = get_game_records_files(models_dir)
index=-1
file_i... |
def get_game_records_files( dir_name):
experience_dir = os.path.join("..", "models",dir_name )
files = os.listdir(experience_dir)
files = [file for file in files if file.startswith("game_record")]
files.sort(key = lambda x: int((x.split("_")[2]).split(".")[0]))
print(files)
return experience_di... | The main task of the code is to replay and visualize game records from specified directories using Pygame, allowing step-by-step viewing of game states and actions for a given player number. It processes files line by line, updates the display, and supports pausing/resuming playback via the spacebar. | def main():
run = True
pause= False
PLAYER_NUM = int(sys.argv[2])
clock = pygame.time.Clock()
models_dir = sys.argv[1]
# exp_dir, files = get_game_records_files("model_100000_pure_collect_seed_reward_3_gamma_0.99")
exp_dir, files = get_game_records_files(models_dir)
index=-1
file_i... |
def exceeds_rate_limit(user_id, request_type):
"""Checks whether the given address has exceeded rate limits
Args:
user_id (str): unique user id
request_type (str): type of rate limit - can be "spliceai:total", "spliceai:model", or "liftover:total"
Return str: error message about exceeding ... | This function handles API requests for splice prediction using SpliceAI or Pangolin tools. It validates inputs, checks rate limits, retrieves or computes splicing scores, caches results, and returns JSON responses with variant analysis, genome version, parameters, and processing duration. | def run_splice_prediction_tool(tool_name):
"""Handles API request for splice prediction
Args:
tool_name (str): "spliceai" or "pangolin"
"""
if tool_name not in ("spliceai", "pangolin"):
raise ValueError(f"Invalid tool_name: {tool_name}")
start_time = datetime.now()
logging_pref... |
def extract_all_chunks(names: Optional[Dict[str, str]], no_ellipses: bool, disfluent_comma: bool, no_asterisks: bool, file_names: List[str]) -> List[WtWord]:
all_chunks = []
for file_name in file_names:
print(f" - {os.path.basename(file_name)}")
original_speaker = extract_speaker_name(file_name... | The main task of the code is to process and assemble multiple .words.json files from an input directory into a synchronized transcript. It extracts speech chunks, sorts them by timestamp, normalizes and collapses adjacent segments, checks for synchronization issues, auto-punctuates problematic sections, and writes the ... | def assemble(input_dir, corrections, names, no_ellipses, disfluent_comma, no_asterisks, show_timestamps):
if input_dir is None:
print("Please provide an input directory.")
return
print()
print("--------------------")
print("ASSEMBLE")
print("--------------------")
print()
... |
def titleMousePressed(event,data):
if event.x>175 and event.x<325 and event.y>425 and event.y<475:
data.mode='Selection'
def selectionMousePressed(event,data):
if event.x>24 and event.x<240 and event.y>65 and event.y<350:
data.mode='Ionic'
elif event.x>260 and event.x<476 and event.y>65 and ... | This function handles mouse click events in a GUI application, checking for an error state and validating coordinates to reset the error if clicked within a specific region. Depending on the current mode (e.g., Title, Selection, Instruction), it delegates the event to corresponding handler functions, enabling mode-spec... | def mousePressed(event, data):
# use event.x and event.y
if data.error:
if not (event.x>100 and event.x<425 and event.y>390 and event.y<460):
return
data.error=False
return
if data.mode=='Title':
titleMousePressed(event,data)
elif data.mode=='Selection':
... |
def messageToGUI(self,message):
try:
self.txtBox_message.insert(END,"\n ->"+message)
except Exception as ex:
Log.WriteLog(traceback.format_exc(),"messageToGUI()")
def dataToCSV(self):
try:
List_file = os.listdir(GlobalVariables.calculationDataPath)
... | This code initializes technical indicators (Stochastic oscillator and EMA) for financial tickers by iterating through date-ticker pairs, updating price data dictionaries, calculating indicators when sufficient historical data is available, and managing data retention. It then triggers GUI updates, CSV export, and simul... | def Init_calculation(self):
try:
for dt in GlobalVariables.DateTime_collection.keys():
for objTicker in GlobalVariables.ticker_collection.values():
if(dt in objTicker.ohlc):
objBar = objTicker.ohlc[dt]
objTicker.hand... |
def sim_warthog(self, v, w):
x = self.pose[0]
y = self.pose[1]
th = self.pose[2]
v_ = self.twist[0]
w_ = self.twist[1]
dt = self.dt
self.prev_ang = self.pose[2]
self.pose[0] = x + v_ * math.cos(th) * dt
self.pose[1] = y + v_ * math.sin(th) * dt
... | The code defines a `step` function for a reinforcement learning agent navigating a robot (e.g., Warthog) toward waypoints. It clips and scales actions, updates the simulation, checks if the target waypoint is reached, calculates errors (cross-track, velocity, heading), computes a reward based on these errors, and termi... | def step(self, action):
action[0] = np.clip(action[0], 0, 1) * 4.0
action[1] = np.clip(action[1], -1, 1) * 2.5
self.sim_warthog(action[0], action[1])
self.prev_closest_idx = self.closest_idx
obs = self.get_observation()
done = False
if self.closest_idx >= self.num... |
def getOracleTwapPrice(self):
oracle = self.getDataFromContract('k_ora')
priceKey = self.getDataFromContract('k_ora_key')
return self.getDataFromAddress(oracle, priceKey) / 1000000
def getTwapSpotPrice(self):
qtAstR = self.getDataFromContract('k_qtAstR')
bsAstR = self.getDataFro... | The function calculates the funding rate by determining the premium between the spot TWAP price and the underlying asset's price, adjusting it by the funding period and time unit, then normalizing it relative to the underlying price for precise financial derivative calculations. | def getFundingRate(self):
underlyingPrice = self.getOracleTwapPrice()
spotTwapPrice = self.getTwapSpotPrice()
premium = spotTwapPrice - underlyingPrice
decimalUnit = (1 * (((((10 * 10) * 10) * 10) * 10) * 10))
oneDay = 86400 * decimalUnit
fundingPeriodRaw = self.getDataFr... |
def getOracleTwapPrice(self):
oracle = self.getDataFromContract('k_ora')
priceKey = self.getDataFromContract('k_ora_key')
return self.getDataFromAddress(oracle, priceKey) / 1000000
def getTwapSpotPrice(self):
qtAstR = self.getDataFromContract('k_qtAstR')
bsAstR = self.getDataFro... | This function calculates the funding rate by determining the premium difference between the spot TWAP price and the underlying asset price, adjusting for decimal precision and funding period duration. It returns the normalized funding rate as a fraction of the underlying price, incorporating time-based scaling factors ... | def getFundingRate(self):
underlyingPrice = self.getOracleTwapPrice()
spotTwapPrice = self.getTwapSpotPrice()
premium = spotTwapPrice - underlyingPrice
decimalUnit = (1 * (((((10 * 10) * 10) * 10) * 10) * 10))
oneDay = 86400 * decimalUnit
fundingPeriodRaw = self.getDataFr... |
def get_font():
fonts = [x for x in pygame.font.get_fonts()]
default_font = 'ubuntumono'
font = default_font if default_font in fonts else fonts[0]
font = pygame.font.match_font(font)
return pygame.font.Font(font, 14)
def create_main_actors(start_pose, waypoint):
blueprint_library = world.get_bl... | The main task of the code is to run a CARLA-based simulation for multi-modal data acquisition, controlling a vehicle with keyboard inputs, capturing RGB/depth sensor data, GPS, and vehicle dynamics. It displays real-time telemetry, records data to files, and synchronizes sensor outputs with timestamps for calibration a... | def main():
actor_list = []
pygame.init()
pygame.display.set_caption(
'IBISCape: Multi-modal Data Acquisition Framework')
display = pygame.display.set_mode(
(1200, 450),
pygame.HWSURFACE | pygame.DOUBLEBUF)
font = get_font()
clock = pygame.time.Clock()
iterator = 1
... |
def parse_text_file():
"""
Scrapes websites listed on each row in text file
"""
with open(file, 'r') as torfile:
torfile = torfile.readlines()
url2 = [x.replace('\n', '') for x in torfile]
try:
try:
for res in url2:
print('\n' + C +... | The code allows users to select a file by inputting its name or location. It checks the file extension (txt, csv, xlsx) and calls corresponding parsing functions. If the file type is unsupported, it displays an error message. The main task is to enable file selection and trigger format-specific parsing processes. | def choose_file():
"""
Allows the user to choose a file type to be parsed
"""
global file
file = input(C + '[+] ' + G + 'Please Enter File Name or Location -> ')
if '.txt' in str(file):
parse_text_file()
elif '.csv' in str(file):
parse_csv_file()
elif '.xlsx' in str(file)... |
def get_grid_size(num: int = 1) -> tuple:
# get num of cols andd rows in result grid
cols = max(int(np.ceil(np.sqrt(num))), 1)
rows = max((num - 1) // cols + 1, 1)
return (rows, cols)
def get_random_key(all_keys):
key = random.choice(list(all_keys))
return key
def create_frame(ds_name, img, f_im... | The main task of the code is to generate a video from a dataset's images by arranging them in a grid layout, with optional random selection of images, and save the result as an MP4 file. It uses parameters like frame rate, opacity, and thickness to customize the video, ensuring the output matches the specified dimensio... | def create_video_for_dataset(
dataset, ds_name, ds_path, all_projects, details, frames_count, is_random
):
fps, opacity, thickness = details
# choose image size
all_img_in_cur_ds = iter(dataset["images"].values())
f_img_info = next(all_img_in_cur_ds)
f_img_shape = (f_img_info.height, f_img_info... |
def create_project(project_name):
# create new project and dataset
project = g.api.project.create(
g.WORKSPACE_ID, project_name, sly.ProjectType.VIDEOS, change_name_if_conflict=True
)
print(f"New project has been sucessfully created (id={project.id})")
return project.id
def dataset_is_valid(... | The main task of the code is to render videos from datasets, upload them to a newly created project, and clean temporary files. It iterates through datasets, generates videos using specified parameters, creates corresponding datasets in the project, uploads videos, and manages temporary storage by cleaning directories ... | def start_render_and_upload_to_new_project(project_name, datails, frames_count, random):
# iterate over datasets, images, merge images to frames and write video fo each dataset
DATA_DIR = sly.app.get_data_dir() # temp directory to store result video before uploading
all_projects = g.src_projects_data.value... |
def add_possible_moves(self, player):
moves = []
for piece in player.piece_list:
if isinstance(piece, King):
self.add_castle_moves(piece, moves)
if isinstance(piece, Pawn):
self.add_pawn_moves(piece, moves)
for direction in piece.move_d... | The code generates all valid moves for a player by first collecting possible moves, then checking each move's legality. It temporarily applies each move, verifies if it results in the player being in check (invalidating it), and undoes the move. Invalid moves are removed from the list, returning only valid moves that d... | def get_valid_moves(self, player):
possible_moves = self.add_possible_moves(player)
invalid_moves = []
for move in possible_moves:
self.make_move(move)
match move:
case Castle():
if not self.is_legal_castle(player, move):
... |
def wrap_as_node(self, func):
'wrap a function as a node'
name = self.get_name(func)
@wraps(func)
def wrapped(*args, **kwargs):
'wrapped version of func'
message = self.get_message_from_call(*args, **kwargs)
self.logger.info('calling "%s" with %r', na... | The main task of the code is to wrap a function into a graph node by applying transformations, logging debug information, and registering the processed function with a graph system using parameters like name, fields, and subscriptions. It checks for a custom wrapper method and applies it if available before final regis... | def outer(func):
'outer level function'
# create a wrapper function
self.logger.debug('wrapping %s', func)
wrapped = self.wrap_as_node(func)
if hasattr(self, 'wrap_node'):
self.logger.debug('wrapping node "%s" in custom wrapper', wrapped)
... |
def rc4_decrypt(key, ciphertext):
return rc4_encrypt(key, ciphertext)
def decrypt_image(ciphertext, key):
"""
Decrypt an image file using AES algorithm.
"""
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
padded_plaintext = cipher.decrypt(ciphertext[AES.block_size:])... | The main task of the code is to decrypt an encrypted image using a provided password, save the decrypted image to a file, and update a GUI status label to indicate success or error. It retrieves encrypted data from a dictionary, decrypts the AES key with RC4, decrypts the image data, writes it to disk, and manages UI f... | def fetch_image_data(name, password):
# Process to get the image
print(f"Fetching Image: {name}, Password: {password}")
# Your fetching logic goes here
# verifying input
image_name = name
password_decrypt = password
status_label = tk.Label(frame, text="")... |
def _find_parent_table(self, table: str = "") -> str:
"""
Find the parent table from a given table name
:param table: table name
:return: table: the parent table name(if it is not partitioned table, it is just the input
"""
if self.part_tables is not None:
if ... | The function recursively traverses an execution plan to map table aliases, collect output columns, handle filters/index conditions, and manage CTEs/subqueries. It processes scan nodes, CTE scans, subquery scans, and append nodes, updating internal data structures like table aliases, possible columns, and CTE dictionari... | def _traverse_plan(self, plan: dict = None) -> None:
"""
Traversing the plan using recursion and go into Plans if it is present
:param plan: the given execution plan
:return: None
"""
if plan["Node Type"] in [
"Seq Scan",
"Parallel Seq Scan",
... |
def _find_cte_col(self, sql: str = "") -> dict:
"""
Find the column names for each cte since it does not show in the execution plan
:param sql: the sql that needs to be analyzed
:return: the dict with table name as keys and list of columns as child
"""
cte_col_dict = {}
... | This code initializes a SQL parser/analyzer by setting up attributes to track columns, tables, CTEs, and subqueries. It parses SQL using SQLGlot, identifies column relationships, and processes query plans to resolve metadata. Key tasks include AST parsing, CTE column detection, table traversal, and column mapping resol... | def __init__(
self,
plan: dict = None,
sql: str = "",
table_name: str = None,
faldbt: FalDbt = None,
part_tables: dict = None,
):
self.split_regex = re.compile(r"[^a-zA-Z0-9._]")
self.all_used_col = []
self.possible_columns = []
self.ta... |
def conv_bn_layer(self,
input,
filter_size,
num_filters,
stride,
padding,
num_groups=1,
if_act=True,
act=None,
name=None,
... | This code defines a neural network architecture with residual blocks, applying convolutional layers, activation functions, and pooling. It processes input data through configurable layers, compresses features via a squeeze layer, and expands them for classification. If an embedding size is specified, it generates an em... | def net(self, input, embedding_size=256):
scale = self.scale
inplanes = self.inplanes
cfg = self.cfg
cls_ch_squeeze = self.cls_ch_squeeze
cls_ch_expand = self.cls_ch_expand
#conv1
conv = self.conv_bn_layer(
input,
filter_size=3,
... |
def is_queue_empty(ready_queue):
return True if len(ready_queue) == 0 else False
def save_process_state_in_scheduling(process):
actual_state = copy(process)
cpu_scheduling.append(actual_state)
colors.append(process.color)
def set_all_times(process_list):
completion_times(process_list)
return_tim... | The code implements a **round-robin scheduling algorithm**. It processes tasks from a `ready_queue`, executing each for a maximum `quanta` time. If a task's remaining burst time exceeds `quanta`, it is paused and reinserted into the queue. Otherwise, it completes. The scheduler tracks execution timelines, context switc... | def scheduler(process_list):
ready_queue = process_list.copy()
timeline = 0
while not is_queue_empty(ready_queue):
head_process = ready_queue[0]
scheduling_starts.append(timeline)
save_process_state_in_scheduling(head_process)
ready_queue.remove(head_process)
if h... |
def operator_unify(operator):
"""
I just was annoyed adding additional square brackets to the operators.
This one allows to make operator form simpler.
Parameters
----------
operator : list
Operator in form ... .
Returns
-------
unified_operator : list
DESCRIPTION.
... | This function processes a differential operator to generate a list of grid-specific operators for different subsets. It unifies the input operator, applies type-specific transformations, and maps them to grid shifts, returning a list of operators for use in algorithms. | def apply_all_operators(operator, grid, h=0.001, subset=None, true_grid=None):
"""
Parameters
----------
operator : list
operator_unify result.
grid : torch.Tensor
grid with sotred nodes (see grid_prepare)
h : float
derivative precision parameter. The default is 0.0... |
def __init_population(self):
self.pop = self.initial_population(self.pop_size)
self.cur_gen = 0
def __stop_criteria(self):
return self.cur_gen >= self.generations
def __assign_fitness_values(self):
for individ in self.pop:
u = individ.genotype
individ.fitness_valu... | This code executes an evolutionary algorithm to optimize a population of candidates by iteratively generating offspring, applying mutations based on a specified rate, and tracking the best solution's fitness until convergence. It initializes a population, evaluates fitness, selects top candidates, mutates offspring, an... | def run(self):
# self.history.init_new_run()
self.__init_population()
while not self.__stop_criteria():
self.__assign_fitness_values()
top = self.graded_by_fitness()[0]
if self.cur_gen == 0:
self.__first_min_fitness = top.fitness_value
... |
def op_dict_to_list(opdict):
return list([list(term.values()) for term in opdict.values()])
def operator_unify(operator):
"""
I just was annoyed adding additional square brackets to the operators.
This one allows to make operator form simpler.
Parameters
----------
operator : list
O... | The function `operator_prepare` converts a conventional differential operator into a format compatible with specified grid subsets. It accepts the operator, grid, and optional parameters like subsets and precision. The operator is first converted from a dictionary (if provided) to a list, unified, and then applied to t... | def operator_prepare(op, grid, subset=['central'], true_grid=None, h=0.001):
"""
Changes the operator in conventional form to the input one
Parameters
----------
op : list
operator in conventional form.
grid : torch.Tensor
grid with sotred nodes (see grid_prepare)
h : fl... |
def bnd_unify(bconds):
"""
Serves to add None instead of empty operator
Parameters
----------
bconds : list
boundary in conventional form (see examples)
Returns
-------
unified_bconds : list
boundary in input-friendly form
"""
if bconds==None:... | The function processes boundary conditions by unifying their format, converting operators to a standard form, applying them to a grid with specified precision, and returning the prepared boundary conditions in input-ready format for further use in simulations or models. | def bnd_prepare(bconds, grid, h=0.001):
"""
Parameters
----------
bconds : list
boundary in conventional form (see examples)
grid : torch.Tensor
grid with sotred nodes (see grid_prepare)
h : float
derivative precision parameter. The default is 0.001.
Returns
... |
def b_param(k: CURVE) -> B_PARAM:
a1, a3, a2, a4, a6 = k
b2 = a1**2 + 4*a2
b4 = a1*a3 + 2*a4
b6 = a3**2 + 4*a6
b8 = int(1.0/4 * (b2*b6 - b4**2))
return b2, b4, b6, b8
def _c_param(b: B_PARAM) -> C_PARAM:
b2, b4, b6, b8 = b
c4 = b2**2 - 24*b4
c6 = -b2**3 + 36*b2*b4 - 216*b6
return... | The main task of the code is to generate a structured report of an elliptic curve's parameters. It prints coefficients (a1-a6, b2-b8, c2-c4), the short Weierstrass form, discriminant, and j-invariant (if discriminant ≠ 0) for the input curve `k`, aiding in analyzing its mathematical properties and transformations. | def report_curve(k: CURVE):
b = b_param(k)
c = _c_param(b)
print(f'a1={k[0]} a3={k[1]} a2={k[2]} a4={k[3]} a6={k[4]}')
print(f'b2={b[0]} b4={b[1]} b6={b[2]} b8={b[3]}')
print(f'c2={c[0]} c4={c[1]}')
print(f'short weierstrass: {pretty_short_weierstrasss(k)}')
d = discriminant(k)
print(f'd... |
def FIND(self, node_id:int):
node = self.NODE(node_id)
if node.find == node_id: return node_id
return self.FIND(node.find)
def CCPAR(self, node_id:int):
return self.NODE(self.FIND(node_id)).ccpar
def UNION(self, n1:int, n2:int):
n1 = self.NODE(self.FIND(n1))
n2 = self.NOD... | The code implements a merge operation for a union-find data structure. It merges two nodes (node_id1 and node_id2) if they belong to different sets, then recursively merges all congruent node pairs from their parent lists (p1, p2) using itertools.product. The process ensures hierarchical union of nodes while maintainin... | def MERGE(self, node_id1:int, node_id2:int):
if self.FIND(node_id1) != self.FIND(node_id2):
p1 = self.CCPAR(node_id1)
p2 = self.CCPAR(node_id2)
self.UNION(node_id1, node_id2)
for t1, t2 in list(itertools.product(p1, p2)):
if self.FIND(t1) != self.F... |
def getArgmax(self,wordSeq):
senLength=len(wordSeq) #get the tag sequence length
tagCandidateSet=self.tagSeqList[senLength] #get all possible candidate tag sequence
scoreFea1List=np.zeros(len(tagCandidateSet)) #store the score of all tag sequence for one feature
scoreFea2List=np.zeros(... | The code trains a model using multiple features by iteratively updating weights based on prediction errors. It shuffles the training set, predicts tags with four feature sets, updates weights when predictions mismatch true tags, accumulates weights across iterations, and finally averages them to prevent overfitting. Th... | def train(self):
c=0 #initialise counter as 0 in order to average weight
listTrainSet=self.trainSet #get trainSet
sum_weight_featu1={k:0 for k in self.weight_oneFea.keys()} #initialise this dict to sum weight_one each time
sum_weight_featu2={k:0 for k in self.weight_twoFea.keys()} #init... |
def getAllPossiTagSeq(self):
tagSeqList=[0]
tagSeqList.append(self.candidateTagSet(1))
tagSeqList.append(self.candidateTagSet(2))
tagSeqList.append(self.candidateTagSet(3))
tagSeqList.append(self.candidateTagSet(4))
tagSeqList.append(self.candidateTagSet(5))
tagSe... | The code's main task is to implement a sequence labeling model by extracting word and tag features, calculating word-label, tag-tag, and trigram counts, training the model with training data, evaluating it on test data, and printing top features for analysis. It prepares tag sequences, computes feature statistics, and ... | def implement(self):
self.tagSeqList=self.getAllPossiTagSeq() #get all possible tag sequence
self.wordCurrentCount() #get the current word-label counts in corpus
self.tag_tagCount() #get the current label-label counts in corpus
self.trigramCount() #get the current label-label-label coun... |
def initialize(dimension):
weight = np.full((dimension, 1), 0.01)
bias = 0.0
return weight, bias
def update(weight, bias, x_train, y_train, learningRate, iteration):
costList = []
index = []
# for each iteration, update weight and bias values
for i in range(iteration):
cost, gradien... | The code implements a logistic regression model by initializing parameters, training using gradient descent with given learning rate and iterations, predicting test data outcomes, and calculating manual test accuracy as a percentage compared to actual labels. | def logistic_regression(x_train, y_train, x_test, y_test, learningRate, iteration):
dimension = x_train.shape[0]
weight, bias = initialize(dimension)
parameters, gradients = update(weight, bias, x_train, y_train, learningRate, iteration)
y_prediction = predict(parameters["weight"], parameters["bias"],... |
def _update(self, movement, dt):
if movement["direction"] in {1, "forward"}:
if self.velocity.x < 0:
self.acceleration = self.brake_deceleration
else:
self.acceleration += dt
elif movement["direction"] in {-1, "backward"}:
if self.veloc... | This code moves a car model based on kinematic laws, updating its position, checking collisions, calculating radar data, and updating the score if the car is alive. It processes movement input, computes collision points, detects collisions with the environment, gathers radar information, and evaluates performance metri... | def move(self, movement, dt, screen, surface):
"""Moves a car model according to the kinematics laws and the input direction"""
if self.is_alive:
self._update(movement, dt)
self._compute_collision_points()
self._check_collision(screen, surface)
self._compu... |
def _agglob(self, feat, state):
feat_sum = self.sumpool(state.g, feat)
h = self._theta6fc(feat_sum)
return h
def _aggcur(self, feat, state):
cur_feat = self._getCurFeat(state.g, feat, state.v)
h = self._theta7fc(cur_feat)
return h
def _aggact(self, action):
h = se... | The code performs a forward pass in a neural network to compute Q-values by aggregating input features, environment state, and actions through three separate functions (_agglob, _aggcur, _aggact), concatenating their outputs, applying ReLU activation, and passing the result through a final fully connected layer (_theta... | def forward(self, feat, state, action):
"""
A method for forward pass
Args:
feat (tensor): a batch of embedding features
state (returnState): enviroment state
action(tensor): a bacth of actions
"""
h1 = self._agglob(feat, state)
h2 = self._a... |
def _init_writer(self):
self.logger = get_logger(os.path.join(self.args.save_dir, "train.log" if self.args.is_train else "test.log"))
with open(os.path.join(self.args.save_dir, "description.txt"), 'w') as f:
f.close()
def _init_dataset(self):
self.logger.info("init dataset.")
... | The code initializes a training setup by configuring arguments, setting random seeds, creating directories, logging parameters, initializing datasets and models, and preparing GPU buffers for training. It sets up logging, device configuration, and initializes buffers for bit-based operations, preparing the environment ... | def __init__(self, args):
self.args = args
torch.random.manual_seed(seed=self.args.seed)
torch.autograd.set_detect_anomaly(True)
os.makedirs(self.args.save_dir, exist_ok=True)
self._init_writer()
self.logger.info('Start logging...')
if self.args.is_train:
... |
def from_ugc(filename):
return "ugc/%s" % filename
def parse_content_type(header):
components = header.split(";")
value = components[0]
options = components[1:]
dictionary = {}
for kv in options:
kv = kv.strip().split("=")
k = kv[0]
v ... | This function loads paginated JSON data from a local file, validates its MIME type, extracts the "value" array, and inserts records into a database using provided procedures. It handles pagination via "odata.nextLink" by repeatedly fetching and processing subsequent files until no more pages exist. | def load_json_pages(local_file, cursor, insert_procs):
more = True
while (more):
filename = from_ugc(local_file["filename"])
content_type = parse_content_type(local_file["content-type"])
mime_type = content_type[0]
options = content_type[1]
if (mime_type != "... |
def set_seed(seed):
torch.manual_seed(seed)
np.random.seed(seed)
def get_dataset_configuration(dataset):
if dataset == 'ECG':
generator = [('id=100', dict(filenames=['100']))]
elif dataset == 'STOCKS':
generator = (('_'.join(asset), dict(assets=asset)) for asset in [('SPX',), ('SPX', 'DJ... | The main task of the code is to train machine learning models on specified datasets using multiple algorithms and random seeds. It creates a data directory, configures training parameters (device, batch size, etc.), iterates over datasets, algorithms, and seeds, and executes training runs with specified hyperparameters... | def main(args):
if not pt.exists('./data'):
os.mkdir('./data')
# if not pt.exists('./data/oxfordmanrealizedvolatilityindices.csv'):
# print('Downloading Oxford MAN AHL realised library...')
# download_man_ahl_dataset()
#if not pt.exists('./data/mitdb'):
# print('Downloading MI... |
def _get_unique_rand_indices(self, max_int):
if self._selection_size >= max_int:
return list(range(max_int))
if self._selection_size < 5:
return self._dumb_selection(max_int)
return np.random.choice(max_int, self._selection_size, replace=False)
def _find_inds_for_removal(... | This method performs Age-Fitness selection to reduce a population's size by removing chromosomes, ensuring the new population meets a target size. It calculates required removals, iteratively selects indices, identifies candidates for removal, and trims the population. If the target size exceeds the initial population,... | def __call__(self, population, target_population_size):
"""Performs Age-Fitness selection on a population. If ``selection_size``
is larger than the population, the population size is used as the
``selection_size``.
Parameters
----------
population : list of chromosomes
... |
def generate_real_samples(dataset, n_samples):
#select random instances
#NOTE: constructor randint(low, high, size)
ix = randint(0, dataset.shape[0], n_samples)
#retrieve selected images
X = dataset[ix]
#generate 'real' class labels (literally '1')
#NOTE: constructor ones(shape, dtype)
#... | This function trains a GAN by alternating between updating the discriminator with real and fake samples, then training the generator via the combined GAN model. It iterates over epochs and batches, generates latent points, and renders plots. Discriminator updates use real/fake samples, while the generator is trained wi... | def train(g_model, d_model, gan_model, dataset, latent_dim, render_latent, n_epochs=200, n_batch=150):
bat_per_epo = int(dataset.shape[0] / n_batch)
half_batch = int(n_batch / 2)
#manually loop epochs
for i in range(n_epochs):
#loop batches over the training set
for j in range(bat_p... |
def intersects(self, newpos, angle):
"""Checks for intersecting blocks on path of each block of tetrimino.
Parameters: newpos (new position) and angle (new angle)
"""
tetrimino = self.all_tetriminos[-2]
oldpos = tetrimino.position
y_difference = oldpos[0] - newpos[0]
... | This code handles user controls for a Tetris piece, adjusting its position (left/right/down/drop) or rotation based on input. It checks for collisions with existing blocks before updating the piece's position or rotation, ensuring valid moves. The 'drop' action recursively moves the piece down until it hits the bottom ... | def controls(self, control):
""" controls current piece """
self.control = control
current_piece = self.all_tetriminos[-2]
position = current_piece.position
angle = current_piece.rotation
if self.control == "left":
newpos = position[0], position[1]-1
... |
def tuxTopHead():
os.system('cls' if os.name == 'nt' else 'clear')
colorSpace("black", 56)
colorSpace("dark_g", 7)
print("")
for a in range(0, 2):
colorSpace("black", 55)
colorSpace("dark_g", 9)
print("")
colorSpace("black", 55)
colorSpace("dark_g", 10)
print("")... | The code generates a stylized, colored text output using predefined color patterns and formatting functions. It prints a structured layout with headers, color blocks, and the provided text, incorporating the 'look' parameter for customization. The main task is to display formatted text with specific color schemes and s... | def tux(text, look):
tuxTopHead()
colorSpace("black", 54)
colorSpace("dark_g", 2)
colorSpace("white", 1)
colorSpace("dark_g", 3)
colorSpace("white", 1)
colorSpace("dark_g", 4)
print("")
lookCheck(look)
colorSpace("black", 54)
colorSpace("dark_g", 1)
colorSpace("white", ... |
def tuxTopHead():
os.system('cls' if os.name == 'nt' else 'clear')
colorSpace("black", 56)
colorSpace("dark_g", 7)
print("")
for a in range(0, 2):
colorSpace("black", 55)
colorSpace("dark_g", 9)
print("")
colorSpace("black", 55)
colorSpace("dark_g", 10)
print("")... | The main task of the code is to generate a stylized ASCII art representation of a tuxedo-themed character's mouth and head using colored text. It uses the `colorSpace` function to define color blocks and spacing, incorporates input parameters `text` and `look` for customization, and prints formatted text with ANSI colo... | def tuxMouthOpen(text, look):
tuxTopHead()
colorSpace("black", 54)
colorSpace("dark_g", 2)
colorSpace("white", 1)
colorSpace("dark_g", 3)
colorSpace("white", 1)
colorSpace("dark_g", 4)
print("")
lookCheck(look)
colorSpace("black", 54)
colorSpace("dark_g", 1)
colorSpace(... |
def preprocess(self, text: str) -> str:
return text.replace("\n\n", "\n")
def _generate_prompt(self, text: str) -> str:
examples_text = ""
if len(self._model_config.examples):
examples_text = "\n\n".join(
[
self._get_example_text(
... | The code processes input text by preprocessing it, generating a prompt, creating cards using the prompt and user ID, and postprocessing the result to return a list of Card objects. | def __call__(self, text: str, user_id: str) -> List[Card]:
preprocessed_text = self.preprocess(text)
prompt = self._generate_prompt(preprocessed_text)
completion = self._generate_cards(prompt, user_id)
cards = self.postprocess(completion)
return cards |
def get_output_name(self, i_file):
i_file, _ = splitext(i_file) # Remove ext
start_t = _format_time(self._start_time)
end_t = _format_time(self._end_time)
return f'_{i_file}_[{start_t}_{end_t}]'
def _get_duration(self, file):
"""
Get video duration in seconds
:pa... | The main task of the code is to convert video files by iterating through input files, filtering out images, calculating total frames using duration and FPS, and executing the conversion process for each video file to generate output files. | def _convert_videos(self):
# Load videos
for i_file in filter(lambda x: splitext(x)[-1].lower() not in image_types, self._files):
o_file = self.get_output_name(i_file)
i_file = join(self._path, i_file)
# Convert the video
self._set_total_frames(self._get_d... |
def exec_sql(cursor: Any, sql: str) -> None:
"""Execute the given SQL."""
_log_sql(sql)
cursor.execute(sql)
def _log_sql(sql: str) -> None:
_log.debug('SQL: {}'.format(sql))
def sql_select_table_with_local_columns(inspector: Any, schema: str, schema_table: Any, src_table: str,
... | The main task of the code is to perform a full import (upsert) of data from a file into a PostgreSQL table by creating temporary tables, validating columns, transforming data, and comparing rows to efficiently insert or update records. It ensures data integrity with key checks, handles foreign keys, and returns import ... | def pg_upsert(inspector: Any, cursor: Any, schema: str, dest_table: str, input_file: str,
file_format: Optional[str] = None, file_config: Optional[FileConfig] = None,
config_per_table: Optional[TablesConfig] = None) -> ImportStats:
"""
Do a full import (actually a merge or upsert) of... |
def replace_local_columns_with_alternate_keys(inspector: Any, config_per_table: TablesConfig, schema: str,
table: str, local_columns: List[str]
) -> List[ForeignColumnPath]:
"""
Replace foreign-key columns in table with ... | This function exports specified database tables and their subsets into CSV files based on configuration settings, handling encoding, column mappings, and filtering. It processes each table's configuration, generates output files, and returns the count of tables and exported files. | def export_tables_per_config(connection: Any, inspector: Any, schema: str, output_dir: str, tables: List[str],
config_per_table: Optional[TablesConfig] = None,
file_format: Optional[str] = None) -> Tuple[int, int]:
"""Export all given tables according to the... |
def random_seed(length):
global seed, finished_name
seed = ""
choices = "0123456789abcdefghijklmnopqrstuvwxyz"
i = 0
while (i < length):
seed = seed + random.choice(choices)
i = i + 1
seed_name = './seeds/' + finished_name + '_seed.txt/'
original_stdout = sys.stdou... | The main task of the code is to split original images into multiple random-sized sub-images (splits) using random coordinates and dimensions, save them as JPEG files in a "splits" directory, record their origins, and update a JSON file with new image metadata. Each image is processed to generate `num_of_splits` cropped... | def random_split():
print("Splitting original images...")
# Access global var - split origins (x,y)
global split_origins, seed, num_of_splits
# Generate a random seed for the splits
if (seed == "-1"):
random_seed(num_of_splits)
# Dictionary of images from original coco file
images... |
def generator(self):
if self.G:
return self.G
if self.is_residual :
residual_string = ""
else :
residual_string = "_nn_residual"
if self.u_net_gen :
if self.is_... | The main task of the code is to construct and compile a generator model in a GAN framework, freezing the discriminator's weights during training by setting their learning rate to zero. It creates input layers, generates fake images, and connects them to the discriminator for adversarial loss. The model is configured wi... | def generator_model(self):
if self.gen_model:
return self.gen_model
print("We freeze the weights of Discriminator by setting their learning rate as 0 when updating Generator !")
# We freeze the weights of Discriminator by setting their learning rate as 0 when updating Generator !
... |
def _popen(self, command,
stdin=None, stdout=None, stderr=None,
close_fds=True):
"""Execute the given command in the sandbox using
subprocess.Popen, assigning the corresponding standard file
descriptors.
command ([string]): executable filename and arguments... | The function executes a command in a sandbox using subprocess.Popen, discarding standard input, output, and error. It returns True/False if blocking (based on sandbox exit codes) or the Popen object if non-blocking, preventing execution blocking by reading all output/error asynchronously. | def execute_without_std(self, command, wait=False):
"""Execute the given command in the sandbox using
subprocess.Popen and discarding standard input, output and
error. More specifically, the standard input gets closed just
after the execution has started; standard output and error are
... |
def update_tftp_config():
vbox_path = get_vbox_path()
pxelinux_path = get_pxelinux_path()
pxelinuxcfg_path = vbox_path.joinpath(pxelinux_path).joinpath("pxelinux.cfg")
try:
pxelinuxcfg_path.mkdir()
except FileExistsError:
pass
dst = pxelinuxcfg_path.joinpath("default")
shutil... | The code creates and configures a VirtualBox VM with specified hardware, storage, and boot settings. It generates a virtual disk, sets up networking, adjusts memory/CPU, and modifies boot order. The VM is started, monitored until shutdown, then its boot order is reset, marking it as ready for use. | def create_vm():
update_tftp_config()
vboxmanage(f"createhd --filename {vmname}.vdi --size {storage}")
vboxmanage(f"createvm --name {vmname} --ostype RedHat_64 --register")
vboxmanage(f"modifyvm {vmname} --nested-hw-virt on --memory {memory} --vram=12 --acpi on --nic1 nat --cpus {cpus} --audio none")
... |
def print_cell(cell):
lattice, positions, numbers = cell
print('lattice vectors')
for vec in lattice:
print('%15.9f %15.9f %15.9f' % (vec[0], vec[1], vec[2]))
print('atomic postions and type')
for coor, atype in zip(positions, numbers):
print('%4d %15.9f %15.9f %15.9f' % (atype, coor... | The function generates CIF data for a crystal structure, including chemical formula, space group details, symmetry operations, and atomic positions. It standardizes the cell, extracts symmetry information, calculates lattice parameters, and formats entries for CIF output. | def make_cifdata(cell, atoms, tol=1.0e-5):
cifdata = []
scell = spglib.standardize_cell(cell)
print('*** scell ***')
print_cell(scell)
dataset = spglib.get_symmetry_dataset(scell, tol)
wyckoffs = dataset['wyckoffs']
equiv_atoms = dataset['equivalent_atoms']
trans_matrix = dataset['tran... |
def read_structure_vasp(filename):
input = open(filename, "r")
input.readline() # comment
scale = float(input.readline())
lattice = []
for i in range(3):
v0 = input.readline().strip().split()
v = list(map(float, [v0[0], v0[1], v0[2]]))
lattice.append([v[0] * scale, v[1] * sc... | The main task of the code is to process crystal structures from CIF/POSCAR files, analyze space group symmetries, compare structures from different inputs (CIF vs. calculation outputs), and generate outputs like POSCAR, KPOINTS, CIF files, and Brillouin zone data for VASP/QE/Abinit. It also validates structural consist... | def main():
arg = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='''
+-+-+-+-+-+-+-+-+-+-+-+-+
C I F L I B
+-+-+-+-+-+-+-+-+-+-+-+-+
author : pearcandy
last update : 2021.2.12
contact vrzxa@example.com''')
arg.add_argument("-c", "--cif", action... |
def getTools(filename):
tool_file = open(filename, "r")
tools = []
for line in tool_file:
name, description, purchase_price, purchase_date, shareable = line.split(",")
newTool = [name, description, purchase_price, purchase_date, shareable]
tools.append(newTool)
return tools
def ... | The main task of the code is to read user data from a CSV file, insert each user's details into a database, and associate them with preloaded tools and categories. It opens the input file, parses each line into user fields, executes an SQL INSERT statement with hashed passwords and current timestamps, then links the us... | def read_users(filename):
user_file = open(filename, "r")
tools = getTools('tools.csv')
cats = getCategories('categories.csv')
for line in user_file:
username, password, first_name, last_name, email = line.split(",")
sql = """
INSERT INTO users (username, password, fi... |
def log(self, level, statement):
self.logger.log(level, "message -- {}".format(statement))
def remove_all_labels(self):
self.log(INFO, "func --> remove_all_labels")
labels = self.get_message_labels()
for label in labels:
self.remove_label(label)
def move_message(self, destina... | The main task of the code is to delete a message by first removing all its labels, moving it to the 'Trash' folder, and then permanently deleting it, with logging for tracking purposes. | def trash_message(self):
self.log(INFO, "func --> trash_message")
self.remove_all_labels()
self.move_message('Trash')
self.delete_message() |
def mu_V(self, ve, vi, adapt, vout):
return (self.E[0]*self.mu_Gei(ve,0) + self.E[1]*self.mu_Gei(vi,1) + self.EL*self.gL - adapt - vout*self.tau_w*self.b + self.a*self.EL)/(self.mu_G(ve, vi) + self.a)
def sigma_V(self, ve, vi, adapt, vout):
return np.sqrt((self.K[0]*ve*(self.U(ve, vi, 0, adapt, vout)*se... | The code calculates the membrane potential's mean, standard deviation, and time constant (tau) using the MPF model. It accepts input parameters ve (excitatory input), vi (inhibitory input), adapt (adaptation current), and vout (output voltage). Default values of 0 are assigned if adapt or vout are not provided. The res... | def run(self, ve, vi, adapt=None, vout=None):
'''
calculates MPF statistical moments
args: ve, vi, adaptation w, vout
returns: membrane potential mean, std, tau (in mV!)
'''
if adapt==None: adapt=0
if vout==None: vout=0
return self.mu_V(ve, vi, adapt, vout... |
def hash_zobrist(self):
h = 0
if self.to_move == BLACK:
h = h ^ self.zobr_black
for sq in range(64):
curr_piece = self.board[sq]
if curr_piece != NO_PIECE:
h = h ^ self.zobr[sq][curr_piece]
return h
def upd... | This function commits a chess move by updating game state variables, including piece positions, half/full move counters, Zobrist hash, and check status. It checks for game-over conditions like checkmate, stalemate, 50-move rule, and threefold repetition, while updating reachable squares and legal move validity. The fun... | def commit(self, move, capture, moved_piece):
fy,fx,ty,tx,_ = move
from_sq, to_sq = YX2INT[(fy,fx)], YX2INT[(ty,tx)]
piece_color, piece_type = PIECE_SPLIT[moved_piece]
# when committing a move, it makes sense to update this variable, as it is the basis for the calculation of next move... |
def search_all_captures(self, alpha, beta):
# see if any good non-captures exist first, otherwise we might return a bad evaluation of a good position if only bad captures are available
evaluation = self.rel_evaluate()
if evaluation >= beta:
return (beta, None)
alpha = max(a... | This function performs a recursive minimax search with alpha-beta pruning to evaluate chess positions and select the best move. It uses transposition tables for memoization, move ordering to optimize pruning, and extensions for deeper analysis of critical moves. The function handles game termination conditions, checkma... | def recursive_search(self, depth, alpha, beta, start_move=None, ext_count=0):
best_move = None
current_hash = self.board.zobr_hash
# early termination if the position was already evaluated
if current_hash in self.transpositions:
if self.transpositions[current_hash][0] >= de... |
def h(p1, p2):
x1, y1 = p1
x2, y2 = p2
return sqrt((x1 - x2)**2 + (y1 - y2)**2)
def reconstruct_path(came_from, current, draw):
while current in came_from:
current = came_from[current]
current.set_status('path')
draw()
def draw(win, grid, size, rows, columns, win_length, win_heig... | This code implements the A* pathfinding algorithm on a grid, using a priority queue to explore nodes. It calculates tentative g-scores (path costs) and f-scores (g + heuristic) for each node, updating the open set with neighbors having lower scores. When the end node is reached, it reconstructs the optimal path via the... | def algorithm(draw, grid, start, end):
count = 0 # count is just a tie breaker
open_set = PriorityQueue()
open_set.put((0, count, start))
came_from = {}
# both g and f scores are initialized to +inf for all squares, then we change it to g=0 and f=h(start, end) for the starting square
g_score = ... |
def make_grid(size, rows, columns, win_length, win_height):
grid = []
for i in range(rows):
grid.append([])
for j in range(columns):
sq = Square(i, j, rows, columns, size)
grid[i].append(sq)
return grid
def draw(win, grid, size, rows, columns, win_l... | This code implements a pathfinding visualization tool using a grid. Users can set start/end points and barriers via mouse clicks. Pressing SPACE initiates an algorithm (likely A* or Dijkstra's) to find the shortest path, with real-time visualization. The 'C' key resets the grid, while 'R' clears start/end points but re... | def main():
grid = make_grid(SQ_SIZE, ROWS, COLUMNS, WIN_LENGTH, WIN_HEIGHT)
start = None
end = None
run = True
while run:
draw(WIN, grid, SQ_SIZE, ROWS, COLUMNS, WIN_LENGTH, WIN_HEIGHT)
for event in pygame.event.get():
if event.type == pygame.QUIT:
... |
def legal_moves(self, onlycaptures=False):
legal = []
# C ext
pseudo_noncaptures, pseudo_captures = pseudo_legal_moves(self.piece_loc[self.to_move],self.board,self.castling_rights[self.to_move],self.to_move,self.en_passant_target)
# python
#pseudo_noncaptures, pseudo_c... | This function compares the number of variations (legal move sequences) between two chess boards up to a given depth. It recursively explores all legal moves, ensuring both boards generate identical move lists. If discrepancies are found, it prints debug info and raises an error. If matches, it counts valid variation pa... | def find_variations_compare(self, depth, comparison_board):
count= 0
if depth == 0:
return 1
# generating legal moves for the current depth
my_movelist = self.legal_moves()
#print(my_movelist)
true_movelist = list(comparison_board.legal_moves)
... |
def is_stringlist(obj: object) -> bool:
return isinstance(obj, Sequence) and all(
[isinstance(elt, str) for elt in obj]
)
def is_strdict(obj: object) -> bool:
return (
isinstance(obj, Mapping)
and is_stringlist(list(obj.keys()))
and is_stringlist(list(obj.values()))
)
def parse_pattern(p... | This function parses a single TCAM rule from a JSON-like input by validating its structure, ensuring required fields exist, verifying integer annotations match input indices, and converting patterns/actions into specific data structures. It returns a tuple of parsed patterns and actions after validation checks. | def parse_rule(table_idx: int, rule_idx: int, rule: object) -> d.Rule:
"""Parse a single TCAM rule."""
error_prefix = "Error parsing rule %s in table %s: " % (rule_idx, table_idx)
if (
not isinstance(rule, Mapping)
or "patterns" not in rule
or "actions" not in rule
or "table" not in rule
... |
def _cache_output_metric_attributes_multi(self, metrics, weighted_metrics):
"""Caches metric name and function attributes for every model output."""
output_shapes = []
for output in self.outputs:
if output is None:
output_shapes.append(None)
else:
... | This method compiles a multi-output model for training, configuring optimizer, loss functions (including L1/L2 regularization variants), metrics, and sample weights. It handles weighted loss combinations, prepares target tensors, and sets up training/test/predict functions. The code supports multiple outputs with disti... | def mcompile(self, optimizer,
loss1=None,
loss2=None,
metrics=None,
loss1_weights=None,
loss2_weights=None,
sample_weight_mode=None,
weighted_metrics=None,
target_tensors=None,
... |
def _standardize_user_data_multi(self, x,
y=None,
sample_weight=None,
class_weight=None,
check_array_lengths=True,
batch_size=None):
... | The `mfit` method trains a machine learning model for a specified number of epochs using provided input data (`x`), target data (`y`), and optional parameters like batch size, validation data, and callbacks. It supports various input formats (NumPy arrays, generators, sequences) and handles validation splitting, shuffl... | def mfit(self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose=1,
callbacks=None,
validation_split=0.,
validation_data=None,
shuffle=True,
class_weight=None,
sample_weight=No... |
def test_llist():
print('\n-------------------- TEST_LLIST ------------------')
data = [3,2,4,35,6,65,6,4,3,21]
llist = LinkedList()
for item in data:
llist.append(item)
print('LinkedList: {}'.format(llist)) # output: 3 2 4 35 6 65 21
print('-------------------- END... | The code defines a test suite function that executes multiple test cases for a linked list implementation, including tests for list creation, empty lists, union operations, intersection operations, and scenarios with no intersection, ensuring the correctness of the linked list's functionalities. | def TEST_SUITE():
test_llist()
test_empty_list()
test_union()
test_union_empty_inputs()
test_intersection()
test_no_intersection() |
def test():
print('\n-------------------- TEST ------------------')
c_files = sorted(find_files('.c', './testdata/testdir')) # sorted for printing
print('{} C-Files are found:'.format(len(c_files))) # output: 4 C-Files are found
print(*c_files, sep='\n') # ... | The main task of the code is to execute a test suite comprising three functions: `test()` for general validation, `test_invalid_path()` for handling invalid file paths, and `test_no_c_file()` for scenarios where a C file is absent. The `TEST_SUITE()` function orchestrates these tests to ensure robustness against edge c... | def TEST_SUITE():
test()
test_invalid_path()
test_no_c_file() |
def test_queue():
print('\n-------------------- TEST_QUEUE ------------------')
queue = PriorityQueue()
queue.enque(Node(character='A', frequency=5))
queue.enque(Node(frequency=2))
queue.enque(Node(frequency=9))
queue.enque(Node(character='B', frequency=5))
print(queue) ... | The code defines a test suite to validate implementations of data structures and algorithms, including queues, priority queues, trees, and Huffman coding. It executes multiple test cases to ensure correctness, handling scenarios like empty data, repetitive inputs, and encoding/decoding processes. | def TEST_SUITE():
test_queue()
test_empty_queue()
test_get_priority_queue()
test_get_priority_queue_empty()
test_tree()
test_huffman_encoding()
test_huffman_decoding()
test_huffman_decoding_repetitive_data()
test_huffman_decoding_empty_data() |
def interact_with_openai_api(msgs: list[dict], functions: list[dict] = None, stream: bool = True, model_name: str = FAST_MODEL_NAME):
"""Call the OpenAI API and handle any potential errors."""
max_retry = 7
retry = 0
while True:
try:
create_params = {
'model': model_n... | The function `filter_results_in_threads` evaluates search results in parallel threads to assess their relevance to a given query. It uses an AI model to score each result (0-4) based on title, URL, and content. Results scoring ≥3 are added to a shared list using a lock for thread safety. If a result scores 4, its conte... | def filter_results_in_threads(question, sliced_results, results, lock):
"""Evaluate search results in parallel threads based on their relevance."""
for r in sliced_results:
msgs = [
{
"role": "system",
"content": f"""Task Description:
You are a Search Result ... |
def interact_with_openai_api(msgs: list[dict], functions: list[dict] = None, stream: bool = True, model_name: str = FAST_MODEL_NAME):
"""Call the OpenAI API and handle any potential errors."""
max_retry = 7
retry = 0
while True:
try:
create_params = {
'model': model_n... | The main task of the code is to initiate a program that generates search queries for a user question about dispersed camping in Utah, executes web and Wikipedia searches using AI-generated queries, consolidates results, and saves them to a file. It parses command-line arguments for search result limits, interacts with ... | def _start():
"""
Initiates the main execution of the program.
This function performs the following tasks:
1. Defines a question regarding dispersed camping sites in Utah.
2. Queries an expert web research agent to generate a relevant search query.
3. Executes a web search using the generated q... |
def read_user():
print("reading user data...")
pd.set_option('display.max_columns', None)
global longitude, latitude
longitude, latitude = user_location()
date = selected_date.strftime("%Y-%m-%d")
user_data = pd.DataFrame({'date': [date], 'latitude': [latitude], 'longitude': [longitude]})
u... | The main task of the code is to predict weather conditions (min/max/avg temperature and pressure) using machine learning models, display results via a Streamlit interface, categorize weather based on average temperature, provide tailored suggestions, and store prediction data in a database. It processes user inputs, ap... | def main():
import datetime as dt
print("STARTED ...")
user_data = read_user()
cleaned_data = clean_data(user_data)
standardized_data = standardize(cleaned_data)
input_variables = standardized_data
print('printing input variables', input_variables)
input_v = np.array(input_variables)
... |
def new_expense(edited=False):
# edited=True if this is called from edit_transaction
name = request.form['name']
#Parse the name field to separate names by commas
names = name.split(',')
names = [n.lstrip() for n in names if n.lstrip()]
amounts = request.form.getlist('amount')
envelope_ids = request.form.... | The function edits a transaction by deleting the existing one and creating a new entry based on the provided type (e.g., expense, transfer, income). It returns a JSON response confirming the edit, appending a health error if detected, along with a flag indicating scheduled transaction submission status. | def edit_transaction():
sched_t_submitted = False #This has to be here or else the javascript side breaks
id = int(request.form['edit-id'])
type = int(request.form['type'])
delete_transaction(id)
if (type == BASIC_TRANSACTION):
new_expense(True)
elif (type == ENVELOPE_TRANSFER or type == ACCOUNT_TRANSFE... |
def edit_account(id, name, balance):
#updates account balalnce and name, then subtracts the change in balance from the unallocated envelope
with conn:
current_balance = get_account_balance(id)
diff = current_balance - balance
unallocated_balance = get_envelope_balance(1)
new_unal... | This function synchronizes a database with provided old and new account lists by updating existing accounts, inserting new ones, and deleting accounts no longer present in the old list. | def edit_accounts(old_accounts, new_accounts):
# updates database given 2 lists of account objects
c.execute("SELECT id FROM accounts WHERE deleted=0")
account_ids = c.fetchall()
old_ids = []
# adds id to old_ids then updates the info for the old accounts
for a in old_accounts:
old_ids.a... |
def fetch_calendar_meetings(
calendar: caldav.Calendar, start_time: datetime, end_time: datetime
) -> list[caldav.Event]:
"""Fetch all events from calendar in time interval"""
logging.info(f"Get events from {start_time} to {end_time}")
events_fetched = []
try:
events_fetched = calendar.date... | (The code initializes a calendar, fetches upcoming meetings from specified calendars, filters events belonging to the user, and exports the filtered meetings into an org-file format. It processes multiple calendars, aggregates events, logs statistics, and writes results to a file.) | def main(my_principal: caldav.objects.Principal) -> None:
"""Init calender, fetch meetings, filter my meetings, dump in org-file"""
events_fetched = []
today = datetime.now()
end = today + timedelta(days=config.days)
for calendar_name in config.calendars:
logging.info(f"process calender <{c... |
def _flatten(self, x):
return x.view(x.size(0), -1)
def _forward_pass(self, x_train):
'''
TODO: The method should return the output of the network.
'''
pass
def _backward_pass(self, y_train, output):
'''
TODO: Implement the backpropagation algorithm responsible fo... | The code trains a neural network model over multiple epochs using a training and validation data loader. It tracks training and validation accuracy metrics in a history dictionary, updating them after each epoch. The model performs forward and backward passes, updates weights via an optimizer, and returns the accuracy ... | def fit(self, train_loader, val_loader):
start_time = time.time()
history = {'accuracy': [], 'val_accuracy': []}
for iteration in range(self.epochs):
for x, y in train_loader:
x = self._flatten(x)
y = nn.functional.one_hot(y, 10)
sel... |
def _forward_pass(self, x_train):
'''
TODO: Implement the forward propagation algorithm.
The method should return the output of the network.
'''
pass
def _backward_pass(self, y_train, output):
'''
TODO: Implement the backpropagation algorithm responsible for updat... | The main task of the code is to train a machine learning model over multiple epochs by iterating through training data, performing forward and backward passes to compute weight gradients, updating model weights, and tracking training and validation accuracy metrics in a history dictionary for each epoch. | def fit(self, x_train, y_train, x_val, y_val):
history = {'accuracy': [], 'val_accuracy': []}
start_time = time.time()
for iteration in range(self.epochs):
for x, y in zip(x_train, y_train):
output = self._forward_pass(x)
weight_gradients = self._bac... |
def reset_hercules(self,clpa=False):
print('[AUTOMATION] Restarting hercules')
self.quit_hercules(msg=False)
# drain STDERR and STDOUT
while True:
try:
line = self.stdout_q.get(False).strip()
except queue.Empty:
break
whil... | The code initializes a system (likely Hercules) by resetting it with CLPA options if specified, sending IPL commands, and waiting for specific status confirmations like "IKT005I TCAS IS INITIALIZED" to ensure proper initialization. | def ipl(self, step_text='', clpa=False):
print(step_text)
self.reset_hercules(clpa=clpa)
#self.wait_for_string("0:0151 CKD")
if clpa:
self.send_herc("ipl 150")
self.wait_for_string("HHC00010A Enter input for console 0:0009")
self.send_oper("r 0,clpa")... |
def rotate_check_column_border(img,th3,angle,scaling_factor,imgshape_f):
th4=rotate(th3,angle,value_replace=0)
th_sum00=np.sum(th4,axis=0)
empty_spc_clm=np.where(th_sum00<(np.min(th_sum00)+100))[0]
empty_spc_clm_dif=np.ediff1d(empty_spc_clm)
Column_boundries=(empty_spc_clm[np.where(empty_spc_clm_dif... | This code extracts three columns from an image by applying blurring, resizing, denoising, thresholding, and morphological operations to identify column boundaries. If initial detection fails, it rotates the image at varying angles to find valid boundaries. If still unsuccessful, it delegates to helper functions to extr... | def Column_main_Extracter(img,orignal_img,scaling_factor):
blur_cr_img=cv2.blur(img,(13,13))
crop_img_resize=cv2.resize(blur_cr_img, None, fx=scaling_factor/2, fy=scaling_factor/2, interpolation=cv2.INTER_AREA)
crop_img_resize_n=cv2.fastNlMeansDenoisingColored(crop_img_resize,None,10,10,7,21)
crop_img_... |
def Header_Boundary(img,scaling_factor):
crop_img=img[:1200,:6800,:].copy()
blur_cr_img=cv2.blur(crop_img,(7,7))
crop_img_resize=cv2.resize(blur_cr_img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
crop_img_resize_n=cv2.fastNlMeansDenoisingColored(crop_img_resize,None,10,10,... | This code processes an image by cropping it into specific regions, adding borders, rotating segments based on detected angles, and applying blur to extract and save detailed parts of the image, likely for structured data extraction or analysis. | def get_croped_images(image_path):
img=cv2.imread(image_path)
img_height,img_width,_=img.shape
scaling_factor=0.25
max_start=Header_Boundary(img,scaling_factor)
orignal_img=img[max_start:,:,:]
img = cv2.copyMakeBorder(orignal_img,top=int(orignal_img.shape[1]/40),bottom=int(orignal_img.shape[1]... |
def get_row_coordinates(self, index):
return ((index, i) for i in range(9))
def get_column_coordinates(self, index):
# returns the items (as generator) in the column in the index-th place (0-8)
return ((i, index) for i in range(9))
def get_block_coordinates(self, index):
# returns the it... | This function generates a dictionary mapping each coordinate (y, x) in a specified container type (row, column, or block) to the set of valid digits for that slot. It validates the container type, retrieves coordinates using the corresponding method, and populates the dictionary with valid digits for each slot via `val... | def valids_for_slot_in_conatiner(self, container_type, index):
# returns a dictionary with 9 key-value pairs (tuple- slot coordinate, set - valid digits for the slot)
temp = {}
container_funs = {"row": self.get_row_coordinates(index), "column": self.get_column_coordinates(index),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.