dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def __get_middleware_environment_reference(self, locale: str):
if locale == "en":
return Environment.get().MIDDLEWARE_ADD_THOUGHT_EN
elif locale == "hr":
return Environment.get().MIDDLEWARE_ADD_THOUGHT_HR
else:
raise LocaleError
def __get_doc(self, locale: str... | The code's main task is to save a 'thought' object by sending its data to a remote middleware API, updating a document and reference in a database, and triggering a Firebase push notification. It processes the thought's locale and item ID to determine the correct database and API endpoints for storage and notification ... | def write(self, thought: Thought):
self.remote_database.get_middleware_post_request(
data=thought.remote_dict(),
api=self.__get_middleware_environment_reference(thought.locale.name.lower())
)
self.__get_doc(thought.locale.name.lower(), thought.itemId).set(thought.remote_d... |
def moveRight():
global champ_size
global champ_position
champ_position['x'] += champ_size
w.moveto(mychamp,champ_position['x'],champ_position['y'])
print('>Right Dim (X): ' , champ_position['x'])
## check posible right squares note here we did check after new position of hero so it <= last_righ... | This function handles real-time keyboard input for a game character's movement (arrow keys) and spell casting (Q/W/E/R), applying controlled delays to regulate speed. It updates the character's position, logs actions, and maintains a compass state, ensuring movement only occurs at predefined intervals to prevent excess... | def moveChamp(event):
# this very important point in game and in later levels it define how speed of user in attack or in move later
# can have delay for move that with boots and delay for attack q and w and e and r depend on training and level
global oldepoch
global mychamp
global current_right
... |
def create_lf(self, mode='random'):
"""sample a random scalar to scale loads"""
if mode == 'random':
self.manipulate['lf'] = np.random.uniform(low=0.95, high=1.05, size=(1))[0]
def create_topology(self,br2open=[], br2close=[]):
"""randomly sample branches(lines) that will be openned/... | This code initializes a power system case simulation, setting up pre- and post-contingency scenarios. It configures system parameters, creates topology and load factors, runs simulations to check feasibility, and iteratively adjusts settings if the post-contingency state is infeasible. The class manages branch/transfor... | def __init__(self, case_name, c_type, argvs, manipulate = None, contingency = None, auto_create=True):
np.random.seed()
#raw case data file
self.case_name = case_name # a string
self.Niter = dict() #iterations needed to solve PF, e.g. self.Niter['methodname'] = 10
self.x = dict()... |
def makeYbus(self):
Ybus = makeYbus(self.bus_key_dict, self.Nbus, self.branch, self.shunts)
self.Ybus = Ybus
return Ybus
def makeJ(self):
#make J from node features, feature=[busnum, Vr, Vi, Pinj, Qinj, Irinj, Iiinj, Qshunt,...]
J = makeJ(self.bus_key_dict, self.Nbus, self.bus)
... | The code updates the power system model by removing branches or buses based on a contingency scenario (e.g., line/substation outages), then recalculates the admittance matrix (Ybus) and Jacobian (J) to reflect post-contingency conditions. It maintains pre-contingency matrix sizes for sensitivity analysis, ensuring cons... | def update_case(self,contingency):
#contingency is a dictionary, having keys: 'type','location', and 'parameter'
#update self.bus,self.bus_key_dict and self.branch, according to contingency
"""Note that we typically do not change the size of Y and J,
even if some buses are off after cont... |
def draw_grid():
"""Draw 9x9 soduku board grid and border lines"""
for i in range(0, 10):
# Thicker borders
line_width = 2
if i % 3 == 0:
line_width = 4
# Draw horizontal & vertical grid lines
pygame.draw.line(screen, (0, 0, ... | The main task of the code is to run a Sudoku game loop using Pygame, handling user interactions, displaying the game board, timer, error count, and buttons. It loads and scales game assets, processes mouse clicks for board selection and menu navigation, updates the game state, and maintains the display with a 60 FPS up... | def main():
"""Main display for the game (main function)"""
screen.fill((154, 182, 217))
# Images
board_bg = pygame.image.load('Assets/Game/white_bg.jpg').convert_alpha()
menu_bg = pygame.image.load('Assets/Game/cream_bg.jpeg').convert_alpha()
border_img = pygame.image.... |
def numOfLines(file):
with open(file) as f:
count = sum(1 for _ in f)
return count
def initial(): # To calculate the extreme points to make the initial simplex
x_min_temp = 10**9
x_max_temp = -10**9
y_min_temp = 10**9
y_max_temp = -10**9
z_min_temp = 10**9
z_max_temp = -10**9
for i in range(num):
if po... | The code computes the convex hull of a set of 3D points from input data. It reads points, validates their count, constructs an initial tetrahedron, iteratively expands the hull by identifying and adding planes, removing internal structures, and forming new faces. Finally, it outputs the number of vertices in the convex... | def make_hull(fdata):
global points
global num
global list_of_planes
points = [] # List to store the points
# if len(sys.argv) < 2:
# print "Few arguments. See README for help"
# sys.exit()
try: # Open the input and store it in points list
data = open(fdata, "r")
num = numOfLines(fdata)
for line in da... |
def make_visualization_dic(state_machine):
visualization_dic = {}
for state in state_machine.states:
t = state.t
predicates = state.predicates
for predicate_name in predicates.keys():
predicate = predicates[predicate_name]
try:
type(predicates[pred... | The function `run_visualization` generates visualizations (line plots or bar graphs) from a `StateMachine` based on user-specified parameters. For line plots, it requires a single predicate-agent pair; for bar graphs, a list of tuples with predicate, agent, and value, along with a timestep count. It uses helper functio... | def run_visualization(StateMachine, plot_type, predicate_to_plot, time):
"""Input is the StateMachine, the plot type('line' or 'bar') and then what you want to plot as a list.
If you wish to do a line plot then your list is one predicate and agent(you can only plot one at a time).
Thus your list will be ['... |
def vornoi(graph, path, characters, center_nodes):
g = createSubGraph(graph, path, characters)
return nx.voronoi_cells(g, center_nodes)
def translate_voting(g, path, characters, ancors, dict_characters):
d = dict()
for i in voting_partition(voting(g, path, characters, ancors), ancors).values():
... | The main task of the code is to analyze graph partitions and community structures using multiple algorithms. It computes Voronoi partitions, voting-based partitions (for directed/undirected weighted/unweighted graphs), and applies community detection methods like modularity, Girvan-Newman centrality, clique percolation... | def Question3(g, path, characters, center_nodes, ancors, dict_characters, colors):
# # part d
print('part d:')
vornoi_partition = vornoi(g, path, characters, center_nodes)
print('vornoi_partition', vornoi_partition)
vot_part = translate_voting(nx.MultiDiGraph(g), path, characters, ancors, dict_chara... |
def __groupName__(self, bands):
bands_name = '_'.join(bands)
subset_name = "None" if self.__subset is None else '_'.join([str(i) for i in self.__subset])
return bands_name + "x" + subset_name + "x" + self.__subsetMode
def __openBandsGroup__(self, bands):
if self.multibandDataset is None:... | The function retrieves or creates a band group. It converts the input band to a string, generates a group name, checks if the group exists in a dictionary. If not, it opens the band data, loads it into the dictionary, and returns the corresponding group. | def band(self, band):
bands = [str(band)]
group = self.__groupName__(bands)
if not group in self.__bandsGroups__:
ds, bs = self.__openBandsGroup__(bands)
self.__bandsGroups__[group] = self.__loadBand__(group, ds[0], bs[0])
return self.__bandsGroups__[group] |
def __groupName__(self, bands):
bands_name = '_'.join(bands)
subset_name = "None" if self.__subset is None else '_'.join([str(i) for i in self.__subset])
return bands_name + "x" + subset_name + "x" + self.__subsetMode
def __openBandsGroup__(self, bands):
if self.multibandDataset is None:... | This function groups input bands into a predefined structure, validating minimum two bands. It converts bands to strings, generates a group name, and either retrieves an existing group or creates a new one by opening and loading the bands data. The group is stored in a dictionary for future access and returned. | def bandsGroup(self, bands):
if len(bands) < 2:
raise ValueError("Bands Group require two bands minimum")
bands = [str(band) for band in bands]
group = self.__groupName__(bands)
if not group in self.__bandsGroups__:
ds, bs = self.__openBandsGroup__(bands)
... |
def traverse_metadata(self, metadata_root: str) -> dict:
"""Function to extract metadata from XML."""
# Searching for complexType and simpleType XML elements
for element_type in ["complexType", "simpleType"]:
root_element = self.root_node.find(
f".//{NS}{element_type}... | The code's main task is to perform data extraction by traversing specified metadata types, processing messages, and generating WSDL (Web Services Description Language) output. The method iterates through metadata types using `traverse_metadata`, executes `traverse_messages` for message handling, and finalizes with `gen... | def extract(self) -> None:
"""Method to perform the extraction process."""
for metadata_type in self.metadata_types:
self.traverse_metadata(metadata_type)
self.traverse_messages()
self.generate_wsdl() |
def calc_arr(type_: str, rewards: np.array, reb_freq: int) -> float:
# Calculate the Annualized Rate of Return (ARR) in Percentage (%)
return np.mean(rewards * 100) * get_num_trading_per_year(type_=type_, reb_freq=reb_freq)
def calc_avol(type_: str, rewards: np.array, reb_freq: int):
# Calculate the Annuali... | The code computes and prints financial performance metrics for a list of rewards. It calculates metrics like fPV (product of rewards +1), ARR (annualized return), AVol (annualized volatility), ASR (annualized Sharpe ratio), SoR (sortino ratio), MDD (maximum drawdown), and CR (calmar ratio) using helper functions. These... | def get_exp_res(self, r_lst):
fpv = np.prod(r_lst + 1.0)
arr = calc_arr(type_=self.m_args['type_'], rewards=r_lst, reb_freq=self.m_args['reb_freq'])
avol = calc_avol(type_=self.m_args['type_'], rewards=r_lst, reb_freq=self.m_args['reb_freq'])
mdd = calc_mdd(rewards=r_lst)
asr = c... |
def get_all_transitions(self, mode: str):
self.env.set_mode(mode)
s, g = self.env.reset()
s_lst, a_lst, r_lst, d_lst, g_lst, pl_lst, tot_fee_lst, diff_lst, cr_o_lst = \
[], [], [], self.env.d_trn if mode == 'train' else \
self.env.d_val if mode == 'validation' else self.... | The code retrieves validation transitions, formats and prints asset weights and returns as percentages, visualizes action distributions, and generates experimental results using the retrieved return values. | def exp1(self):
s_lst, a_lst, r_lst, d_lst, g_lst, pl_lst, tot_fee_lst, diff_lst, cr_o_lst = \
self.get_all_transitions(mode='validation')
print('\t'.join(['cash', *[str(asset_) for asset_ in self.m_args['assets']], 'return']))
for _idx, action in enumerate(a_lst):
_form... |
def transform_labels_to_multilabel(df, old_cols, new_cols):
for col in new_cols:
name, status = col.split('_')[:-1], col.split('_')[-1]
name = '_'.join(name)
if status == 'ok':
df.loc[:,col] = np.where(df.loc[:, name] == 'ok' , 1, 0)
elif status == 'high':
... | The main task of the code is to train and evaluate a multi-label classification model for predicting health-related targets (e.g., cholesterol, hemoglobin) using spectral and environmental features. It performs cross-validation with multiple seeds, averages results, and saves out-of-fold predictions and test outputs. T... | def main(args):
global DEVICE
pprint(args)
with open(f'{args.model_output_folder}/{args.model_name}.json', 'w') as f:
json.dump(vars(args), f)
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
train = pd.read_csv(f'data/{args.train_csv}')
test... |
def _validation_set(env: gym.Env, device: torch.device) -> torch.Tensor:
frame, _ = env.reset()
next_state = _initial_state(frame, device)
states = [next_state]
terminal = False
while not terminal:
state = next_state
action = env.action_space.sample()
frame, _, terminal, _, _... | The code trains a Deep Q-Network (DQN) agent for the Pong game using experience replay and target network updates. It initializes the environment, neural networks, optimizer, and memory buffer. The agent interacts with the environment, collects experiences, and updates the Q-network via gradient descent. Periodic targe... | def train(args: argparse.Namespace) -> None: # pylint: disable=R0914
env = gym.make("ALE/Pong-v5", repeat_action_probability=0)
env = gym.wrappers.RecordEpisodeStatistics(env)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
q_network = DQN(n_actions=env.action_space.n).to(device) ... |
def compile() -> dict[str, str]:
lib: Lib = Lib()
for file in LUA_FILES:
lib.add_from_file(file)
return {name: compile_file(lib.snippets[name]) for name in COMPILED}
def parse_json() -> str:
with open('protocol.json') as f:
protocol_definition = json.load(f)
result_str: str = ''
for id, definition in protocol... | The main task of the code is to compile configuration data, validate trusted mode settings, and process microcontrollers. It loads environment variables, checks for an 'install' command-line argument, compiles protocol data, sets trusted mode from an environment variable, validates its value, and iterates over microcon... | def main():
load_dotenv()
do_install: bool = len(sys.argv) >= 2 and sys.argv[1] == 'install'
compiled: dict[str, str] = compile()
compiled['protocol'] = parse_json()
compiled['trusted_mode'] = (getenv('TRUSTED_MODE') or 'true').lower()
assert compiled['trusted_mode'] in ('true', 'false'), 'Only true or false are ... |
def readFasta(filename):
with open(filename) as f:
genome = ''
for line in f:
if line[0] != '>':
genome += line.strip()
return genome
def minSkew(genome):
skewList = skew(genome)
minSkew = min(skewList)
minSkewPos = []
for i in range(len(skewList)):
... | The code identifies frequent 9-mer DNA motifs in a 500bp segment of the Salmonella genome, allowing 1 mismatch and reverse complements, to detect potential regulatory sequences or replication origins. | def solveSalmonella():
genome = readFasta('data/Salmonella_enterica.txt')
minSkews = minSkew(genome)
minGenomes = genome[minSkews[0]:minSkews[0]+500]
print(len(minGenomes))
boxes = frequentWordsWithMismatchesAndReverseComplements(minGenomes, 9, 1)
for box in boxes:
print(box, end=' ') |
def setTrain(self):
for model in self.models.values():
model.train()
def processBatch(self, inputs):
for key, value in inputs.items():
inputs[key] = value.to(self.device)
origScaleColorAug = torch.cat([inputs[("color_aug", fi, 0)] for fi in self.frameIdxs])
allFra... | The main task of the code is to train a neural network for one epoch by iterating through batches of training data, computing model outputs and losses, performing backpropagation with an optimizer, updating model parameters, and periodically logging training progress and validating model performance. The epoch includes... | def runEpoch(self):
self.setTrain()
for batchIdx, inputs in enumerate(self.trainLoader):
startTime = time.time()
outputs, losses = self.processBatch(inputs)
self.optimizer.zero_grad()
losses["loss"].backward()
self.optimizer.step()
... |
def load_pickle(path: str, fname: str):
'''
load pickle data from file
Parameters
----------
path : str
load path
fname : str
file name
Returns
-------
_type_
loaded pickle
'''
with open(os.path.join(path, fname), 'rb') as f:
return pickle.lo... | This function registers cropped images by aligning segments across days. It checks if registration is needed, pads images to a common size, stacks them, performs registration, and saves results. Metadata is stored if registration is performed, ensuring each image is processed once. | def regi_cropped_img(crop_path: str='./crop_data', regi_path: str='./registration'):
if len(os.listdir(crop_path))==0: # if there is no cropped image
logger.debug('The is no cropped image for registration. Do the image crop first')
return
for img_id in os.listdir(crop_path): # get cropped image... |
def to_bag() -> None:
if bag := FindType(MINING_BAG, Backpack()):
while FindType(ORE, Backpack()):
MoveItem(FindItem(), -1, bag, 0, 0, 0)
Wait(1000)
def smelt():
IgnoreReset()
forge_x, forge_y = FORGE_LOCATION
newMoveXY(forge_x, forge_y, True, 1, True)
while LastCont... | The code automates mining by moving to a specified tile, managing inventory (smelting when overloaded), crafting tools if missing, and handling interactions with the game environment. It loops until the character dies, continuously attempting to mine while ensuring tools are available and weight limits are respected. | def mine(tile):
tile, x, y, z = tile
if newMoveXY(x, y, True, 1, True):
while not Dead():
# Smelt and return back to mining point
if Weight() > 220:
to_bag()
if Weight() > 250:
smelt()
newMoveXY(x, y, True, 1... |
def to_bag() -> None:
if bag := FindType(MINING_BAG, Backpack()):
# Can't use while cuz of item limit in bag
if FindType(ORE, Backpack()):
for ore in GetFoundList():
MoveItem(ore, -1, bag, 0, 0, 0)
Wait(1500)
def smelt():
IgnoreReset()
forge_x, for... | This code automates mining in a game by moving to a tile, managing inventory weight thresholds, using/crafting tools, smelting ore, and handling navigation blocks via journal messages. It loops until death, packing/smelting/unloading items while attempting to mine at coordinates (x,y,z). | def mine(tile):
tile, x, y, z = tile
if newMoveXY(x, y, True, 2, True):
while not Dead():
# Smelt and return back to mining point
if Weight() > WEIGHT_TO_PACK:
Wait(1000)
to_bag()
if Weight() > WEIGHT_TO_SMELT:
... |
def exitClient(self):
"""Teardown button handler."""
if self.state != self.INIT:
request = RtspPacket(self.TEARDOWN, self.fileName, self.rtspSeq, self.rtpPort).generate()
response = self.sendRtspRequest(request)
print(response[0].split(' ')[1])
if int(response[0].split(' ')[1]) == 200:
print("Server... | The main task of the code is to continuously update the GUI with video frames by retrieving and displaying frames from a buffer, managing playback state, handling frame loss errors, and terminating the thread when instructed. It sleeps between frames, checks for stop conditions, updates frame counters, and exits the cl... | def runMovie(self, stop):
"""Update the image file as video frame in the GUI."""
while True:
sleep(self.DEFAULT_TIME_CLOCK/1000)
# print(f"Movie Thread stop(): {stop()}")
if stop():
print("Movie Player thread is safe to termintate")
break
if self.state != self.PLAYING:
continue
try:
i... |
def openRtpPort(self):
"""Open RTP socket binded to a specified port."""
#-------------
# TO COMPLETE
#-------------
# Create a new datagram socket to receive RTP packets from the server
self.rtpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set the timeout value of the socket to 0.5sec
# .... | The main task of the code is to handle the setup of an RTP stream by sending an RTSP SETUP request, transitioning the state to READY, initializing variables for tracking video data, and preparing to receive RTP packets. It opens an RTP port, resets frame-related counters, and retrieves video information to enable subse... | def setupMovie(self):
"""Setup button handler. Starting RTP receiving thread"""
if self.state == self.INIT:
self.isRtpThreadStopped = False
self.isVideoThreadStopped = False
self.openRtpPort()
#Set up movie:
request = RtspPacket(self.SETUP, self.fileName, self.rtspSeq, self.rtpPort).generate()
res... |
def playMovie(self):
"""Play button handler. Trigger server RTP socket sending frame"""
if self.state == self.INIT:
self.setupMovie()
if self.state != self.READY:
return
if not self.isReceivingRtp: # prevent multiple similar thread
self.rtpThread = threading.Thread(target=self.listenRtp, args=(lambda: ... | The main task of the code is to switch between movies in an RTSP client by sending a SWITCH request, retrieving a list of available filenames from the server, allowing user selection via a menu, and updating the state and connections accordingly. If the selected file differs from the current one, it tears down the old ... | def switchMovie(self):
if self.state == self.INIT:
self.playMovie()
if self.state != self.READY:
self.pauseMovie()
self.state = self.SWITCH
request = RtspPacket(self.SWITCH, self.fileName, self.rtspSeq, self.rtpPort).generate()
# To be implemented: server reponse with dictionary containing array of s... |
def compare_folder_with_file(folder, path):
if not os.path.isdir(folder):
return True
if not os.path.isfile(path):
return False
time_folder = get_time_folder(folder)
time_path = get_time_path(folder)
return (time_folder < time_path)
def constant():
table = {
"width_window": 1600,
... | This function processes screenshots by splitting them into vertical strips based on brightness thresholds, applying image enhancements to thin strips, and saving each strip as a PNG file in a structured directory. It checks for existing files/folders, handles cropping warnings, and uses PIL/NumPy for image manipulation... | def shred_photograph(whether_new, folder_strip, folder_shot):
print("! ! ! Shredding screenshots ! ! !")
suffix_in = ".png"
suffix_out = ".png"
for name_shot in os.listdir(folder_shot):
if not name_shot.endswith(suffix_in):
continue
bare_graph = name_shot[:-len(suffix_in)]
path_gr... |
def compare_folder_with_folder(this_folder, that_folder):
if not os.path.isdir(this_folder):
return True
if not os.path.isdir(that_folder):
return False
time_this = get_time_folder(this_folder)
time_that = get_time_folder(that_folder)
return (time_this < time_that)
def constant():
table = ... | The code processes PNG images from a source folder (`folder_strip`), combining them into larger composite images ("leaf" pages) based on height constraints. It checks if new processing is needed, skips unchanged folders, and iterates through strips, appending them to a leaf image while managing layout limits. When the ... | def patch_leaf(whether_new, folder_leaf, folder_strip):
if whether_new:
if not compare_folder_with_folder(folder_leaf, folder_strip):
return
print("! ! ! Patching pages ! ! !")
suffix_in = ".png"
suffix_out = ".png"
height_inner = constant()["height_inner"]
limit_switch = constant()["li... |
def get_date(stamp):
month = get_month(stamp)
day = get_day(stamp)
date = day + ' ' + month
return date
def unify_name(source):
sink = source
genres = give_genres()
elisions = {value: key for key, value in genres.items()}
if sink in elisions:
sink = elisions.get(sink)
return sink
... | The function generates an HTML anchor tag linking to a page using the formatted month and date from the input `stamp`, returning the formatted string if `stamp` is non-empty, otherwise returning `None`.) | def write_element_stamp(stamp):
if not stamp:
return None
date = get_date(stamp)
sink = (
"<a class=\"data-stamp\"" + ' '
+ "href=\"/page/{}.html\">{}</a>"
).format(unify_name(get_month(stamp)), date)
return sink |
def extract_title(folder_cipher):
many_title = []
suffix = ".txt"
for name in os.listdir(folder_cipher):
path = os.path.join(folder_cipher, name)
if os.path.isfile(path):
if not name.endswith(suffix):
continue
bare = name[:-len(suffix)]
many_title.append(bare)... | The main task of the code is to manage directory structures and process image data based on the `whether_new` flag. It creates or deletes folders like "shot", "strip", and "leaf" under "book", extracts titles from "post-cipher", and sequentially triggers image processing steps: capturing photographs, shredding them, an... | def main(whether_new):
folder_this = os.path.dirname(__file__)
folder_cipher = os.path.join(folder_this, "post-cipher")
folder_book = os.path.join(folder_this, "book")
folder_shot = os.path.join(folder_book, "shot")
folder_strip = os.path.join(folder_book, "strip")
folder_leaf = os.path.join(folder_bo... |
def check_group(member):
group = []
if (isinstance(group, list)):
group = member
else:
group = [member]
return group
def write_element_heading(title, name):
if not title:
return None
sink = ''
if not name:
sink = (
"<span class=\"heading\">"
+ "{}</span>".f... | This function generates a formatted entry by replacing placeholders in the input `source` string with content derived from the `record` dictionary. It processes fields like title, timestamp, genre, series, and tags, using helper functions to create corresponding elements. Missing fields result in placeholder removal. T... | def write_entry(source, record, name):
sink = source
heading = record.get("title")
stamp = record.get("stamp")
elision = record.get("genre")
many_tag = check_group(record.get("tag"))
series = record.get("series")
if heading is not None:
element = write_element_heading(... |
def write_title(title):
sink = "<title>{}</title>".format(title)
return sink
def write_element_display(title, name):
if not title:
return None
sink = ''
if not name:
sink = (
"<span class=\"display\">"
+ "{}</span>".format(title)
)
else:
sink = (
"<a ... | The code generates an HTML page by combining static templates and dynamic content from records. It replaces placeholders in the header and entry sections, constructs the HTML structure, and assembles the final output as a string. | def write_page(matter, folder_post, heading, many_record):
many_whole = []
head = matter["head"].replace("$TITLE", write_title(heading))
header_banner = matter["header_banner"]
header_page = matter["header_page"].replace(
"$HEADING",
write_element_display(heading, None)
)
footer = matter["... |
def stringify_files(file_dictionary):
file_string = ""
for file in file_dictionary:
file_string += f"{file}\n"
file_string += f"```\n{file_dictionary[file]}\n```\n"
file_string += "-----\n"
return file_string
def process_rewrite(self, output):
logger.d... | The main task of the code is to iteratively generate and evaluate code revisions using a tree-based approach, aiming to achieve a goal by exploring multiple hierarchical levels of modifications. It employs AI model prompts to create new file versions, scores them, and builds a node tree of potential solutions, returnin... | def chain_plan_and_execute_lats(self, generation_per_level=3, max_height=3, execution_prompt_type="rewrite"):
root = Node(self.files, Reflection(feedback="The goal has not yet been implemented.", score=0, found_solution=False))
if execution_prompt_type == "rewrite":
system_prompt = prompts.A... |
def display_text(stdscr, text,start_col,color_pair_id):
global line_counter
mrows, mcols = stdscr.getmaxyx()
stdscr.refresh()
time.sleep(0.2)
j=0
if line_counter >= mrows-5:
line_counter = 1
stdscr.clear()
time.sleep(1)
line_counter = 0
stdscr.refresh()
... | The function handles a scenario where the hero drops their weapon after an enemy attack, prompting the user to choose between attempting to retrieve the weapon or seeking help, leading to different combat outcomes or assistance based on the input. | def tool_drop(stdscr,key,enemy_name :str,enemy_health: int,enemy_weapon, hero_health: int,hero_weapon,power):
global line_counter
display_text(stdscr,f"The {enemy_name}'s ferocious attack forces you to relinquish your weapon, the force of the blow knocking it from your grasp.\n",1,4)
time.sleep(1)
displ... |
def type(stdscr,message,i):
for char in message:
stdscr.addstr(char,curses.color_pair(i))
stdscr.refresh()
time.sleep(0.05)
def left(stdscr):
type(stdscr,"You are back at the crossroad.Where to look for the lamp? \n",3)
type(stdscr," 1) right 2)middle\n",1)
... | This code presents a text-based adventure game scenario where the player navigates a crossroad, choosing directions (left, middle, right) to progress through a story involving finding fuel and a lamp. Based on choices, it directs to different functions (left, middle, right) or restarts with error handling, advancing th... | def torch(stdscr):
type(stdscr,"You need to save the light's fuel.\n Quick use it to look for something else to light the way \n",3)
type(stdscr,"while searching for the fule , You find your self at a crossroad \n",3)
type(stdscr,"whitch way you want to go ?\n",2)
type(stdscr," 1) left 2) m... |
def display_text(stdscr, text,start_col,t):
global line_counter
stdscr.refresh()
time.sleep(0.2) # Wait for a second before displaying each letter
for i in range(len(text)):
stdscr.addch(line_counter, start_col + i, text[i],curses.color_pair(t) | curses.A_ITALIC)
stdscr.refresh()
... | The code defines a text-based adventure game function 'hallway' that presents navigation choices in a hallway. It handles user input to direct the player to the living room (which leads back to the hallway) or the kitchen. In the kitchen, players choose between checking a cabinet (finding a torch without batteries) or ... | def hallway(window):
key2 ='0'
display_text(window,"You are in the hallway. Which way do you want to go?\n",0,3)
display_text(window,"1.Left into the living room\n",0,4)
display_text(window,"2.Right into the kitchen\n",0,4)
key1 = window.getkey()
if key1 == '1':
... |
def display_text(stdscr, text,start_col,t):
global line_counter
stdscr.refresh()
time.sleep(0.2) # Wait for a second before displaying each letter
for i in range(len(text)):
stdscr.addch(line_counter, start_col + i, text[i],curses.color_pair(t) | curses.A_ITALIC)
stdscr.refresh()
... | The code presents a text-based interactive choice where the user selects a door (left or right). Choosing the left door triggers a recursive loop requiring a key, while the right door leads to discovering a key amid spiders and invoking a 'spiders' function. Invalid inputs prompt retries, ensuring user-driven navigatio... | def door(window):
display_text(window,"Which door to choose?\n",0,3)
display_text(window,"1. Left\n",0,3)
display_text(window,"2. Right\n",0,3)
key = window.getkey()
if key == '1':
display_text(window,"This door is locked. To proceed, you'll need to find a key. You should return to the other... |
def display_text(stdscr, text,start_col,color_pair_id):
global line_counter
mrows, mcols = stdscr.getmaxyx()
stdscr.refresh()
time.sleep(0.2)
j=0
if line_counter >= mrows-5:
line_counter = 1
stdscr.clear()
time.sleep(1)
line_counter = 0
stdscr.refresh()
... | The function `attack_area` handles player input for choosing an attack type ('o' or 's') during combat, triggering different combat sequences. It displays options, processes key presses, initiates fight mechanics, and manages character actions like attacks and tool drops, using global state tracking via `line_counter` ... | def attack_area (stdscr,key,hero_weapon,hero_health:int ,enemy_name: str, enemy_weapon):
global line_counter
line_counter += 2
display_text(stdscr,"Choose your target wisely. Where will you aim your strike?\n",1,1)
display_text(stdscr,"Please press\n",3,4)
display_text(stdscr,"o: for over the head\n... |
def type(stdscr,message,i):
for char in message:
stdscr.addstr(char,curses.color_pair(i))
stdscr.refresh()
time.sleep(0.05)
def torch(stdscr):
type(stdscr,"You need to save the light's fuel.\n Quick use it to look for something else to light the way \n",3)
type(stdscr,"while... | The main task of the code is to guide the player through the first step of a dark temple scenario by prompting them to use or purchase a torch. It checks inventory status, handles player choices, deducts points or health based on decisions, and triggers the torch function or restarts the step if the player loses a life... | def first_step(stdscr):
global player
type(stdscr,"As you step into the temple, you'll notice it's really dark inside. Hardly anything to see around here . \n use one of your tools to help you find your way \n",3)
choice3 = stdscr.getstr().decode('utf-8')
if choice3 == "torch" :
... |
def display_text(stdscr, text,start_col,t):
global line_counter
stdscr.refresh()
time.sleep(0.2) # Wait for a second before displaying each letter
for i in range(len(text)):
stdscr.addch(line_counter, start_col + i, text[i],curses.color_pair(t) | curses.A_ITALIC)
stdscr.refresh()
... | The code's main task is to inform the player about a limited light source (a lighter) in a game scenario, urging them to conserve fuel and seek a more reliable light source like a torch. It displays narrative text through the window, emphasizing resource management and survival in darkness, then transitions to a hallwa... | def savingLightsfuel(window):
display_text(window,"As you flick the lighter, a small flame dances in the darkness, casting flickering shadows around you.\n",0,3)
display_text(window,"But remember The lighter has limited fuel. Please use it sparingly, illuminating your path only when necessary.\n",0,3)
displ... |
def display_text(stdscr, text,start_col,color_pair_id):
global line_counter
mrows, mcols = stdscr.getmaxyx()
stdscr.refresh()
time.sleep(0.2)
j=0
if line_counter >= mrows-5:
line_counter = 1
stdscr.clear()
time.sleep(1)
line_counter = 0
stdscr.refresh()
... | The code's main task is to let the player choose a weapon from their inventory to attack an enemy. It displays options, processes user input, and triggers specific combat sequences (e.g., fight_show or attack_area) based on the selected item. If invalid, it prompts retry. The function manages text display, input handli... | def fight(stdscr,key,enemy_name: str,enemy_weapon,hero_health):
global line_counter
display_text(stdscr,"Now is your chance to strike back! Seize the moment and unleash your counterattack!\n",1,4)
time.sleep(1)
display_text(stdscr,"Pick your tool:",1,1)
display_text(stdscr,f"Your options are:{invent... |
def display_text(stdscr, text,start_col,t):
global line_counter
stdscr.refresh()
time.sleep(0.2) # Wait for a second before displaying each letter
for i in range(len(text)):
stdscr.addch(line_counter, start_col + i, text[i],curses.color_pair(t) | curses.A_ITALIC)
stdscr.refresh()
... | This function presents a game scenario where the player must choose between using a lighter or another tool to navigate darkness. If the lighter is chosen, it triggers a progression to a fuel-saving mechanic. If not, the player faces consequences like inventory checks, point deductions, or game over outcomes based on t... | def light(window):
key1 = '0'
display_text(window,"The house is dark use one of your tools to help you.\n",0,3)
display_text(window,"Which tool do you want to use?\n",0,3)
display_text(window,"1. Anything else.",0,4)
display_text(window,"2. Lighter\n",0,4)
key = window.getkey()
if key == '1'... |
def display_text(stdscr, text,start_col,color_pair_id):
global line_counter
mrows, mcols = stdscr.getmaxyx()
stdscr.refresh()
time.sleep(0.2)
j=0
if line_counter >= mrows-5:
line_counter = 1
stdscr.clear()
time.sleep(1)
line_counter = 0
stdscr.refresh()
... | This function simulates a game scenario where the player enters a room, faces a powerful enemy, and chooses to either block or dodge an attack. Based on the player's input, it transitions to a fight sequence with specific parameters, handling text display, user input validation, and game state progression. | def door2_entery(stdscr,key,enemy_name: str,enemy_weapon):
global line_counter
display_text(stdscr,"As you insert the key into the lock, the mechanism clicks softly, allowing the door to swing open with a creak. Your senses are immediately assaulted by a musty odor, and as you step cautiously into the room, yo... |
def display_text(stdscr, text,start_col,t):
global line_counter
stdscr.refresh()
time.sleep(0.2) # Wait for a second before displaying each letter
for i in range(len(text)):
stdscr.addch(line_counter, start_col + i, text[i],curses.color_pair(t) | curses.A_ITALIC)
stdscr.refresh()
... | This function presents two house entry options (door/window) to the player. If choosing the door, it checks for a "mystery item" key to unlock access. If successful, the player progresses; if not, they lose points and retry. Choosing the window bypasses the key check. Invalid inputs prompt retries, maintaining the game... | def house_entery(window):
display_text(window,"How do you want to enter the house?\n",0,3)
display_text(window,"1. Through the door.\n",0,4)
display_text(window,"2. Through the windows.\n",0,4)
key = window.getkey()
if key == '1':
if search (window,"mystery item") == 1 :
display_... |
def mom_heuristic(self, variables: str, clauses: list, parameter: float):
"""
Implements MOMs heuristic.
"""
# get shortest list
shortest_clauses = self.shortest_clauses(clauses)
# get highest moms score with variable
max_score = 0
for variable in variabl... | The code implements the DPLL algorithm for solving Boolean satisfiability (SAT) problems. It recursively checks assignments for variables using heuristics (MOM/JW) or default selection, performs unit propagation to simplify clauses, eliminates pure literals, and backtracks when contradictions arise. It returns whether ... | def run(self, variables:list, clauses: list, set_variables: dict, split: bool, value: bool, heuristic: str, par=2) -> bool:
"""
Runs DPLL algorithm by systematically checking all values for literals, with backtracking.
Input: variables(list), clauses(list), set_variables(dict), split(Bool), valu... |
def set_input(self, input_data: np.array) -> None:
"""set the input layer"""
assert len(input_data) == len(self.activation[0])
self.activation[0] = np.array([[e] for e in input_data])
def feedforward(self) -> None:
"""feed forward input to output"""
# set the first layer based on... | This function performs mini-batch gradient descent by computing gradients for each sample in the minibatch, accumulating them, averaging across the batch, and updating neural network weights/biases using the specified learning rate. | def update_minibatch(self, minibatch: np.array, lr: float) -> None:
"""mini-batch gradient descent"""
weight_gradients = [np.zeros(w.shape) for w in self.weights]
bias_gradients = [np.zeros(b.shape) for b in self.bias]
for n_in, expected in minibatch:
self.set_input(n_in)
... |
def read_structure(pdb_file_path: str) -> Structure:
"""
Read and parse pdb/mm-cif nucleotide structure
"""
if pdb_file_path.endswith("pdb"):
parser = PDBParser(PERMISSIVE=1, QUIET=True)
elif pdb_file_path.endswith("cif"):
parser = MMCIFParser(QUIET=True)
pdbcode = os.path.basena... | The main task of the code is to process a molecular structure file by validating its bonds and geometry, then exporting the validated bond data, angle data, and geometric records into separate CSV files specified by the provided output paths. | def main(structure_filepath: str, bonds_out_filepath: str, angles_out_filepath: str, geometry_out_path: str):
sructure = read_structure(structure_filepath)
validation_records, geometry_records = validate_structure(sructure)
bonds_printer = BondsCsvPrinter()
print_records(bonds_printer, validation_recor... |
def _reset(self):
self.avg_times = []
self.std_devs = []
def _define_current_executing(self, platform):
self.executable = self.benchmark_name + "_" + platform
self.cwd = self.options.build_folder + 'src/' + \
self.benchmark_name + '/' + platform + '/'
self.executable_... | The main task of the code is to execute a benchmarking process across multiple platforms. It iterates through each platform, resets the environment, verifies prerequisites (executable availability and validation), runs the benchmark if valid, and generates a report. The function ensures sequential execution, skipping i... | def run(self):
""" runs the benchmark, report benchmarking result
"""
for platform in self.benchmark_platforms:
self._reset()
self._define_current_executing(platform)
if not self._is_executable_found(platform):
continue
if not sel... |
def test2(cluster):
uid = "tester2"
display_name = "'Test User 2'"
access_key = "tester2KEY"
s3_secret = "test3pass"
cmd = t.build_cmd('--uid', uid,
'--display-name', display_name,
'--access-key', access_key,
'--secret', s3_secret,
... | The main task of the code is to initialize an RGW cluster, execute multiple test functions on it, handle exceptions by stopping the cluster and returning an error, and cleanly terminate the cluster if all tests pass. It sets up a cluster with specified parameters, runs tests like test2–test5, ensures proper teardown on... | def init(parse_args):
#argv = []
#if parse_args:
# argv = sys.argv[1:]
#args = parser.parse_args(argv)
#rgw_multi = RGWMulti(int(args.num_zones))
#rgw_multi.setup(not args.no_bootstrap)
# __init__():
port = 8001
clnum = 1 # number of clusters
clid = 1 # 1-based
clust... |
def ParentValue(node):
Lchild = 0
Rchild = 0
if (node.left):
Lchild = node.left.uses
if (node.left):
Rchild = node.right.uses
if (Lchild + Rchild > 0):
node.uses = Lchild + Rchild
if (node.parent):
ParentValue(node.parent)
def CompareNodes(node):
temp = node.p... | The main task of the code is to compress input data using Huffman encoding. It builds a frequency table, constructs a binary tree, generates variable-length codes for characters, and outputs the encoded result. The function checks for valid symbols, handles NYT (Not Yet Transmitted) nodes, and ensures error detection f... | def Codificacion_Huffman(data,name):
#print (name,":",data)
N = 107
nsize = (2 * N) - 1
#inp = input()
NYTlist = []
inp = data
letters = dict()
tree = dict()
root = Node(nsize, 0, 0)
nsize -= 1
error = False
for i in inp:
if (not Letras.get(i)) and i != ' ':
... |
def predict_image(self, path, show = False):
''' Predicts an image and save the predicted image in the same directory
'''
file, ext = os.path.splitext(path)
image = cv2.imread(path)
img_predict = self._classify_frame(image)
cv2.imwrite("{}-predict{}".format(file, ext), im... | The code parses an input path to determine if it is a file or directory. It checks the file extension to decide the action: processing images with `predict_image`, videos with `predict_video`, or directories with `predict_dir`. If the path is invalid or the extension doesn't match known types, it prints an error messag... | def parse_arg(self, path):
''' Parses the input path and chooses the appropriate action.
'''
_, ext = os.path.splitext(path) # Get the file extension
if os.path.isfile(path):
if (ext.lower() in IMG_EXT):
self.predict_image(path, show = True)
elif (... |
def most_frequent_label(self,y):
most_frequent = Counter(y).most_common(1)[0][0] #since most_common is a list of tuples we look for the first element of the first tuple
return most_frequent
def Best_criteria(self, X, y, feat_idxs):
best_gain = 0
split_idx, split_threshold = None, None
... | This function recursively builds a decision tree by selecting optimal features to split data, creating leaf nodes when stopping criteria are met (e.g., max depth, single class), and recursively constructing left/right subtrees. It uses random feature selection, greedy splitting, and returns a tree node with split param... | def build_tree(self, X, y , depth = 0):
n_samples = X.shape[0]
n_features = X.shape[1]
n_labels = len(np.unique(y))
#stopping criteria
if (n_labels ==1
or depth >= self.max_depth
or n_samples < self.min_samples_split):
leaf_value = sel... |
def most_frequent_label(self,y):
most_frequent = Counter(y).most_common(1)[0][0] #since most_common is a list of tuples look for the first element of the first tuple
return most_frequent
def Best_criteria(self, X, y, feat_idxs):
best_gain = 0
split_idx, split_threshold = None, None
... | The code recursively builds a decision tree by selecting random features, splitting data based on the best criterion, and creating nodes until stopping conditions (e.g., max depth, single label, or minimum samples) are met, returning leaf nodes with frequent labels or internal nodes with split details. | def build_tree(self, X, y , depth = 0):
n_samples = X.shape[0]
n_features = X.shape[1]
n_labels = len(np.unique(y))
#stopping criteria
if (n_labels ==1
or depth >= self.max_depth
or n_samples < self.min_samples_split):
leaf_value = self.most_fr... |
def dir_output(comp_dir, rad_dir):
output = []
for x, y in zip(comp_dir, rad_dir):
c = sitk.ReadImage(x)
r = sitk.ReadImage(y)
if equal_dimensions(c, r):
output.append(csv_row(c, r, x))
return output
def calc_avg_std(data):
tiou = []
tdice = []
thaus = []
... | The function `dir_output` generates metrics from directory data (excluding files), calculates their average and standard deviation, and exports the processed metrics to a specified path. | def dir_output(self):
if self.typ == 'file':
print("This object contained file paths, not directories")
return
print("Generating metrics ...")
self.metrics = dir_output(self.comp_list, self.rad_list)
self.metrics = calc_avg_std(self.metrics)
export(self.me... |
def order_folder(self, comp_dir, rad_dir):
comp_list = []
rad_list = []
for roots, dirs, files in os.walk(comp_dir):
for file in files:
filename = comp_dir + "/" + file
comp_list.append(filename)
for roots, dirs, files in os.walk(rad_dir):
... | The method processes two image folders (computer and radio) by ordering their files, generating filenames, reading image pairs, validating them, and computing metrics for valid pairs. It appends these metrics to a list, returning a 2D list of metrics for analysis. | def process_folder(self, map):
"""
This method will process two folders of images and return a 2-dimensional list of
metrics
:return:
"""
self.map = map
comp_list, rad_list = self.order_folder(self.computerPath, self.radioPath)
for x, y in zip(comp_list, r... |
def generate_filename(self, computerPath, radioPath):
"""
:param computerPath:
:param radioPath:
:return: This method returns the longest common substring for the two files
"""
comp = os.path.split(computerPath)
radio = os.path.split(radioPath)
c = comp[1]... | The code processes image pairs by reading computer and radio images, validating their spacing, and computing performance metrics if valid. It generates filenames, checks image compatibility, and appends calculated metrics to a list. The method returns a list of performance metrics for the image pair after ensuring prop... | def process_file(self, map):
"""
Process metrics for an image pair
:return: list of performance metrics for the image pair
"""
self.map = map
self.filename.append(self.generate_filename(self.computerPath, self.radioPath))
self.computerImage = sitk.ReadImage(self.c... |
def get_markable_id_to_info(doc,
naf_path):
"""
:param doc:
:return:
"""
wfid_to_sentid = {}
for wf_el in doc.xpath('text/wf'):
sent_id = int(wf_el.get('sent'))
wfid_to_sentid[wf_el.get('id')] = sent_id
for subtoken_el in wf_el.xpath('subtoken... | The function processes NAF annotations by parsing XML, enriching predicate and frame element data with FrameNet and Lemon lexicon details, generating structured annotations per sentence. It maps NAF elements to linguistic frames, extracts metadata like luID, frame IDs, timestamps, and role offsets, then organizes resul... | def load_annotations_from_naf(your_fn,
path_to_your_fn_in_lemon,
naf_path,
doc_id,
premon):
"""
"""
parser = etree.XMLParser(remove_blank_text=True, strip_cdata=False)
doc = etree.par... |
def findPattern(self, game: Game, x, y) -> bool:
counter = 0
# Line
for i in range(0, y):
for j in range(0, x - 4):
for j in range(j, j + 5):
if game.board[i][j] == self.numberToFind:
counter += 1
if (counter... | The code determines the best move in a game by prioritizing strategies: first, it checks for patterns to find a '1' or '2' (likely game-specific markers), then evaluates semi-attack and semi-defense patterns. If none are found, it randomly selects an empty cell. The function returns coordinates based on the highest pri... | def getBestMove(self, game: Game, x, y):
self.size_tab = x - 1
self.suite = 4
self.numberToFind = '1'
if self.findPattern(game, x, y) == True:
return ((self.x, self.y))
self.numberToFind = '2'
if self.findPattern(game, x, y) == True:
return ((self... |
def _preprocess_data(self):
"""
There are three types of coefficients that the model uses:
1) absolute differences of feature values between a control case and a treatment case
2) first order raw sample moment of a feature for a control case : to approximate average difference
3)... | This code initializes a class to analyze control and treatment groups by storing customer subsets, features, and calculating statistical moments. It preprocesses data, computes moments for both groups, determines upper bounds for variables Z and Y, and prints these bounds. The main task is to set up structures for caus... | def __init__(self,
subset_control_customers: Dict,
subset_treatment_customers: Dict,
features: List[str]):
self.control = subset_control_customers
self.treatment = subset_treatment_customers
self.features = features
# Getting indices to ... |
def pi(self, ob_state : dict, softmax_dim=0):
if isinstance(ob_state, list):
x, x2= [], []
for obs in ob_state:
x_lst, x2_lst= [], []
for ob in obs:
x_, a1 = self.policy_net(1, ob)
x2_, a2 = self.policy_net(2, ob)
... | The code calculates the losses for a reinforcement learning agent, including the policy loss (pi_loss) using entropy regularization, temperature parameter losses (tau_loss) for entropy control, and Q-value losses (q_loss) via mean squared error against target Q-values. It processes actions, masks, and states to compute... | def calc_loss(self, mini_batch):
s, a, a_mask, a_mask2, r, s_prime, done_mask, log_prob, prob_am, prob_am2 = mini_batch
a_1q = torch.cat([ a_mask, a[..., :self.action_space_per]] , dim= -1)
a_2q = torch.cat([ a_mask2, a[..., self.action_space_per:]] , dim= -1)
# a_ma... |
def get_grouped_lines(_file_paths):
# each line is a json
default = [file_path for file_path in _file_paths if not is_csv_gzip(file_path)]
default_files = [(open(file_path, "r"), get_last_modified(file_path)) for file_path in default]
default_grouped_lines = [try_load_json_file(file, last_modified) for... | The main task of the code is to process and aggregate data lines from multiple files by grouping them, adding exchange and pair metadata, correcting timestamps, sorting the lines, and passing the processed data to a further processing function. It ensures timestamp consistency, handles exceptions during correction, and... | def process_exchange(_exchange, hr, _file_paths):
grouped_lines = get_grouped_lines(_file_paths)
lines = []
for group in grouped_lines:
for line in group:
line["exchange"] = _exchange
line["pair"] = PAIR
try:
(line["timestamp"], line["timestampNano... |
def init_network(self):
try:
logger.debug("Try logging in now...")
self.network = pylast.LastFMNetwork(
api_key=self.kwargs["api_key"],
api_secret=self.kwargs["api_secret"],
username=self.kwargs["user_name"],
password_hash=s... | The main task of the code is to scrobble played tracks to a network service by checking each player's playback status, updating "now playing" metadata, and caching or submitting scrobble data based on playback duration thresholds. It handles both immediate scrobbling when network-connected and temporary caching when of... | def scrobble_all_players(self):
if self.network is None:
self.init_network()
scrobble_list = []
for uri, player_obj in self.player_dict.items():
if player_obj.playback_status == "Playing" and self.network is not None:
try:
self.network.... |
def playActionCard(actionCardsOnHand: list, game: Game) -> Action:
"""
:param actionCardsOnHand:
:return:
"""
if len(actionCardsOnHand) > 1:
order = ["nominate", "invisible", "reset"]
orderList = []
for item in order:
for card in actionCardsOnHand:
... | The function `makeMove` determines which cards to discard or play based on available action cards, matching card sets, and game state. If matches exist, it prioritizes playing action cards; otherwise, it discards cards matching the top card. In absence of matches, it triggers "take" or "nope" actions depending on the g... | def makeMove(actionCardsOnHand, cardMatches, topCard, game):
# decide which cards are discarded
if cardMatches:
if actionCardsOnHand:
discardActionCard = playActionCard(actionCardsOnHand, game)
Connection.playAction(discardActionCard)
else:
discardAction = dis... |
def checkTopCardForActionCards(discardPile: list, game: Game, index: int) -> Card:
topCard = discardPile[index]
if len(discardPile) - index <= 1:
print("INITIAL TOP CARD")
match topCard.type:
case "invisible":
topCard.value = 1
case "reset":
... | The main task of the code is to implement AI logic for a card game. It retrieves the current player's cards, identifies the top discard pile card, matches player cards by color, checks for action cards, and executes a move (discard or draw) based on these evaluations to progress the game. | def main(game: Game):
""" Main AI Logic
"""
player = game.getCurrentPlayer()
# Check if user is disqualified
if not player.disqualified:
playerCards = player.getCards()
# topCard = game.getTopCard()
topCard = checkTopCardForActionCards(game.getDiscardPile(), game, 0)
... |
def __line2(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] - 20, init[1] - 50), trFac)
def __line3(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1] + 50), (init[0] + 20, init[1] + 50), trFac)
def __line4(self, init: tuple, trFac = (0, 0)):
... | The method `__drawTwo` orchestrates the drawing of multiple lines by sequentially invoking five private methods (`__line2` to `__line6`), each using the provided `init` tuple and optional `trFac` transformation factors. Its primary task is to trigger the rendering of these lines, likely for visualizing geometric patter... | def __drawTwo(self, init: tuple, trFac = (0,0)):
self.__line2(init, trFac)
self.__line3(init, trFac)
self.__line4(init, trFac)
self.__line5(init, trFac)
self.__line6(init, trFac) |
def __line1(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] - 20, init[1] + 50), trFac)
def __line2(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] - 20, init[1] - 50), trFac)
def __line3(self, init: tuple, trFac = (0, 0)):
self... | The main task of the code is to draw a "zero" shape by invoking six line-drawing methods (__line1 to __line7) with an initial position tuple `init` and a translation factor `trFac`. These methods collectively construct the geometric structure of a zero, likely through connected line segments, using the provided paramet... | def __drawZero(self, init: tuple, trFac = (0,0)):
self.__line1(init, trFac)
self.__line2(init, trFac)
self.__line3(init, trFac)
self.__line5(init, trFac)
self.__line6(init, trFac)
self.__line7(init, trFac) |
def __line3(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1] + 50), (init[0] + 20, init[1] + 50), trFac)
def __line4(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] + 20, init[1]), trFac)
def __line5(self, init: tuple, trFac = (0, 0)):
self... | The main task of the code is to draw multiple lines (3–7) using the provided initial position (`init`) and transformation factors (`trFac`), likely to create a structured pattern or shape by calling private methods `__line3` to `__line7` with consistent parameters. | def __drawThree(self, init: tuple, trFac = (0,0)):
self.__line3(init, trFac)
self.__line4(init, trFac)
self.__line5(init, trFac)
self.__line6(init, trFac)
self.__line7(init, trFac) |
def __line1(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] - 20, init[1] + 50), trFac)
def __line4(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] + 20, init[1]), trFac)
def __line6(self, init: tuple, trFac = (0, 0)):
self.MPLi... | The main task of the code is to draw four lines using the private methods `__line1`, `__line4`, `__line6`, and `__line7`, each called with the same `init` coordinates and optional `trFac` transformation factors. The method aggregates these line-drawing operations to generate a composite graphical output, likely for ren... | def __drawFour(self, init: tuple, trFac = (0,0)):
self.__line1(init, trFac)
self.__line4(init, trFac)
self.__line6(init, trFac)
self.__line7(init, trFac) |
def __line1(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] - 20, init[1] + 50), trFac)
def __line3(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1] + 50), (init[0] + 20, init[1] + 50), trFac)
def __line4(self, init: tuple, trFac = (0, 0)):
... | The main task of the code is to draw a shape or pattern by sequentially invoking five private line-drawing methods (`__line1`, `__line3`, `__line4`, `__line5`, `__line7`) with given initial coordinates (`init`) and transformation factors (`trFac`). These methods likely contribute to rendering a specific geometric desig... | def __drawFive(self, init: tuple, trFac = (0,0)):
self.__line1(init, trFac)
self.__line3(init, trFac)
self.__line4(init, trFac)
self.__line5(init, trFac)
self.__line7(init, trFac) |
def __line1(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] - 20, init[1] + 50), trFac)
def __line2(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] - 20, init[1] - 50), trFac)
def __line3(self, init: tuple, trFac = (0, 0)):
self... | The main task of the code is to draw the digit '6' by invoking six line-drawing methods (__line1 to __line5 and __line7) with specified initialization coordinates and transformation factors, likely rendering a stylized numeric representation of '6' through connected line segments. | def __drawSix(self, init: tuple, trFac = (0,0)):
self.__line1(init, trFac)
self.__line2(init, trFac)
self.__line3(init, trFac)
self.__line4(init, trFac)
self.__line5(init, trFac)
self.__line7(init, trFac) |
def __line3(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1] + 50), (init[0] + 20, init[1] + 50), trFac)
def __line6(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] + 20, init[1]), (init[0] + 20, init[1] + 50), trFac)
def __line7(self, init: tuple, trFac = (0, 0)):
... | The main task of the code is to draw three lines using the private methods __line3, __line6, and __line7, passing the parameters init and trFac to each. This method likely contributes to rendering a specific shape or pattern, possibly part of a larger drawing system, by combining these line segments with transformation... | def __drawSeven(self, init: tuple, trFac = (0,0)):
self.__line3(init, trFac)
self.__line6(init, trFac)
self.__line7(init, trFac) |
def __line1(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] - 20, init[1] + 50), trFac)
def __line2(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] - 20, init[1] - 50), trFac)
def __line3(self, init: tuple, trFac = (0, 0)):
self... | The main task of the code is to draw the digit '8' by sequentially calling seven line-drawing methods (__line1 to __line7) with initial coordinates `init` and transformation factors `trFac`, likely forming the shape of the number 8 through connected line segments. | def __drawEight(self, init: tuple, trFac = (0,0)):
self.__line1(init, trFac)
self.__line2(init, trFac)
self.__line3(init, trFac)
self.__line4(init, trFac)
self.__line5(init, trFac)
self.__line6(init, trFac)
self.__line7(init, trFac) |
def __line1(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1]), (init[0] - 20, init[1] + 50), trFac)
def __line3(self, init: tuple, trFac = (0, 0)):
self.MPLine((init[0] - 20, init[1] + 50), (init[0] + 20, init[1] + 50), trFac)
def __line4(self, init: tuple, trFac = (0, 0)):
... | The main task of the code is to draw the digit "9" by invoking seven distinct line-drawing methods (__line1 to __line7), each responsible for rendering a specific segment of the numeral. The `init` parameter defines the starting coordinates, while `trFac` adjusts the transformation or positioning of the lines. This met... | def __drawNine(self, init: tuple, trFac = (0,0)):
self.__line1(init, trFac)
self.__line3(init, trFac)
self.__line4(init, trFac)
self.__line5(init, trFac)
self.__line6(init, trFac)
self.__line7(init, trFac) |
def run_command_output(cmd_args, env=None, fail_ok=False):
if env:
env = {**os.environ, 'PWD': os.getcwd(), **env}
result = subprocess.run(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env)
if result.returncode != 0 and not fail_ok:
print_error(f'Process failed: {" ".join(... | This code parses the output of the 'dpkg -l' command to extract installed package names and versions, storing them in a dictionary. It identifies separator lines in the output to determine field boundaries, then iterates through lines starting with 'i' (installed packages) to map package names to their versions. The re... | def get_system_build_environment():
success, output = run_command_output(['dpkg', '-l'])
if not success or not output:
print(output)
print_fatal('Could not get list of installed packages from dpkg!')
build_env = {}
separator_points = None
for line in output.split('\n'):
if... |
def run_command_output(cmd_args, env=None, fail_ok=False):
if env:
env = {**os.environ, 'PWD': os.getcwd(), **env}
result = subprocess.run(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env)
if result.returncode != 0 and not fail_ok:
print_error(f'Process failed: {" ".join(... | The main task of the code is to parse the output of the `pip3 list` command to extract installed Python package names and their versions, returning them as a dictionary. It handles potential errors during execution, identifies separator lines to determine parsing positions, and constructs the dictionary by splitting ea... | def get_python_build_environment():
success, output = run_command_output(['pip3', 'list'])
if not success or not output:
print(output)
print_fatal('Could not get list of installed packages from pip3!')
build_env = {}
separator_points = None
for line in output.split('\n'):
... |
def clean_text(self, text):
data = self.__comment_remover(text)
data = self.__nullstr_remover(data)
return data
def __get_bb(self, text):
i = self.__iter_bb(text)
f = self.__get_func_bb(text, i)
return f
def __create_ast_tree(self, bb):
operand = operands()
... | The main task of the code is to parse a given file by splitting its content into basic blocks, generate instruction code for each block using AST analysis, and concatenate the results with an include statement to produce a new output file. | def parse(self, file, uinst):
instr_file = ["#include <Library/UefiAflProxy2.h>\n"]
i = 0
with open(file, "r") as cf:
text = cf.read()
text = self.clean_text(text)
bb = self.__get_bb(text)
for b in bb:
instr_file.append(text[i:b[0]])
i ... |
def syntax():
print("Usage:", sys.argv[0], "[options] <color(s)>")
print(
"Colors and options can be provided in any order. At least one color is required."
)
print("If multiple colors are provided, a transition option must be included")
print("")
print("OPTIONS:")
print("Transition ... | The code processes command-line arguments to control LED animations, determining actions (e.g., color, morph, strobe), settings (brightness, duration, loop), and color lists. It executes the specified animation effect using the parsed parameters and color inputs. | def main():
action = "color"
loop = False
colorlist = []
if len(sys.argv) < 2:
syntax()
for arg in sys.argv:
if arg == sys.argv[0]:
continue
if arg == "--color":
action = "color"
elif arg == "--morph":
action = "morph"
e... |
def chooseSpecificItemFromInventory(self, name):
for item in self.inventory:
if item.name == name:
return item
def addSpecificItemToTotal(self, inventoryItem):
units = self.checkUnits(inventoryItem)
self.addToTotal(inventoryItem.markdownPrice * units)
def checkSpeci... | The function adds an item to the cart by either appending a new inventory item or updating an existing one. If the item is new, it retrieves it from inventory, adds it to the cart, updates the total, and checks for specialties. If the item exists and uses 'lb' units, it prompts for additional quantity, adjusts the tota... | def addItemToCart(self, name):
if name not in self.listOfItemNamesInCart:
inventoryItem = self.chooseSpecificItemFromInventory(name)
self.listOfItemNamesInCart.append(inventoryItem.name)
self.cart.append(inventoryItem)
self.addSpecificItemToTotal(inventoryItem)
... |
def printInventoryandPrices(self):
for item in self.inventory:
name = item.name
markdownPrice = item.markdownPrice
units = item.units
specialtyToString = self.specialtyToString(item)
print('{0}: ${1:.2f}/{2} {3}'.format(name, markdownPrice, units, spe... | This code implements a simple Point of Sale (POS) system allowing users to view inventory, add/remove items from a cart, and track their total. It loops until the user quits, handling commands for inventory display ('I'), adding items ('A'), removing items ('R'), and exiting ('Q'). The cart updates dynamically, and the... | def runPOS(self):
command = True
while command:
print('Your total is: ${0:.2f}'.format(self.total))
command = input('Enter I to see inventory and prices.\nEnter A to add an item to cart.\nEnter R to remove an item from cart.\nEnter Q to quit.')
if command.lower() == '... |
def daily_charts(request):
users_list = User.objects.filter(is_superuser=False)
data, en, ne = get_daily_data()
# print("ne and en = ", en, ne)
tot_ans_cnt = get_total_event_cnt()
# print("tot_ans_cnt_wr =============== ", tot_ans_cnt[0])
busy_count = get_busy_period_count()
busy_count_l... | The code generates downloadable PDF and Excel reports (Daily/Monthly) based on the request path, using data from `daily_charts()` and `monthly_charts()`. It returns PDFs for `/export_pdf/` paths and Excel files for `/export_excel/Monthly/` with structured data, headers, and multiple tables. The `Daily` Excel export is ... | def report(request, report_name):
# print('==============================', request.path)
if request.path == '/export_pdf/Daily/':
context = daily_charts(request)
pdf = render_to_pdf('home/daily_export.html', context)
if pdf:
return HttpResponse(pdf, content_type='applicatio... |
def _upload_docs_to_couchdb(self, docs):
"""
Upload a large number of documents to couchdb
This takes a list of documents to be uploaded, and returns the status of
them (which needs to be checked by the caller of this function. If there
is a non-success status given back by couc... | The function updates an existing record in CouchDB by uploading new AVPs, handling upload errors, uploading a new revision document, and updating the record's reference with the new revision's details. | def update_existing_record(self, new_revision, new_avps):
"""
Update a record with new data. This assumes that the revision has
already been set up with new ids
"""
failures = []
logging.debug(new_avps)
for result in self._upload_docs_to_couchdb(new_avps):
... |
def get_latest(self):
""" method to query table and get the latest fraud data"""
try:
response = self.api_table.query(
KeyConditionExpression=Key("id").eq("weather") & Key("sk").begins_with(today),
ScanIndexForward=False,
Limit=1
)
... | The main task of the code is to determine the type of the input item and delegate data retrieval to the corresponding method (e.g., get_latest(), get_24h_devt(), etc.). It acts as a dispatcher, returning results from the appropriate method based on the item's type or returning None if no match is found. | def get_data(self, item):
""" check type and call appropriate get method"""
if item.type == "latest":
return self.get_latest()
elif item.type == "24h_devt":
return self.get_24h_devt()
elif item.type == "24h_average":
return self.get_24h_average()
... |
def estimate_planes(self, pcd_splits, label):
"""
:param pcd_splits: [[(N0,5), (N1,5), ...], : first rows of sections
[(Ni,5), (Ni+1,5), ...], : second rows of sections
]
:return: (rows, cols, 4) [nx, ny, nz, h], nx*x + ny*y + nz*z + h =... | The code processes point cloud data to estimate and refine plane parameters. It first estimates planes from the input point cloud and label, then normalizes the planes, fills gaps in missing planes, applies spatial and temporal averaging to smooth inconsistencies, and returns the refined planes along with the processed... | def fit_section_planes(self, pcd, label):
"""
:param pcd: [[(N0,5), (N1,5), ...], : first rows of sections
[(Ni,5), (Ni+1,5), ...], : second rows of sections
]
:return:
"""
planes, label_out_pcd = self.estimate_planes(pcd, label) ... |
def is_specification_imported(spec_name):
"""
TODO: Check if the specification has been imported already we should
perform 2 checks:
1. If the spec_name in Specification?
2. If a table with spec_name has been created
"""
kwargs = {
'specification_name': spec_name,
}
row = db.... | (The function `import_specification_by_name` checks if a specification with the given name has already been imported. If not, it locates the corresponding CSV file in the spec folder, reads its contents, and dynamically creates a table using the data. The function raises an exception if the specification is already imp... | def import_specification_by_name(spec_name):
"""
Given a specificaiton name, attempt to locate the csv file in spec folder
and create a table dynamically
"""
if is_specification_imported(spec_name):
raise Exception(
"Specification [%s] has been imported already" % spec_name)
... |
def load_table_from_specification(spec_name):
if not is_specification_imported(spec_name):
raise Exception(
"Specification [%s] has not been imported yet!", spec_name)
path = get_spec_path(spec_name)
with open(path, "r") as spec_file:
columns, column_objects_list = load_columns_... | The main task of the code is to retrieve all records from a database table specified by `spec_name`, print its column headers, and output each row's data formatted according to the column definitions. It first loads the table and column metadata, executes a SELECT query, prints headers using `get_header_output`, and it... | def select_all_from_specification(spec_name):
specification_table, column_objects_list =\
load_table_from_specification(spec_name)
specification_table.select().execute().fetchall()
for line in get_header_output(column_objects_list):
print(line)
for row in specification_table.select().exe... |
def set_training_props(self, train_x, tagset):
words, tags = set([]), set([])
max_count = 0
for s in train_x:
word_count = 0
for w in s:
words.add(w)
word_count += 1
if word_count > max_count:
max_count = word_co... | The code trains a BLSTM model using provided sentences and their POS tags. It encodes inputs, converts tags to categorical format, creates the model, trains it for specified epochs with validation, saves the model, and returns the trained instance. | def train(self, sentences, sentence_pos, tagset, num_of_epochs=30):
"""
Train the BLSTM-MODEL using provided data
:param sentences: list of sentences
:param sentence_pos: list of POS tags for the each words in provided sentences
:param tagset: list of all tags in dataset
... |
def main_menu():
WIN.fill(BLACK)
title = MAIN_FONT.render('Site-X', 1, MINT)
press_enter = PRESS_ENTER.render('Press ENTER to Start', 1, WHITE)
WIN.blit(title, (WIDTH/2 - title.get_width()/2, HEIGHT/2 - 100))
WIN.blit(press_enter, (WIDTH/2 - press_enter.get_width()/2, HEIGHT/2 + 50))
p... | The main task of the code is to run a spaceship shooter game where the player controls a white spaceship, shoots enemies with lasers, collects points upon hitting enemies, and manages explosions using sprite animations, with a game loop handling enemy spawning, movement, collision detection, and rendering the game wind... | def main():
main_menu()
animation_missile = []
animation_explosion = []
missile_ss = Spritesheet(MISSILE_IMAGE)
explosion_ss = Spritesheet(EXPLOSION_IMAGE)
animation_missile.append(missile_ss.image_at((0, 0, 127, 127), colorkey=-1))
animation_missile.append(missile_ss.image_at((128, 0, ... |
def _clone_or_pull_algorithm_repo(self, algo_name):
repo, repo_path = repo_ops.clone_or_pull_repo(
self.api_key,
self.username,
algo_name,
self.algo_api_addr,
self.artifact_path,
)
return repo, repo_path
def _create_algorithm(
s... | This function prepares an algorithm for deployment by checking if an existing algorithm matches the deployment ID. If found, it reuses the existing algorithm; otherwise, it creates a new one, sets metadata, adds secrets, updates manifests, tests, publishes, and manages resources. The goal is to ensure the algorithm is ... | def _prep_algo_for_depl(
self, user_algos, dralgo, mlops_api_token=None, test_inputs=None
):
algo_for_depl = f"{self.algo_prefix}{dralgo.depl_id}"
matching_algo = next((x for x in user_algos if x[1] == algo_for_depl), None)
if matching_algo:
self.logger.info(f"Found an ex... |
def generaterandlist(size):
numlist = []
for y in range(0, size, 1):
numlist.append(y)
random.shuffle(numlist)
return numlist
def generatereverselist(size):
numlist = []
for y in range(size, 0, -1):
numlist.append(y)
return numlist
def generateshuffledlist(size, shuffleamt):
numlist = []
for y... | The code tests a sorting algorithm's performance on different list types (random, reversed, shuffled) across varying sizes, running multiple trials and saving average timings to a CSV file for analysis. | def test_algorithm(sortfunc, outfilename,
trials = 1, scrambleamt = 5, start = 1, end = 10, step = 1 ):
file = open(outfilename, "w")
file.write("size,random,reversed,shuffled")
for cursize in range(start, end + step, step):
file.write("\n")
#generate lists
randlist = generaterandlist(curs... |
def is_train_test_file_exists(self) -> bool:
try:
logging.info("Checking if training and test file is available")
is_train_file_exist = False
is_test_file_exist = False
train_file_path = self.data_ingestion_artifact.train_file_path
test_file_path = se... | The main task of the code is to validate data by checking the existence of train/test files, verifying the dataset schema, and detecting data drift. If successful, it creates and returns a `DataValidationArtifact` with validation status, file paths, and a success message. Exceptions during validation trigger an `insura... | def initiate_data_validation(self) -> DataValidationArtifact:
try:
self.is_train_test_file_exists()
self.validate_dataset_schema()
self.is_data_drift_found()
data_validation_artifact = DataValidationArtifact(
schema_file_path=self.data_validation_... |
def valid_inputs(func, min_x, max_x):
if (func == '') or (min_x >= max_x):
if func == '':
message = 'ERROR: Must enter function!!'
else:
message = 'ERROR: (minimum x) must be less than (maximum x)'
msg = QMessageBox()
msg.setIcon(QMessageBox.Critical)
... | The code processes a user-input mathematical function by validating inputs, generating x-values, converting the function to postfix notation, evaluating it, and plotting the graph. It handles syntax errors by displaying messages if the function is invalid. | def plot_handler(func, min_x, max_x):
plt.close()
if not valid_inputs(func, min_x, max_x):
return
min_x = int(min_x)
max_x = int(max_x)
x_list = np.linspace(min_x, max_x, num=(max_x - min_x) * 100)
while func[0] == ' ':
func = func.replace(" ", "", 1)
func = func[::-1]
... |
def create_priority_order(path, exits):
""" Create a priority order of rooms to visit. The exits have highest priority,
the rooms connected to exits have next highest priority, and so on.
"""
vertices = get_vertices_from(path,[(ex,float("inf")) for ex in exits],visited = {})
# In case some vertices ... | The code computes the maximum flow in a network using a priority-based iterative approach. It initializes flow matrices, updates residual capacities iteratively, and checks for equilibrium. The priority order determines vertex flow prioritization, while dictionaries enable efficient exit/entrance lookups. The loop cont... | def solution(path,exits,entrances,debug=False,max_iters=None):
global PRIORITY_ORDER
PRIORITY_ORDER = create_priority_order(path,exits) # Create priority order -> The order of vertices in which we prioritise putting flow to.
# Pre-compute the sources and sinks to dictionaries for quick look-ups wit... |
def create_none_array(tile_size,distance,my_pos):
tile_size = [float(t) for t in tile_size]
xneq = math.ceil((distance - my_pos[0])/tile_size[0])
xpos = math.ceil((distance + my_pos[0])/tile_size[0])
ypos = math.ceil((distance + my_pos[1])/tile_size[1])
yneq = math.ceil((distance - my_pos[1])/tile_s... | This code generates possible movement directions or paths in a grid-based game by creating a tile array centered on the player's position, then iteratively expanding outward to yield each generated tile as a potential step toward the enemy's position, constrained by the game's bounds and distance limits. | def generate_directions(bounds,my_pos,enemy_pos,distance):
ogtile = Tile(my_pos,enemy_pos,(0,0),bounds)
ogtile.change_position_to_relative(my_pos)
assert ogtile.my_pos == (0,0)
tile_arr = create_none_array(bounds, distance, my_pos)
rind,cind = insert_center_tile_inplace(tile_arr,ogtile)
next_til... |
def generate_directions(bounds,my_pos,enemy_pos,distance):
ogtile = Tile(my_pos,enemy_pos,(0,0),bounds)
ogtile.change_position_to_relative(my_pos)
assert ogtile.my_pos == (0,0)
tile_arr = create_none_array(bounds, distance, my_pos)
rind,cind = insert_center_tile_inplace(tile_arr,ogtile)
next_til... | The code calculates the number of distinct laser shooting directions from `my_pos` that hit `enemy_pos` exactly at a specified distance in a bounded 2D room. It considers reflections (mirrored rooms) to simulate straight-line paths, avoiding self-intersections or corner collisions. Hits on the enemy are counted if the ... | def solution(bounds,my_pos,enemy_pos,distance,plot=False):
"""Count the total number of directions where we can shoot a laser to hit the point at 'enemy_pos' from 'my_pos' in
a room with dimensions = bounds with the laser traveling a distance of 'distance'
Args:
bounds (tuple of 2 ints): Dimensions... |
def get_vector(self, direction: int):
# Vectors representing tile movement
return self.vectors[direction]
def build_traversals(self, vector) -> Traversals:
traversals = Traversals([], [])
for pos in range(self.size):
traversals.x.append(pos)
traversals.y.append(p... | The code handles tile movement in a grid-based game (likely 2048), merging adjacent tiles of equal value when moving in a specified direction. It updates the score, checks for a win condition (2048 tile), tracks if any movement occurred, and manages tile positions and merges. | def move(self, direction: int):
# 0: up, 1: right, 2:down, 3: left
cell = None
tile = None
vector = self.get_vector(direction)
traversals = self.build_traversals(vector)
moved = False
score = 0
won = False
# Save the current tile positions and re... |
def cell_occupied(self, cell: Cell) -> bool:
return not not self.cell_content(cell)
def cell_content(self, cell: Cell) -> Tile:
if self.within_bounds(cell):
return self.cells[cell.x][cell.y]
else:
return None
def get_vector(self, direction: int):
# Vectors represe... | (The code calculates a "smoothness" score by iterating over a 4x4 grid of cells. For each occupied cell, it compares its value (log2-transformed) with the values of the farthest cells in two directions. It accumulates penalties (absolute differences) for large value disparities, returning the total as a measure of dist... | def smoothness(self) -> float:
smoothness = 0.0
for x in range(4):
for y in range(4):
if self.cell_occupied(self.indexes[x][y]):
value = math.log2(
self.cell_content(self.indexes[x][y]).value)
for direction in ra... |
def handle_action(self, line):
logger.debug("Action: {}".format(line))
if self.hole and not self.table:
multiplier = self.hole_strategy.get_multiplier(self.hole)
max_bet = int(self.match.get('big_blind', '20')) * multiplier
self.bet(line, max_bet=max_bet)
elif... | The code processes input lines from stdin, parsing and handling commands like "Action", "Settings", or "Match" by dispatching to specific methods. It validates input structure, logs errors for invalid lines, and handles unrecognized commands. The loop continues until stdin is closed, ensuring real-time processing of in... | def run(self):
logger.debug("Starting up!")
while not sys.stdin.closed:
try:
raw_line = sys.stdin.readline()
if not raw_line:
continue
line = raw_line.split()
# logger.debug("Line: {}".format(line))
... |
def read_events():
with open("events.json", "r") as read_file:
return json.load(read_file)
def get_topic_data(event):
dict_df = get_dict_data(event)
for key in dict_df.keys():
dict_df[key] = [
list(itertools.chain.from_iterable([list(*[segment_string(word)])
... | The code performs topic analysis on event data by reading events, logging their details, and generating topic models using `get_model_out`. It processes each event's data to extract topics, with parameters like `num_topics=11` for efficiency. The task involves analyzing textual data from events to identify key themes o... | def topic_analysis():
events = read_events()
for event in events["events"]:
swanalytics_logger.info(f"[{event['start_date']} to {event['end_date']}] {event['title']}")
dict_df = get_topic_data(event)
# change num_topics to some value (11) for a fast run, else None
get_model_out(... |
def get_blocks(self, row, column):
color = self.field[row][column].color
blocks = []
checked = [[False for c in range(self.col_count)] for r in range(self.row_count)]
self.find_neighbors(row, column, blocks, color, checked)
return blocks
def remove_blocks(self, blocks_to_remove: ... | This function handles a button click event in a game, removing blocks from the grid if conditions are met, updating the score, and advancing the game level when applicable, while ensuring actions only occur during the PLAYING state. | def on_button_click(self, row: int, col: int):
if self.state != GameState.PLAYING:
return
cell = self.field[row][col]
blocks = self.get_blocks(row, col)
block_level = len(blocks)
if not cell.block or block_level == 1:
return
else:
self.... |
def pressure(pi, pf, pstep):
pX = np.arange(pi, pf, pstep)
return pX
def mu_0(Ti, Tf, tstep, elec, sigma,wX8):
'''Chemical Potential Tempreture Dependent Terms'''
mu_0 = []
rot = rotational(Ti, Tf, tstep, sigma)
vib = vibrational(Ti, Tf, tstep, elec,wX8)
trans = translational(Ti, Tf, tstep)
... | The function calculates chemical potentials (mu_X and mu_M) as functions of temperature (T) and pressure (p) by combining a reference chemical potential (mu_10) with pressure-dependent corrections (p_dep), using given parameters. It generates 2D arrays of mu_X (divided by 8) and mu_M (derived from mu_MX2 and mu_X) acro... | def mu(Ti, Tf, tstep, elec, sigma, pi, pf, pstep,wX8,mu_MX2):
'''Chemical Potential as a function of Temperature and Pressure '''
pindx = 0
pX = pressure(pi, pf, pstep)
T = np.arange(Ti, Tf, tstep)
mu_10 = np.zeros(len(T))
mu_10 = mu_0(Ti, Tf, tstep, elec, sigma,wX8)
p_dep = np.zeros((len(pX... |
def get_img_contour_thresh(img):
img = cv2.flip(img, 1)
imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
dst = cv2.calcBackProject([imgHSV], [0, 1], hist, [0, 180, 0, 256], 1)
disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))
cv2.filter2D(dst, -1, disc, dst)
blur = cv2.GaussianBlur(dst,... | This code implements a gesture-based calculator interface using camera input. It detects hand gestures for numbers and operators, performs calculations, and provides real-time visual feedback on a screen. The system handles input states (first number, operator, second number), clears the screen on 'C' gesture, evaluate... | def calculator_mode(cam):
global is_voice_on
flag = {"first": False, "operator": False, "second": False, "clear": False}
count_same_frames = 0
first, operator, second = "", "", ""
pred_text = ""
calc_text = ""
info = "Enter first number"
Thread(target=say_text, args=(info,)).start()
... |
def print_typewriter(text, delay=0.03):
for char in text:
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(delay)
def view_inventory(player):
print("\n--- Inventory ---")
for item in player.inventory:
print(item)
print("-----------------\n")
def move_player(player, di... | The function handles player interaction at a cave entrance ("D") in a game. It checks if the player has defeated all enemies to proceed, then allows navigation through the cave to locate an artifact at (8,8). The player can move, view inventory, or quit. Upon finding the artifact, the objective is marked complete. | def handle_landmark(player, objectives, cave_map):
if cave_map.map_data[player.y][player.x] == "D":
if not objectives["Defeat All Enemies"]:
print_typewriter("You are not yet eligible to enter the cave, defeat all enemies first\n")
input("Press Enter to continue...")
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.