dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def choose_random_word(list_of_words):
'''
Selects random word from the list provided.
'''
return random.choice(list_of_words).upper()
def start_game(word):
'''
this function manages the game, updates the word status
and provide required feedback for bthe user
'''
attempts = MAX_ATTE... | The main task of the code is to initialize a game by selecting a random car brand, starting the game with that word, and managing user interaction to either continue playing or exit. It displays a farewell message and terminates the program if the user chooses not to play again. | def init_game(username):
'''
Function to generate a random word and provide it
to the start game function. Also displays if user
wish to play again and exits.
'''
while True:
random_word = choose_random_word(CAR_BRAND)
start_game(random_word)
if not play_again():
... |
def show_welcome_msg():
"""
Display LOGO and initial welcome messages.
"""
welcome_page()
typewriter_effects("WELCOME TO CUT-2-CHASE")
typewriter_effects("Coded by Priyanka Dhanabal\n")
time.sleep(1)
typewriter_effects("You are on the run from a heist!")
typewriter_effects("Try not t... | The main task of the code is to orchestrate a game's initialization process by sequentially calling functions to display a welcome message, collect user input, show rules, clear the screen, and start the game with the provided name. It manages flow control, user interaction, and game setup through function calls and de... | def main():
'''
Function to call all other functions.
'''
show_welcome_msg()
user_name = take_user_name_input()
typewriter_effects(f"""GREAT!! Hi {user_name.upper().strip()},
Ready to DRIVE !!\n""")
time.sleep(1)
initial_game_rules()
time.sleep(1)
clear_screen()
init_game(use... |
def _sudo(self, *args):
"""a helper to run a subprocess with sudo, raises SudoError"""
ctx = self.ctx
def get_file_contents(f):
f.flush()
f.seek(0)
return f.read()
cmd = ["/usr/bin/sudo"] + list(args)
ctx.logger.info("Running: '%s'", ' '.joi... | The main task of the code is to create specified directories using `mkdir -p`, set permissions for the Chef data root directory to 700 via `chmod`, and install a Chef handler. This prepares system structure and permissions for Chef configuration management. | def install_files(self):
dirs = map(self.get_path, self.DIRS.values() + ['etc', 'log'])
self._sudo("mkdir", "-p", *dirs)
self._sudo("chmod", "700", self.get_chef_data_root())
self.install_chef_handler() |
def install_files(self):
dirs = map(self.get_path, self.DIRS.values() + ['etc', 'log'])
self._sudo("mkdir", "-p", *dirs)
self._sudo("chmod", "700", self.get_chef_data_root())
self.install_chef_handler()
def _prepare_for_run(self, runlist):
pass
def get_node(cls, ctx):
if ... | The code executes a chef run by installing files, preparing the environment, storing chef_attributes in a temporary JSON file, running a command with sudo, and handling errors by raising a ChefError with details if the execution fails. | def run(self, runlist, chef_attributes):
ctx = self.ctx
self.install_files()
self._prepare_for_run(runlist)
t = 'cloudify_chef_attrs_in.{0}.{1}.{2}.'.format(
self.get_node(ctx).name, self.get_instance(ctx).id, os.getpid())
self.attribute_file = tempfile.NamedTemporar... |
def _is_halt_event(event):
return type(event) is HaltEvent
def _is_direction_event(event):
return type(event) is DirectionEvent
def direction_event_to_engine_input(event: DirectionEvent):
'''
Get a position in a circle and transform into left/right engine powers.
'''
(x, y) = event.get_coordina... | The function processes an InputEvent by checking its type: it returns a halt signal if the event is a halt event, converts direction events to engine input, and raises an error for unrecognized event types. | def handle_event(event: InputEvent):
if _is_halt_event(event):
return HALT_ENGINE_EVENT
elif _is_direction_event(event):
return direction_event_to_engine_input(event)
else:
raise ValueError("Could not understand event type " +
type(event).__name__) |
def is_localnet():
return network.show_active() in LOCAL_BLOCKCHAIN_ENVS
def netconfig():
return config['networks'][network.show_active()]
def deploy_mocks():
net = network.show_active()
print(f'Active network is {net}')
if not is_localnet():
price_feed = config['networks'][net]['eth_usd_pr... | The function retrieves a contract instance based on the network environment. If not local, it fetches the contract type and address from configurations, instantiates the contract, and returns it. For local networks, it uses a mock contract type, deploying mocks if necessary, and returns the last mock instance. | def get_contract(contract_name):
if not is_localnet():
contract_type = CONTRACTS[contract_name]['type']
contract_address = netconfig()[contract_name]['address']
contract = contract_type(contract_address)
return contract
else:
contract_type = CONTRACTS[contract_name]['moc... |
def get_account(index=None, id=None):
if index:
return accounts[index]
if id:
return accounts.load(id)
if is_localnet() or is_fork():
return accounts[0]
return accounts.add(config['wallets']['from_key'])
def get_contract(contract_name):
if not is_localnet():
contr... | This function funds a specified contract address with a predefined amount of LINK tokens using an Ethereum account. It defaults to using a local account and the standard LINK token contract, transferring 1e18 units of LINK to the target contract and confirming the transaction. | def fund_with_link(
contract_address,
account=None,
link_token=None,
amount=100000000000000000
):
account = account if account else get_account()
link_token = link_token if link_token else get_contract("link_token")
tx = link_token.transfer(contract_address, amount, my())
tx.wait(1)
... |
def force(x, v_vec, gammas, U0):
output = np.zeros_like(v_vec)
output[0] = force_PMF(x, U0)
output[0] -= gammas[0,0] * v_vec[0]
output[0] -= gammas[0,1] * v_vec[1]
output[1] -= gamma21(x) * v_vec[0]
output[1] -= gammas[1,1] * v_vec[1]
return output
def sigma11(x, gammas):
return sqrt(ga... | The code implements a leapfrog integration scheme for simulating particle motion with velocity coupling and stochastic dynamics. It updates positions and velocities over nsteps, incorporating forces from a potential U0, mass-dependent time scaling, and thermal noise (via xi terms) to model temperature effects. The func... | def vel_coupl_leapfrog_integrator(nsteps, x, v_vec, masses, gammas, dt, kT, U0):
nvels = len(v_vec)
th = 0.5 * dt
tm = np.zeros_like(v_vec)
xi_factor = np.zeros_like(v_vec)
for nvel in range(nvels):
tm[nvel] = dt / masses[nvel]
xi_factor[nvel] = sqrt(2 * kT * dt) / masses[nvel] ... |
def load_variables_from_file():
'''
Configuration variables are all set in the "meeting_config.key" file.
Loads up:
- notes_folder_path,
- gpt_log_dir, and
- the api_key
- errors_log path
Returns a tuple of strings.
'''
# Variable python_file_dir is the direc... | The main task of the code is to process an audio file by transcribing it, generating structured meeting notes and bullet points using GPT, and compiling the analysis into a Word document. It handles audio splitting, text chunking, AI-driven summarization, and document formatting with sections like summaries, action ite... | def main():
### Load up user defined variables
notes_folder_path, api_key, gpt_log_dir, error_log_file = load_variables_from_file()
logging.debug("Notes Folder Path: " + notes_folder_path)
logging.debug("API Key: " + api_key)
logging.debug("GPT Log Directory: " + gpt_log_dir)
logging.debug(... |
def process_r_results(self, f_path):
"""
Process GSEA summary results from R output
:param f_path:
:return:
"""
keep_cols = ['GS', 'ES', 'NES', 'NOM p-val']
new_col_names = ['GS', 'ES', 'NES', 'pval']
df = pd.read_csv(f_path, sep='\t', header=0)
... | The code compares GSEA results between baseline and normalized datasets for each tissue. It processes AMP tissues using R-generated files and other tissues with gseapy, extracts NES/GS metrics, merges data, and saves comparative TSV/JSON files for visualization. | def process_gsea_output(self):
"""
Compare GSEA output for each tissue
:return:
"""
for t_name in self.tissues:
print(t_name)
# AMP files were processed with R
if t_name.startswith('AMP'):
baseline_report = os.path.join(self.gs... |
def create_database():
own_database = [
"mdnxi@example.com", "fgmav@example.com", "fugxn@example.com", "wjcth@example.com"
]
people_database = [
"wjcth@example.com", "cfuxa@example.com", "fugxn@example.com", "fgmav@example.com",
"wedqy@example.com", "brendonandmichelle", "wedqy@... | The code's main task is to manage a database by creating it, setting time periods (2014–2023), retrieving and cleaning messages (deleting old and redundant ones), analyzing message senders, counting sender frequencies, and identifying unidentified senders. It processes data to generate statistics and outputs results li... | def main_loop():
database = create_database()
set_periods(2014, 2023)
get_messages()
delete_old_messages()
delete_messages_in_database(database)
print_large_messages()
all_messages = get_messages()
senders = get_senders_logic(all_messages)
print(Counter(senders))
print_unidentifi... |
def get_playlist_id(self):
base_url = "https://api.spotify.com/v1/me/playlists"
headers = {
"Authorization": f"Bearer {self.new_access_token()}"
}
response = requests.get(url=base_url, headers=headers)
data = json.loads(response.text)
names = [i['name'] for i ... | The code adds a user-specified song to a Spotify playlist by retrieving the playlist ID and song URI, then sending a POST request to the Spotify API with authentication. It prompts for the playlist name, song title, constructs the API endpoint, and confirms the addition. | def add_to_playlist(self):
playlist = input("What playlist do you want to add to?\t")
playlist_id = self.get_playlist_id()[f"{playlist}"]
base_url = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks"
song_to_add = input("What song would you like to add?")
song_uri = sel... |
def prepare_batch_mlm(self, batch):
"""
Prepare the batch: from the token_ids and the lengths, compute the attention mask and the masked label for MLM.
Input:
------
batch: `Tuple`
token_ids: `torch.tensor(bs, seq_length)` - The token ids for each of the sequ... | The code implements a training loop for a student model using a teacher model for guidance. It processes batches, handles GPU acceleration, prepares input data for masked language modeling (MLM) or causal language modeling (CLM), and performs training steps with interchange masks. The loop logs progress, updates metric... | def train(self):
"""
The real training loop.
"""
if self.is_master:
logger.info("Starting training")
self.last_log = time.time()
self.student.train()
self.teacher.eval()
for _ in range(self.params.n_epoch):
if self.is_master:
... |
def getSelectedLayer(self):
points = self.viewer.layers.selection.active
#print("Type of the active Layer Proxy :" + str(type(points)))
if str(type(points)) != "<class 'napari.utils._proxies.PublicOnlyProxy'>":
return None
#print("Type of the active Layer :" + str(type(point... | This function updates UI elements based on the currently selected layer. It retrieves or updates confidence thresholds, adjusts histogram ranges, and sets slider values to reflect the active layer's data, ensuring visualizations align with the selected points' properties. | def _on_layer_changed(self, event):
anID = id(self.viewer.layers.selection.active)
if anID in self.points:
self.confidence = self.points[anID][1]
self.selectedPoints = self.points[anID][0]
self.thresholdMin = self.lowBound[anID]
self.thresholdMax = self.hi... |
def initialize_parameters(self):
for l in range(1, len(self.layers_size)):
self.parameters["W" + str(l)] = np.random.randn(self.layers_size[l], self.layers_size[l - 1]) / np.sqrt(
self.layers_size[l - 1])
self.parameters["b" + str(l)] = np.zeros((self.layers_size[l], 1)... | This function implements mini-batch stochastic gradient descent (SGD) for training a neural network. It initializes parameters, iterates over mini-batches of size 32, performs forward and backward propagation to compute gradients, updates weights and biases using the learning rate, and records training/test accuracy ev... | def mini_batch_SGD(self, X, Y, X_test, Y_test, activation, learning_rate=0.01, num_iter=200):
self.n = X.shape[0]
self.layers_size.insert(0, X.shape[1])
self.iterations = num_iter
self.initialize_parameters()
self.activation=activation
for loop in range(self.it... |
def getFilesForDataset(dataset, eos=True):
""" lists the files in a dataset directory and retrieves a list of files for analysis """
if not eos:
print('ERROR: dasgoclient is not available in SWAN, cannot get list of files for dataset')
return []
if dataset not in datasets.keys():
p... | The main task of the code is to list available datasets and their associated file metadata. It iterates through dataset keys, retrieves file lists from EOS, calculates total file sizes, and prints each dataset's name with details like file count, size (in human-readable format), or a note if no files exist. The functio... | def listDatasets():
""" prints the available keys """
print('The following datasets are available:')
for ds in datasets.keys():
fileList=getFilesForDataset(ds,eos=True)
size=0; unit='bytes'
for file in fileList: size+=os.path.getsize(file)
nfiles=len(fileList)
... |
def convertDoc(self, doc, restText="",contents=False, header=False):
htmlTitle = ""
if restText == "":
itemPath = join(self.sourcePath,doc)
with open(itemPath, encoding="utf-8") as restFile:
restText = restFile.read()
if restText != None:
htmlT... | The main task of the code is to build documentation by converting RST files from the source directory into HTML format, organizing them into a target directory, handling duplicate titles by appending counters, and generating necessary support files and an index. It processes each RST file, skips ignored files, and ensu... | def buildDocs(self):
print("building into " + str(self.targetPath) + ".")
fileList = []
newFileDict = {}
settingsPath = join(self.sourcePath,settingsFile)
if isfile(settingsPath):
print("using existing settings file: " + str(settingsPath))
noTitleCounter = 0
... |
def getStatus(self):
return self.getVm().status().current().get().get('status');
def getName(self):
return self.getVm().status().current().get().get('name');
def getVm(self):
return self.proxmox.nodes(self.getNodeName()).qemu(self.vmid) | This function sets a virtual machine's status to 'start', 'shutdown', or 'stop' based on the input. It checks the current status to avoid redundant actions, logs status changes, and executes corresponding API calls via self.getVm().status(). Methods include starting, shutting down (forceful), or stopping the VM, with e... | def setStatus(self, status, **kwargs):
if status == 'start':
if self.getStatus() == 'running':
logger.info('Already running {vmName}'.format(vmName=self.getName()))
return None
logger.info('Starting {vmName}'.format(vmName=self.getName()))
retu... |
def populate_registers(init_keyword: str) -> tuple:
"""Populate registers
init_keyword -- inital secret word that will be used to populate registers X, Y, and Z
return registers X, Y, Z as a tuple
"""
xyz = ""
for char in init_keyword:
xyz += bin(ord(char))[2:].zfill(8)
... | The code encrypts a file using a secret key by generating a keystream from the secret, encrypting each line of the input file with the keystream, converting the result to hexadecimal, and writing it to a new file with the `.secret` extension. | def encrypt_file(filename: str, secret: str) -> None:
"""Encrypt a file
filename -- filename to be encrypted
secret -- secret to initialize registers
return write the result to filename.secret
"""
r = open(filename, "r")
w = open("data/projects/a51/roster.secret", "w")
for lin... |
def pad_image(self, picture):
return np.pad(picture, ((self.radius - picture.shape[0] // 2, self.radius - picture.shape[0] // 2 + 1),
(self.radius - picture.shape[1] // 2, self.radius - picture.shape[1] // 2 + 1)))
def initial_arrays(self):
self.sinogram = np.zeros((self.... | The code processes an image by padding it, initializing necessary arrays, and computing its Radon transform, likely for tomographic imaging or feature extraction tasks. | def process(self):
self.original_image = self.pad_image(self.original_image)
self.initial_arrays()
self.radon() |
def wordListTFDict(word_list):
review_TF_dict = {}
for word in word_list:
if word in review_TF_dict:
review_TF_dict[word] += 1
else:
review_TF_dict[word] = 1
#calculating the TF for each word
for word in review_TF_dict:
review_TF_dict[word] = review_TF_dic... | The code tokenizes HTML documents by extracting text, computes term frequencies, builds an inverted index, and exports results to two files: postings_file.txt (document-term frequencies) and dictionary_records.txt (term metadata). It processes multiple HTML files, stores text in a document dictionary, generates term fr... | def tokenize(input_dir, output_dir):
file_num = 1 # current number of scanned files
#tf_weights = [] # complete dictionary of all tokens from all documents
tf_dict = []
# complete_list = []
documents = {}
inverted = {}
for file_name in glob.glob(os.path.join(input_dir, "*html")):
p... |
def getClassifier(arg):
if arg.lower() == 'forcetrain':
clf = trainRandomForestClassifier()
else:
try:
print('opening pre-trained model file.')
with open(r"vggRfcModel", "rb") as inputFile:
clf = pickle.load(inputFile)
print('Loaded Pre-trained... | (The main task of the code is to load a pre-trained classifier (RFC) using the `getClassifier` function, predict test data with `predictTestData`, save the results to a CSV file via `saveDfToCsv`, and print a success message. The VGG16 model and feature extractor are commented out, suggesting they are not actively used... | def main(arg):
# Loading VGG16 model and defining feature extractor
#arg = 'forcetrain' #sys.argv[1]
#arg = 'dummy'
clf_rfc = getClassifier(arg)
df = predictTestData(clf_rfc)
saveDfToCsv(df)
print('Program Exited succesfully.') |
def getClassifier(arg):
if arg.lower() == 'forcetrain':
clf_svm, pca = trainHogSvmClassifier()
else:
try:
print('opening pre-trained model file.')
#with open(r"SvmHogModel", "rb") as inputFile:
clf_svm = cv2.ml.SVM_load('SvmHogModel')
with open(r"S... | The main task of the code is to perform image classification using a pre-trained VGG16 model. It loads a classifier and PCA model via `getClassifier`, predicts test data features with `predictTestData`, and saves results to a CSV file. The workflow includes feature extraction, dimensionality reduction via PCA, classifi... | def main(arg):
# Loading VGG16 model and defining feature extractor
#arg = 'forcetrain' #sys.argv[1]
#arg = 'dummy'
clf, pca = getClassifier(arg)
df = predictTestData(clf, pca)
saveDfToCsv(df)
print('Program Exited succesfully.') |
def squareUnderAttack(self, r, c):
'''Detrmines if the enemy can attack the current square'''
self.whiteToMove = not self.whiteToMove # switch to opponents turn
oppMoves = self.getAllPosiibleMoves()
self.whiteToMove = not self.whiteToMove # switch back to current turn
for move... | This function generates valid castling moves for a chess game. It checks if the current square is under attack, then determines if king-side or queen-side castling is allowed based on the player's turn and castling rights. Valid moves are added to the 'moves' list by calling respective helper methods for each castling ... | def getCastleMoves(self, r, c, moves):
if self.squareUnderAttack(r,c):
return # cannot perform castling
if (self.whiteToMove and self.currentCastlingRights.wks) or (not self.whiteToMove and self.currentCastlingRights.bks):
self.getKingSideCastlingMoves(r, c, moves)
if (se... |
def getAllPosiibleMoves(self):
'''All possible moves without considering checks'''
moves =[]
for r in range(len(self.board)):
for c in range(len(self.board[r])):
turn = self.board[r][c][0]
if (turn == "w" and self.whiteToMove) or (turn == "b" and not s... | The main task of the code is to generate all valid moves for the current player, considering checks. It filters out moves that leave the king in check by simulating each move, checking for check status, and removing invalid moves. It also handles castling rights, determines checkmate/stalemate conditions, and restores ... | def getValidMoves(self):
''' All possible moves considering checks'''
tempCurrentCastlingRight = CastleRights(self.currentCastlingRights.wks,self.currentCastlingRights.bks,
self.currentCastlingRights.wqs,self.currentCastlingRights.bqs)
# get... |
def _prepare_topics(self, topics, topic_types):
if topic_types is None:
topic_types = [""] * len(topics)
assert len(topics) == len(topic_types)
for i, (topic, topic_type) in enumerate(zip(topics, topic_types)):
if topic == "/tf_static":
continue
... | This function bridges ROS1 and ROS2 topics/services by preparing parameters, launching the ROS1-ROS2 bridge with specified configurations, and handling the tf_static topic separately. It sources workspaces, sets ROS parameters, and runs the parameter_bridge node, stopping the tf_static session if needed. | def run_bridge(self,
topics=tuple(), topic_types=None,
services_2_to_1=tuple(), services_2_to_1_types=None,
services_1_to_2=tuple(), services_1_to_2_types=None):
topics_param_str = self._prepare_topics(topics, topic_types)
services_2_to_1_param_str = self._prepare_ser... |
def wishme():
hour = int(datetime.datetime.now().hour)#to exteact time
tt = time.strftime("%I:%M %p")
if hour >= 0 and hour <= 12:
speak(f"good morning "+MASTER+f" its {tt}")
elif hour >= 12 and hour <= 18:
speak(f"good afternoon "+MASTER+f" its {tt}")
else:
speak(f"good eve... | The main task of the code is to execute user commands via a voice-controlled assistant, performing actions like playing sounds, opening applications, searching the web, controlling system functions (shutdown, sleep), managing media, and handling tasks such as telling jokes or fetching news. It processes voice inputs to... | def TaskExecution(self):
# os.startfile("C:\\Users\\Rohan J Billava\\Downloads\\power up.mp3")
playsound.playsound("C:\\Users\\Rohan J Billava\\Downloads\\power up.mp3")
playsound.playsound("C:\\Users\\Rohan J Billava\\Downloads\\Jarvis.mp3")
wishme()
while True:
... |
def get_hw_class(c):
p = subprocess.Popen(
["lshw", "-json", "-numeric", "-notime", "-class", c],
stdout=subprocess.PIPE,
)
return json.loads(get_output(p).read())
def get_input_devices_with_description():
# Get only devices with description. This helps to categorize them to mouses, key... | This code scans hardware components by retrieving GPU, network, and input device information, filters PCI devices for GPUs (excluding those without bus info), and compiles the data into a structured dictionary for hardware inventory or system diagnostics. | def scan_hardware():
gpus = get_hw_class("display")
network_devices = get_hw_class("network")
inputs = get_input_devices_with_description()
return {
"name": "",
"network": {"pciDevices": filter_pcis(network_devices, lambda _: True)},
# XXX: What if there's no drivers available f... |
def get_w_metric(self):
# NOTE: in lora pruning, the importance metric will be: lora_B @ grad(lora_A) + grad(lora_B) @ lora_A - grad(lora_B) @ grad(lora_A)
if self.metric_type == 'Weight':
self.W_metric = torch.abs(self.weight)
elif self.metric_type == 'Wanda':
self.W_met... | This function initializes a sparsity learning mechanism for model weights, configuring block-wise or global sparsity schedules, probability maps for sparsity levels, and optional LoRA (Low-Rank Adaptation) parameters. It sets up dynamic pruning by generating candidate sparsity values, initializing mask parameters, and ... | def init_learn_sparsity(self, sparsity_step=0.01, prune_n=0, prune_m=0, blocksize=-1, sigmoid_smooth=False, lora_rank=-1, lora_alpha=1):
self.prune_n, self.prune_m = prune_n, prune_m
self.get_w_metric()
torch.cuda.empty_cache()
if hasattr(self, 'sparsity'):
self.block_wise =... |
def load_user_database():
"""
Loads users list from file ## FILE SUPPORT TO BE ADDED LATER
Recieves: -
Returns: user dictionary
"""
data = {}
with open('users.json', 'r', encoding='utf-8') as file:
user_data = json.load(file)
data.update(user_data)
return data
def load_questions():
"""
Loads questions ba... | The main task of the code is to implement a trivia server that loads user and question databases, sets up a socket server, and manages client connections. It handles client messages (e.g., logging out or processing commands), monitors incoming connections using `select.select`, and gracefully closes connections on erro... | def main():
global users
global questions
users = load_user_database()
questions = load_questions()
print("WELCOME TO TRIVIA SERVER!")
server_socket = setup_socket()
client_sockets = []
while True:
ready_to_read, ready_to_write, in_error = select.select([server_socket] + client_sockets, [], [])
for curren... |
def connect():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((SERVER_IP, SERVER_PORT))
return sock
def login(conn):
while True:
username = input("Please enter username: \n")
password = input("Please enter password: \n")
build_and_send_message(conn, chatli... | This code implements a trivia game with login/register functionality. It connects to a server, allows users to view scores, play questions, check logged-in users, and logout. The main loop handles user choices for login, registration, or exiting, with specific actions triggered by menu options, all while maintaining a ... | def main():
print("Hi welcome to TRIVIA game !")
first_input = input("1. Login\n2. Register\n3. Exit\nYour Answer:")
while first_input == "1" or first_input == "2":
sock = connect()
if first_input == "1":
login_check = login(sock)
if login_check == 1:
... |
def make_expresso():
global machine_water, coffee_beans, machine_money, machine_cups
if check_expresso():
machine_water = machine_water - 250
coffee_beans = coffee_beans - 16
machine_money = machine_money + 4
machine_cups = machine_cups - 1
print_machine_state()
else:... | The function `handle_buy()` processes user input to determine which coffee type (espresso, latte, cappuccino) to prepare by calling the corresponding `make_` function, based on the selected option (1, 2, or 3). | def handle_buy():
buy_options = int(input())
if buy_options == 1:
make_expresso()
if buy_options == 2:
make_latte()
if buy_options == 3:
make_cappuccino() |
def handle_buy():
buy_options = int(input())
if buy_options == 1:
make_expresso()
if buy_options == 2:
make_latte()
if buy_options == 3:
make_cappuccino()
def handle_fill():
global machine_water, machine_milk, coffee_beans, machine_cups
user_fill_water = int(input("Write ... | The code handles user input by checking if the input is 'buy', 'fill', or 'take', then calls corresponding functions. If invalid, it prints an error. It acts as a dispatcher for commands in a program, likely for a coffee machine simulation, routing actions like purchasing, refilling, or taking money. | def handle_options():
options = input()
if options == "buy":
handle_buy()
elif options == "fill":
handle_fill()
elif options == "take":
handle_take()
else:
print("Option not found") |
def interruptible_accept(socket):
wait_interruptible(socket, 5)
return socket.accept()
def parse_http_headers(sockf):
# Read the first line from the HTTP message
# This will either be the Request Line (request) or the Status Line (response)
headline = interruptible_readline(sockf).decode().strip()
... | This code implements a proxy server that listens on a specified port, caches HTTP responses, and serves them to clients. It deletes existing cache, accepts client connections, parses requests, checks cache for the requested file, and either retrieves it from the cache or fetches it from the origin server, caches it, an... | def proxyServer(port):
if os.path.isdir(cacheDir):
shutil.rmtree(cacheDir)
# Create a server socket, bind it to a port and start listening
tcpSerSock = socket(AF_INET, SOCK_STREAM)
# Fill in start.
### Bind socket to specified port and listen for incoming TCP packets
tcpSerSock.bind((''... |
def printSudoku(self, data):
print("\n")
for i in range(len(data)):
line = ""
if i % self.m == 0:
print("------------------------")
for j in range(len(data[i])):
if j % self.m == 0:
line += "| "
line... | This code implements a simulated annealing algorithm to solve a Sudoku puzzle by iteratively improving a randomly generated solution. It tracks error counts, adjusts temperature for exploration, and terminates when a valid solution (zero errors) is found. The process visualizes progress via a plot and prints the initia... | def solve(self, printR = True):
result = []
solutionFound = 0
decreaseFactor = 0.99
stuckCount = 0
fixedSudoku = np.copy(self.data)
if printR == True:
self.printSudoku(self.data)
# Fixed Value and Assign Random Value to Sudoku
fixedSud... |
def __getDubsDict(self):
dub_arr = []
for i in range(self.dimension):
dub_arr += self.__markDubs(i)
dub_list = sum(dub_arr, [])
create_dict = lambda value: dict((v, 'u') for v in value)
return [create_dict(sorted(Counter(dub_list))), dub_list]
def __initSolver(sel... | The code implements a simulated annealing algorithm to solve a puzzle by iteratively adjusting a grid configuration. It initializes duplicate pairs/lists, calculates an initial score, and iteratively applies changes to reduce the score while checking for a valid solution. Temperature decreases over time, with adjustmen... | def solve(self):
start_time = time.time()
stuck_count = 0
decrease_factor = .99
tmp = self.__getDubsDict()
self.dup_pairs = tmp[1]
self.dup_lists = tmp[0]
temperature = len(self.dup_lists) * 100
# self.temp_arr = np.copy(self.array_grid)
# hold... |
def collide(self):
return self.robot.pos.equals(self.obstacle.pos)
def show(self):
if not self.showExecution: return None
os.system('cls' if SO =='Windows' else 'clear')
print(">>> PASSO: ", self.stepCount+1, " EPISODIO: ", self.episode+1, " (" + self.robot.action + ")",sep="")
if not self.info == "": pri... | The code defines a `step` method that executes an action by moving a robot, checks for collisions, updates the environment (showing visuals and moving obstacles if no collision), retrieves the current state, calculates a reward, and determines if the task is completed, returning these values for reinforcement learning ... | def step(self, action):
r = self.robot.move(action, self)
if self.showExecution and not self.collide():
self.show()
time.sleep(0.2)
if not self.collide():
self.obstacle.move3()
st = self.get_state()
rw = self.get_reward(st)
done = self.done()
return st, rw, done |
def reduce_graph(graph, relevant_valves):
reduced_graph = {}
for start in relevant_valves:
reduced_graph[start] = {}
for end in relevant_valves:
if start != end:
dst = find_min_dst(start, end, graph)
reduced_graph[start][end] = dst
return reduced_g... | The code parses input data to build a graph representing valves and their connections, extracting flow rates. It filters relevant valves (non-zero flow rates or "AA") and reduces the graph. The reduced graph and flow rates are then passed to `part1` and `part2` functions, likely solving a two-part problem involving opt... | def main():
graph = {}
flow_rates = {}
for data in s.split("\n"):
valve = data[6:8]
flow_rate = int(data[data.find("=") + 1:data.find(";")])
if "to valves " in data:
tunnels = data.split("to valves ")[1].split(", ")
else:
tunnels = data.split("to valv... |
def select_only_one_target(args, targets):
one_target = None
for arg in args:
for target in targets:
if arg == target.cargo_target_triple or arg == target.dotnet_runtime_target:
one_target = target
return one_target
def write_cargo_config():
config_f = os.path.join('.cargo', 'config')
if not... | This code builds the VUF library and GUI for specified target platforms, defaulting to all supported targets (Linux x64, Windows x64, macOS x64). If 'run' is in the arguments, it builds only the host platform's version and executes the UI executable. It first filters targets based on command-line inputs, writes Cargo c... | def main(args=sys.argv):
targets_to_build = [
Target.LINUX_x64, Target.WINDOWS_x64, Target.OSX_x64,
]
# If the user passes 'run', only the host target is built
if 'run' in args:
targets_to_build = [ Target.get_host_target() ]
# For all properties of targets, if one is specified in args we only build t... |
def load_data(utterances_file_path: str, tags_file_path: str, intent_file_path: str):
utterances = None
tags = None
intents = None
with open(utterances_file_path, "r") as fd:
utterances = fd.readlines()
with open(tags_file_path, "r") as fd:
tags = fd.readlines()
with open(inte... | The code trains a transformer model for intent classification and slot tagging using a dataset of utterances and their corresponding BIO tags. It loads and preprocesses data, tokenizes text, splits into training/validation sets, trains the model, evaluates performance, and returns the trained model. | def train_model():
global DATASET_SIZE
print("Training the model...")
utterances, tags, intents = load_data(UTTERANCES_FILE, BIO_TAGS_FILE, INTENT_FILE)
DATASET_SIZE = len(utterances)
print(f"Dataset size: {DATASET_SIZE}")
utterances = list(map(preprocess_utterance, utterances))
tags = list... |
def train_model():
global DATASET_SIZE
print("Training the model...")
utterances, tags, intents = load_data(UTTERANCES_FILE, BIO_TAGS_FILE, INTENT_FILE)
DATASET_SIZE = len(utterances)
print(f"Dataset size: {DATASET_SIZE}")
utterances = list(map(preprocess_utterance, utterances))
tags = list... | The main task of the code is to handle command-line arguments. If the single argument is "--train", it trains a model; if "--eval", it evaluates the model. Otherwise, it prints help information. If no argument is provided, it also prints help. The function uses `sys.argv` to check inputs and route execution to `train_m... | def main():
if len(sys.argv) == 2:
if sys.argv[1].lower() == "--train":
train_model()
elif sys.argv[1].lower() == "--eval":
evaluate_model()
else:
print_help()
else:
print_help() |
def update_timer_label():
global remaining_time, timer_lbl
if remaining_time > 0:
timer_lbl.config(text=f"Time Left: {remaining_time} seconds")
remaining_time -= 1
timer_lbl.after(1000, update_timer_label)
else:
timer_lbl.config(text="Time's up!")
submit()
d... | The function `refresh_question()` updates the displayed question and answer choices in a quiz application, resets timer settings, and progresses to the next question. If all questions are answered, it triggers result calculation and hides buttons. | def refresh_question():
global lblQuestion, r1, r2, r3, r4, ques, remaining_time
r1.config(fg="black")
r2.config(fg="black")
r3.config(fg="black")
r4.config(fg="black")
if ques < 5:
lblQuestion.config(text=questions[indexes[ques]])
r1['text'] = answers_choice[indexes[ques]][0... |
def gen():
global indexes
while len(indexes) < 5:
x = random.randint(0, 9)
if x in indexes:
continue
else:
indexes.append(x)
def startquiz():
global lblQuestion, r1, r2, r3, r4
lblQuestion = Label(
root,
text=questions[indexes[0]],
... | The function `startIspressed()` removes initial UI elements (labels, buttons) and initiates a quiz by calling `gen()`, `startquiz()`, and `show_buttons()`, transitioning from a start screen to an interactive quiz interface. | def startIspressed():
global labelimage, labeltext, lblInstruction, lblRules, btnStart
labelimage.destroy()
labeltext.destroy()
lblInstruction.destroy()
lblRules.destroy()
btnStart.destroy()
gen()
startquiz()
show_buttons() |
def assigne(List, threat_list):
dictionary = {}
Sum = sum(threat_list)
wheel_range = [x/Sum for x in threat_list]
for i in range(len(List)):
if List[i] == 0:
#dictionary.update({'weapon #'+str((i+1)):'not assigned'})
#the 0 here means that that inctance of a specific weap... | The code calculates the fitness of a chromosome by assigning targets, iterating through threats, retrieving corresponding weapons, and summing their multiplied values. The fitness score reflects the chromosome's effectiveness in handling threats through weapon allocation. | def compute_fitness(chrom, threat_list):
fitness = 0.0
assigned_targets = assigne(chrom, threat_list)
print(assigned_targets)
for i in range(len(threat_list)):
weapon_list = get_weapons(assigned_targets, i+1)
fitness += multiply(weapon_list, i+1)
return fitness |
def _read_byte(self,cmd):
return self._bus.read_byte_data(self._address,cmd)
def _load_calibration(self):
"load calibration"
""" read the temperature calibration parameters """
self.dig_T1 =self._read_u16(BMP280_DIG_T1_LSB_REG)
self.dig_T2 =self._read_s16(BMP280_DIG_T2_LSB_REG)
self.dig_T3 =self._read_s1... | This code initializes a BMP280 sensor by setting its I2C address, verifying device identity, loading calibration data, and configuring measurement modes for temperature and pressure. It writes control and configuration registers to enable operation, or prints an error if the device ID is invalid. | def __init__(self, address=BMP280_I2C_ADDRESS):
self._address = address
self._bus = smbus.SMBus(1)
# Load calibration values.
if self._read_byte(BMP280_ID_REG) == BMP280_ID_Value:
self._load_calibration()
ctrlmeas = 0xFF #BMP280_T_MODE_1 << 5 | BMP280_P_MODE_1 << 2 | BMP280_SLEEP_MODE;
config = 0x14 ... |
def gradient_generator(self, guesses):
guess_input = []
for g in guesses:
if len(g.shape) == 4:
if self.use_act:
g = self.act(g)
guess_input.append(g)
self.shadow_model.zero_grad()
output = self.shadow_inference(self.shadow_mode... | This code performs iterative optimization to refine a guess input by minimizing a loss function against target gradients, using gradient descent. It updates the guess through backpropagation, applies constraints, tracks losses, and saves intermediate results. The loop stops early if loss becomes NaN or exceeds a thresh... | def attack_instance(self, gradient_label, gradient_generator, guess):
self.iter = 0
for k in range(self.max_iterations):
self.optimizer.zero_grad()
if gradient_generator is None:
gradient_guess = self.gradient_generator(guess)
else:
gra... |
def guesses_init(self, continuous_shapes=None, discrete_shapes=None, discrete_range=None, disable_discrete_init=False,
lr=None, max_iterations=None, known_continuous=None, prior_initialization=None, milestones=None):
if continuous_shapes is None:
continuous_shapes = self.con... | The code performs a gradient inversion attack to reconstruct input data by combining continuous and discrete guesses. It handles cases with discrete parameters (e.g., classification, RL) by identifying labels/actions via gradients, enumerates all discrete combinations via Cartesian product, and iteratively attacks each... | def attack(self, gradient_label, gradient_generator=None, bsz1=False, case=None, last_idn=None,
continuous_shapes=None, discrete_shapes=None, discrete_range=None):
self.guesses_init(continuous_shapes, discrete_shapes, discrete_range, disable_discrete_init=False)
if len(self.guesses... |
def handle_command_line():
usage = '\n%s --model_name <sfincs|dflow> (optional) ' \
'--hurricane_name <isabel|sandy|irene> (optional) '\
'--storm_time_range <"20121025,20121104"> (optional) ' \
'--file.nc <netcdf file name> ' \
'--ncvar <netcd... | The main task of the code is to process and compare water level predictions during a hurricane with NOAA observed data. It retrieves command-line parameters, prepares station metadata, processes time-series data for specified stations, and generates plots and CSV outputs. The focus is on analyzing storm surge or water ... | def main():
logging.basicConfig(level="DEBUG", filename=log_file, filemode="a")
model, hurricane_name, ncvar, out_dir, dbay_hist_nc, kwarg = handle_command_line()
start_storm_idx = kwarg["storm_sidx"]
end_storm_idx = kwarg["storm_eidx"]
start_storm = kwarg["storm_sdate"]
end_storm ... |
def get_sizes(X, Y):
return X.shape[0], Y.shape[0]
def initialize_parameters(n_x, n_y, number_of_hidden_layers, dimension_of_layer):
np.random.seed(2)
parameters = {}
# this if is here if you just want to try a simple logistic regression
if number_of_hidden_layers == 0:
parameters["W1"] = n... | This function trains a multi-layer neural network using gradient descent. It initializes parameters, performs forward and backward propagation iteratively, updates weights with the learning rate, tracks costs, and returns trained parameters and cost history. | def L_layer_model(
X,
Y,
hidden_layer_number,
layer_dims,
learning_rate=0.0075,
num_iterations=3000,
print_cost=False,
):
np.random.seed(2)
costs = []
n_x, n_y = get_sizes(X, Y)
parameters = initialize_parameters(n_x, n_y, hidden_layer_number, layer_dims)
for i in range(... |
def is_running(self):
return self.cmd.check("jls","-Nj",self.config.jname)
def stop(self):
self.umount_local()
self.remove_vnet()
self.destroy_epair()
self.jail_stop()
self.umount_devfs()
self.force_umount()
if self.config.proxy:
self.delete_pr... | The code's main task is to safely remove a jail by stopping it if running (with optional force flag), unmounting devfs, destroying epair interfaces, and removing the filesystem, ensuring resources are cleanly released without conflicts. | def remove(self,force=False):
if self.is_running():
if force:
self.stop()
else:
raise ValueError(f"Jail running: {self.config.name} ({self.config.jname})")
if self.check_devfs():
self.umount_devfs()
if self.check_epair():
... |
def is_running(self):
return self.cmd.check("jls","-Nj",self.config.jname)
def stop(self):
self.umount_local()
self.remove_vnet()
self.destroy_epair()
self.jail_stop()
self.umount_devfs()
self.force_umount()
if self.config.proxy:
self.delete_pr... | The main task of the code is to clean up a jail's resources by stopping it (if forced), unmounting devfs, destroying epair interfaces, and optionally removing the filesystem, ensuring proper resource release while adhering to safety checks and user-specified flags. | def cleanup(self,force=False,destroy_fs=False):
if self.is_running() and force:
self.stop()
else:
raise ValueError(f"Jail running: {self.config.name} ({self.config.jname})")
if self.check_devfs():
self.umount_devfs()
if self.check_epair():
... |
def generatePuzzle():
"""
Brings together the generation of the board and the creation of the puzzle (above two methods)
:return: void
"""
pygame.event.pump()
generateSolvedBoardGUI()
removeNumbersFromSolvedBoardGUI()
def solveBoardGUI(aBoard=None):
"""
Solves and visualizes the back... | This code defines the main game loop for a puzzle game, handling user inputs (mouse clicks and keyboard presses) to generate puzzles, solve boards, or return to the menu. It updates visual elements like button colors and cursor styles based on mouse position, calls drawing functions, and maintains the game state using ... | def startTheGame():
"""
Method with the main game loop
:return: void
"""
run = True
generatePuzzleColour, solveBoardColour, menuColour = DARK_BLUE
while run:
pygame.event.pump()
screen.fill(ORANGE)
pos = pygame.mouse.get_pos()
for event in pygame.event.get(): ... |
def make_mask(model):
global step
global mask
step = 0
for name, param in model.named_parameters():
if 'weight' in name:
step = step + 1
mask = [None]* step
step = 0
for name, param in model.named_parameters():
if 'weight' in name:
tensor = param.da... | This code defines a training script for a neural network with configurable hyperparameters, pruning, and neural architecture search (NAS) capabilities. It sets up training arguments, initializes a model with dropout, applies iterative pruning, and performs offline evaluation of pruned architectures. The main task invol... | def main():
# Training settings
parser = argparse.ArgumentParser(
description='Learning convolutions from scratch example')
parser.add_argument('--batch-size', type=int, default=512, metavar='N',
help='input batch size for training (default: 512)')
parser.add_argument('--... |
def set_chan_params(chan, vdiv, offset, coupling):
if inst is not None:
print(f"Setting channel {chan} parameters...", end='')
if coupling == COUPLING_DC:
inst.write(f"Channel{chan}:COUPling DC")
else:
inst.write(f"Channel{chan}:COUPling AC")
inst.write(f"Chan... | The code performs a frequency sweep measurement using a signal generator and oscilloscope. It acquires time-domain data for multiple frequencies, applies the Goertzel algorithm to extract frequency and amplitude parameters from each channel's signal, and stores results in global lists. The process involves configuring ... | def do_scan():
global c1vectors
global c2vectors
global NUM_ACQ_POINTS
c1vectors = []
c2vectors = []
NUM_ACQ_POINTS = 10000
freq = 200000
set_chan_params(1, 1.0, 0.0, COUPLING_AC) # chan, vdiv, offset, impedance
set_chan_params(2, 1.0, 0.0, COUPLING_AC)
set_wavegen_params()
... |
def DictUpdate(self, tokens):
index = 0
while index < len(tokens):
self.UploadGram(tokens, index)
index = index + 1
def GramChecker(self, tokens):
dynamic_index = []
if len(tokens) < 2:
pass
else:
index = 1
while index <... | The code parses log files to generate event templates by tokenizing lines, creating unique identifiers via MD5 hashing, and counting template occurrences. It writes event IDs and templates to "OLevent.txt" and template frequencies to "OLtemplate.csv", returning a dictionary of entropy values for analysis. | def Parse(self):
template_dict = dict()
eventFile = open("Output/OLevent.txt", "w")
templateFile = open("Output/OLtemplate.csv", "w")
eventFile.write('EventId,EventTemplate')
eventFile.write('\n')
templateFile.write('EventTemplate,Occurrences')
templateFile.write... |
def dsmaker(tset):
return list(map(lambda z: z[0:-1], tset))
def objmaker(tset):
def search(l, ls):
if ls == []:
return None
if l == ls[0][0:-1]:
return ls[0][-1]
return search(l, ls[1:])
return lambda *dat: search(list(dat), tset)
def learn(p, datlist, obj, e... | The code's main task is to perform classification by preparing dataset structures (`datlist`) and an objective function (`obj`) from the input dataset (`tset`), then invoking a learning algorithm (`learn`) with parameters `p` (model), `eta` (learning rate), and `epsilon` (precision threshold) to train or optimize the m... | def classify(p, tset, eta, epsilon=0):
datlist = dsmaker(tset)
obj = objmaker(tset)
return learn(p, datlist, obj, eta, epsilon) |
def dsmaker(tset):
return list(map(lambda z: z[0:-1], tset))
def objmaker(tset):
return lambda *dat: search(list(dat), tset)
def learn(net, datlist, obj, eta, epsilon=0, maxepochs=20000, verbose=True):
n = 1
while n < maxepochs:
if(n%50== 0):
print("EPOCH: " + str(n))
don... | The function `classify` trains a neural network model using the provided dataset (`tset`) and parameters (learning rate `eta`, convergence threshold `epsilon`, maximum epochs `maxepochs`). It prepares data and objective functions via `dsmaker` and `objmaker`, then invokes the `learn` function to iteratively optimize th... | def classify(net, tset, eta, epsilon=0.1, maxepochs= 20000, verbose=False):
datlist = dsmaker(tset)
obj = objmaker(tset)
return learn(net, datlist, obj, eta, epsilon, maxepochs, verbose) |
def is_registered(username):
if username not in registered_receivers:
return False
if username not in registered_senders:
return False
return True
def valid_username(username):
for c in username:
if ( 'a' <= c <= 'z'):
continue
elif ('A' <= c <= 'Z'):
... | This code handles client registration by validating the received message format, checking username validity, and registering the client as either a sender or receiver. If invalid, it sends an error and closes the connection. If valid, it stores the connection details and sends a confirmation. For TOSEND clients, it ini... | def handle_client_reg(conn, addr):
message = conn.recv(MAX_MESSAGE_SIZE)
task = message.decode().split()
fault = False
username = task[2]
if ( len(task)!=3 or ((task[0] != "REGISTER" or (task[1]!= "TOSEND" and task[1]!= "TORECV" )) and (not is_registered(username)))):
feedback = f"ERROR 101... |
def readMapping(path):
with open(path) as f:
mapping = json.load(f)
return mapping
def fetchApi(url, dataType, pathToArray):
data = None
if(dataType == 'json'):
response = requests.get(url)
if(response.status_code == 200):
data = response.json()
else:
... | The main task of the code is to retrieve and normalize data from multiple APIs based on a mapping configuration, data type (e.g., bikes/weather), and an optional city filter. It filters mappings by city if specified, fetches data from URLs in the mapping, and applies the corresponding normalization function (normalizeS... | def getApiData(mapping, dataType, city=None):
mappings = readMapping(mapping)
# Select the right mapping if whe have selected a city
if city:
cityFound = False
index = 0
while not cityFound and index < len(mappings):
if mappings[index]['city'] == city:
map... |
def _cue(self, lem, doc, root):
if root.pos_ in _pos_verbs:
if self._is_cue(root):
return root
for c in root.children:
if c.dep_ == "svp": # german only
lemma1 = c.text + root.lemma_
# TODO replace somehow with _is_... | This function identifies the subject, verb, and content (cite) of a sentence by analyzing linguistic dependencies. It first detects a verb using `_cue`, then extracts the object and content. If content is missing, it uses a relaxed method. Overlapping spans are merged, and the subject is determined via `_subject`, defa... | def _sentence(self, doc, lem, sent):
verb, subj, cite = self._cue(lem, doc, sent.root), None, None
if verb is not False and verb is not None:
obj = self._object(verb)
cite = self._content(verb)
if cite is None and obj is not None:
cite = self._relaxed_... |
def _contains(self, larger: Span, smaller: Span):
fixed = self._remove_leading_punctuation(smaller)
fixed = self._remove_trailing_punctuation(fixed)
return fixed.start >= larger.start and fixed.end <= larger.end
def _quote_front_indicator(self, quote: Span):
# TODO check up to 3 tokens
... | This function determines text processing actions for a query span in a document, analyzing sentence boundaries, quotation indicators, and surrounding context to generate appropriate operations for handling quoted or referenced text segments. | def _direct2(self, q: Span, certain: bool, lem: Lemmatizer, doc: Doc):
start: Span = q[1].sent
end: Span = q[-2].sent
is_single_sentence: bool = start == end
is_open_start: bool = not self._contains(q, start)
is_open_end: bool = not self._contains(q, end)
has_front_indic... |
def _sentence(self, doc, lem, sent):
verb, subj, cite = self._cue(lem, doc, sent.root), None, None
if verb is not False and verb is not None:
obj = self._object(verb)
cite = self._content(verb)
if cite is None and obj is not None:
cite = self._relaxed_... | This method processes each sentence in a document to yield sentence boundaries and extracted components. It first yields sentence start/end indices, then attempts to extract processed sentence data using `_sentence`. If valid, it yields the result; otherwise, it identifies a subject via `_subjunctive`, cleans punctuati... | def _indirect(self, doc, lem):
for sent in doc.sents:
yield sent.start, sent.end
s = self._sentence(doc, lem, sent)
if s is not None and None not in s:
yield s
else:
subject = self._subjunctive(sent, doc)
if subject:... |
def _directs(self, doc, lem):
for q, certain in self._quotes(doc):
yield q.start, q.end
match = self._direct2(q, certain, lem, doc)
if match:
yield match
def _indirect(self, doc, lem):
for sent in doc.sents:
yield sent.start, sent.end
... | The code processes a document to extract and fuse direct and indirect information into structured statements. It verifies the document is NER-tagged, then generates statements using lemmatized data. Each statement includes subject, cue, citation, and origin, with token tagging. The resulting statements are stored in th... | def __call__(self, doc: Doc):
if not doc.is_nered and not doc._.is_nered:
raise NotNeredException
di = self._directs(doc, self._lem)
indi = self._indirect(doc, self._lem)
statements = [
Statement(i, subj, cue, cite, origin)._tag_tokens()
for i, (subj,... |
def get_example_data():
"""
return an example list of instruction lines
"""
global instructions_length
instructions = ["nop +0",
"acc +1",
"jmp +4",
"acc +3",
"jmp -3",
"acc -99",
... | The code's main task is to execute a two-part process: first, retrieving example data and processing it via an event loop, then applying a self-healing mechanism to the same data. The function `test()` orchestrates these steps, with `event_loop()` handling event-driven operations and `self_heal()` likely addressing sys... | def test():
# Part 1
instructions = get_example_data()
event_loop(instructions)
# Part 2
self_heal(instructions) |
def get_data():
"""
return a list of instruction lines
"""
global instructions_length
instructions = []
with open('day8.txt', 'r') as data_file:
instructions = [line.strip() for line in data_file.readlines()]
instructions_length = len(instructions)
return instructions
def event_l... | The main task of the code is to execute two processes using retrieved data: first, processing instructions via an event loop, then applying self-correction or maintenance logic using the same instructions. The `main()` function orchestrates these steps by sequentially calling `event_loop()` and `self_heal()` with data ... | def main():
# Part 1
instructions = get_data()
event_loop(instructions)
# Part 2
self_heal(instructions) |
def set_null_list(self, lst):
if lst is None:
self.nulllist = self.nulldata.number
else:
if max(lst) > self.nulldata.number.max() or min(lst) < 1:
raise ValueError("Invalid list of nulls given")
self.nulllist = np.array(lst)
def add_structures(self, *a... | This code initializes a 3D visualization tool for magnetic field data from Magnetic Skeleton Analysis, allowing customization of plotted features (e.g., nulls, separators), coordinate systems (cartesian/spherical), fieldline tracing, and visual elements like boxes, axes, and suns. It reads input data, handles periodic ... | def __init__(self, filename, addlist, null_list=None, box=True, fieldlines=None, linecolor=(0, 0, 0), nskip=20,
nullrad=1, nfanlines=40, nring=None, coordsystem='cartesian', no_nulls=False,
sun=True, axes=False, outdir=None, periodicity='', only_nf=False):
"""
Makes a 3... |
def getCellLeftTop(app, row, col):
cellWidth, cellHeight = getCellSize(app)
cellLeft = app.boardLeft + col * cellWidth
cellTop = app.boardTop + row * cellHeight
return (cellLeft, cellTop)
def getCellSize(app):
cellWidth = app.boardWidth / app.cols
cellHeight = app.boardHeight / app.rows
retu... | This function draws a grid cell with appropriate styling, including background color, selected cell highlight, number display, and error indicators. It handles visual representation of game state, showing numbers from the board, red circles for incorrect answers, and legal move options when enabled. | def drawCell(app, row, col):
cellLeft, cellTop = getCellLeftTop(app, row, col)
cellWidth, cellHeight = getCellSize(app)
#Color Reference: https://blog.csdn.net/weixin_36670529/article/details/121744863
#selectedColor = rgb(253, 249, 238)
color = app.selectedColor if (row, col) == app.selection else None... |
def loadRandomBoard(filters=None):
boardPaths = loadBoardPaths(filters)
boardPath = random.choice(boardPaths)
board = [[] for _ in range(9)]
with open(boardPath, 'r') as file:
lines = file.read().splitlines()
for row in range(9):
for char in lines[row]:
if char.isdigit():... | The main task of the code is to initialize a Sudoku game interface by setting up the game board dimensions, loading UI images (buttons/options), configuring game state variables (selection, legal moves, game status), and preparing the Sudoku board with filters. It prepares the application for gameplay by initializing g... | def playScreen_onAppStart(app, filters=None):
##################################
#draw board
##################################
app.rows = 9
app.cols = 9
app.boardLeft = 75
app.boardTop = 75
app.boardWidth = 810
app.boardHeight = 810
app.cellBorderWidth = 0.5
# Load the PIL ... |
def drawGameOver(app):
drawRect(0, 0, 1500, 1000, fill='beige')
drawLabel('GAME OVER!', app.width/2, app.height/2, size = 200, bold=True, font='monospace')
drawLabel('Press v to restart!', 700, 700, size = 100, font='monospace')
def drawBoard(app):
for row in range(app.rows):
for col in range(ap... | The main task of the code is to redraw the game screen, handling game-over states, displaying the game board, difficulty options, control instructions, hints, and interactive elements like keypad visuals, color choices, and mode toggles. It positions labels, images, and UI components to provide player feedback, game co... | def playScreen_redrawAll(app):
if app.gameOver == True:
drawGameOver(app)
return
drawBoard(app)
drawBoardBorder(app)
drawBlockBorder(app)
drawBoardLevel(app)
drawLabel('The * on phone is undo move (or press u)!', 320, 900, size=25, bold=True, font='monospace')
#the as... |
def setVal(app, row, col, value):
prevVal = app.board[row][col]
app.board[row][col] = value
for banR, banC in getCellRegions(app, row, col):
ban(app, banR, banC, {value})
newVal = app.board[row][col]
if prevVal != newVal:
for unbanR, unbanC in getCellRegions(app, row, col):
... | This function handles mouse press events in a Sudoku game, updating selected cells with numbers 1-9, tracking mistakes, triggering game actions (undo, redo, check), and accessing difficulty levels, hints, and screens. It checks mouse coordinates to determine actions, enforces mistake limits, and updates the game state ... | def playScreen_onMousePress(app, mouseX, mouseY):
#print(mouseX, mouseY)
if app.gameOver == False:
if app.selection is not None:
row, col = app.selection
#print(app.selection)
if (960 <= mouseX <= 1035) and (687 <= mouseY <= 724):
setVal(app, row, col,... |
def getHint2(app):
for N in range(2, 6):
for region in getAllRegions(app):
result = applyRule2(app, region, N)
if result is not None:
return result
return None
def getAllRegionsWithTargets(app, targets):
regions = []
for region in getAllRegions(app):
... | The function `hint2` processes a puzzle application by identifying cells that should be banned from certain values based on a hint. It retrieves a hint, determines affected regions, collects cells in those regions (excluding the original hint cell), and applies value restrictions to those banned cells using `banValuesI... | def hint2(app):
hint = getHint2(app)
if hint is None:
return
cell, legalVals = hint
regions = getAllRegionsWithTargets(app, cell)
bannedCells = []
for region in regions:
for r, c in region:
if (r, c) not in cell:
bannedCells.append((r, c))
for r, c... |
def addIntercept(self, X):
if X.ndim == 1:
X = X.reshape((-1, 1))
intercept = np.ones((X.shape[0], 1))
return np.concatenate((intercept, X), axis = 1)
def fitBinaryClass(self, X, y):
#Initialising Weights
self.weightInitialisation(X)
# Converting y in... | This code fits a classifier model by adding an intercept term if specified, determining the number of classes in the target labels, and calling either a binary or multi-class fitting method based on the class count. | def fit(self, X, y):
if self.fit_intercept:
X = self.addIntercept(X)
self.nClasses = len(np.unique(y))
if (self.nClasses == 2):
self.fitBinaryClass(X, y)
else:
self.fitMultiClass(X, y) |
def assignsemesters(self, courseslist):
for i in range(0, 11):
i = Semester(i)
self.sems.append(i)
random.seed(2)
for course in courseslist.values():
nextsem = random.randint(0, len(self.sems) - 1)
course.semtaken = nextsem
self.sems... | The code initializes a course scheduling system by assigning courses to semesters, printing the initial schedule, checking for conflicts, solving the scheduling problem with constraints, and timing the solution process. It prints the schedule, verifies constraints, computes the schedule using a solver, and reports the ... | def __init__(self, courseslist, courseconstraints):
self.assignsemesters(courseslist)
self.schedprint()
self.checkconflicts(courseslist, courseconstraints)
t0 = time.time()
self.solve(courseslist, courseconstraints)
t1 = time.time() - t0
print("Took: ", t1)
... |
def update_title2(self, title1, title2=None):
# Update both lines of the title
self.title = title1
self.title2 = title2
def update_title(self, title):
# Update title within the imshow window.
self.title = title
self.title2 = None
def set_param(self, name, value):
... | This function tests a camera parameter by iterating through a specified range of values, updating the interface with each change, and then resetting the parameter to its default. It updates titles to reflect current settings, applies each value to the parameter, and pauses between steps to observe changes. After comple... | def cam_parameter_range_test(self, param, min, max, step, default):
self.update_title2('{} TEST'.format(param),
'{} --> {}, Default: {}'.format(min, max, default))
time.sleep(5)
for val in range(min, max, step):
print('Changing {} to: {}'.format(param, val... |
def update_title2(self, title1, title2=None):
# Update both lines of the title
self.title = title1
self.title2 = title2
def set_param(self, name, value):
# Validate input values.
params = self.get_params()
if name not in params.keys():
print('.... ERROR: Unkno... | This function tests a camera parameter by iterating through a specified range of values, updating the UI with current settings, and resetting to default after testing. It accepts parameters like min, max, step, and default, generates a value list if not provided, and applies each value to the parameter while displaying... | def cam_parameter_range_test2(self, param, title, min, max, step, default, rangelist=None):
self.update_title2(title, '{} --> {}, Default: {}'.format(min, max, default))
time.sleep(2)
if rangelist is None:
rangelist = list(range(min, max, step))
for val in rangelist:
... |
def _check_events(self):
"""Respond to keypreses and mouse events"""
self.mouse_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN: # if/elif because multiple keys can be active/inactive
self._check_keydown_events(event)
... | The code defines the `run_game` method, which manages the game loop by continuously checking for events (like keypresses), updating game elements (ship, bullets, power-ups, aliens) when the game is active, and rendering the updated screen. The loop ensures real-time interaction, object movement, collision checks, and v... | def run_game(self): # the loop. these things are done in this order, until the game is over.
"""Start the main loop for the game."""
while True:
self._check_events() # 1) checks for events (keypress)
if self.stats.game_active: # Just lets you check for ev... |
def SetRoutedFlagToFalseForAllCustomers(self):
for i in range(0, len(self.customers)):
self.customers[i].isRouted = False
def MinimumInsertions(self):
self.sol = Solution() # call Solution class
self.OpenAllRoutes()
total_duration_routes = 0
model_is_feasible = True
... | The code's main task is to solve a routing problem by first resetting customer routes, then applying the Minimum Insertions heuristic to generate an initial solution. It reports this solution and subsequently employs a Variable Neighborhood Descent (VND) algorithm to refine and optimize the solution further. The method... | def solve(self):
self.SetRoutedFlagToFalseForAllCustomers()
# Question B
print("~~~~~~~~ MINIMUM-INSERTIONS ~~~~~~~~~")
self.MinimumInsertions()
self.ReportSolution(self.sol)
# Question C
# print("~~~~~~~~LOCAL-SEARCH~~~~~~~~~")
# self.LocalSearch(1)
... |
def get_lanes(self,
center_in_world: np.ndarray,
raster_from_world: np.ndarray,
active_tl_ids: set,
raster_radius: float) -> Iterator[Dict[str, Any]]:
lane_indexes = elements_within_bounds(center_in_world,
... | The function generates a semantic map by extracting and compiling elements like lanes, crosswalks, speed bumps, and stop signs around a specified location, using input parameters to define the map's center, coordinate conversion, and active traffic light data. It returns these elements as a dictionary for further proce... | def get_semantic_nodes(self,
center_in_world: np.ndarray,
raster_from_world: np.ndarray,
tl_faces: np.ndarray) -> Dict[str, List]:
"""Renders the semantic map at given x,y coordinates.
Args:
center_in_world (np... |
def extract_feature(self, scene_info: Dict[str, Any]) -> Dict[str, torch.Tensor]:
# features
# - one-hot node type (7): [ego, agent, lane, stop_sign, speed_hump, speed_bump, crosswalk]
# - x_pos
# - y_pos
# - node type specific features
graph = scene_info["graph"... | The code constructs a graph representation of a scene by extracting features, generating masks for different elements (ego, crosswalks, speed bumps, lanes), creating KNN-based edge indices for each element and the entire scene, and packaging these into a `SceneGraphData` object along with target positions, transformati... | def to_data(self, scene_info: Dict[str, Any], k: int, flow: str = "source_to_target") -> Data:
feature = self.extract_feature(scene_info)
x = feature["x"]
ego_mask = get_mask(x, SemGraphRasterizer.EGO)
crosswalk_mask = get_mask(x, SemGraphRasterizer.CROSSWALKS)
crosswalk_batch... |
def print_all_files_in_dir(dir_path,to_print=True):
list1=[]
for file_name in os.listdir(dir_path):
if os.path.isdir(os.path.join(dir_path,file_name)):
list1 += print_all_files_in_dir(os.path.join(dir_path,file_name))
else:
if to_print:
print(file_name)
list1.append(str(file_name))... | The main task of the code is to display the current repository status by identifying staged changes, unstaged changes, and untracked files relative to the current commit. It reads the HEAD reference to determine the current commit, checks file differences in the staging area and working directory, and returns a boolean... | def status():
main_directory = os.getcwd()
images_folder=os.path.join(main_directory, '.wit\images')
wit_folder=os.path.join(main_directory, '.wit')
staging_area_folder = os.path.join(main_directory, '.wit\staging_area')
if not os.path.isdir(wit_folder):
return
#printing current commit_id
with open(os... |
def poly_power(power, f):
"""Polynomials to the power in F_2[x]
:param power: how many times we wish to multiply f by itself
:param f: polynomial in array form (powers go left to right)
"""
g = list(f)
if power == 0:
g = [0] * len(f)
g[len(g) - 1] = 1
if power > 0:
... | The function computes the ab'th Ducci iteration of a tuple `u` by raising the a'th iteration `D_a` to the power `b`, inverting the (b-1)th power of `u`, and multiplying the results. It uses polynomial exponentiation and inversion to derive the ab'th iteration from the given a'th iteration and power parameter. | def ducci_power_correction(D_a, u, b):
"""Takes a'th (unknown a) ducci iteration of u and
gives the ab'th ducci iteration of u
:param D_a: n-tuple
:param u: starting n-tuple
:param b: power
:return: D^ab(u) as n-tuple
"""
quot = [1]*len(u) # initialise quotient of group
D_ab_ub = ... |
def poly_power(power, f):
"""Polynomials to the power in F_2[x]
:param power: how many times we wish to multiply f by itself
:param f: polynomial in array form (powers go left to right)
"""
g = list(f)
if power == 0:
g = [0] * len(f)
g[len(g) - 1] = 1
if power > 0:
... | The function `replace_base_power` computes a transformed message $ D^{ab}(msg) $ using polynomial exponentiation and multiplication. It takes inputs $ D_a $ (iterated result of $ u $), $ u $ (initial tuple), $ b $ (integer exponent), and $ msg $ (message tuple). Key steps include raising $ D_a $ to the power $ b $, com... | def replace_base_power(D_a, u, b, msg):
"""Compute D^{ab}(msg) from D^a(u) and b
:param D_a: a iterations of u
:param u: starting tuple
:param b: integer
:param msg: message as tuple
:return: D^{ab}(msg)
"""
D_ab_m, quot = list(D_a), [1] * len(u)
D_ab_m = poly_power(b, D_a)
u_b ... |
def read_committed_positions(ships, command_queue):
if len(command_queue) > 0:
result = []
for command in command_queue:
_, ship_id, direction = command.split(" ")
ship = next((x for x in ships if x.id == int(ship_id)), None)
result.append(ship.position + dir_to_p... | The function `desired_move` determines the optimal movement for a ship to approach its target position while avoiding spaces already committed by other ships in the command queue. It evaluates possible directions, calculates distances, and selects the move that minimizes the distance to the target, ensuring the new pos... | def desired_move(self, ship, command_queue):
'''Determine the move which gets the given ship closest to its desired target, forbidding claimed spaces in the command_queue.'''
committed_positions = read_committed_positions(self.ships, command_queue)
on_shipyard = (self.me.shipyard.position == shi... |
def sc_log(level, message):
'''
if logging_level >= level:
logging.info(message)
Level 1: Minimum. Log map when available, halite per round, and other necessary information.
Level 2: Log major calculation steps. Used to see process flow in logs.
Level 3: Log various small things that ha... | This function recursively determines a ship's movement by checking for collisions with other ships, deferring to those in its path. It attempts up to 10 times to resolve conflicts by recursively moving blocking ships, appending movement commands to a queue. If no valid move is found, it defaults to "stay". The process ... | def move_ship_recursive(self, command_queue, ship, ignore_ships):
'''Determine ship movement, recursively deferring to a ship in its path and ignoring ships that are confirmed to move elsewhere.'''
sc_log(1, f"Move_ship_recursion start: Ship {ship.id}")
moved = False
loopcounter = 0 # I... |
def sc_log(level, message):
'''
if logging_level >= level:
logging.info(message)
Level 1: Minimum. Log map when available, halite per round, and other necessary information.
Level 2: Log major calculation steps. Used to see process flow in logs.
Level 3: Log various small things that ha... | The main task of the code is to generate and return a command queue for a game turn, which includes moving ships recursively and potentially spawning a new ship if resource conditions are met. It logs game state information, checks ship movement constraints, and ensures the shipyard produces a new ship when halite allo... | def one_game_step(self):
'''Determine and return the command_queue actions to take this turn.'''
sc_log(1, f"##FL-Round:{self.game.turn_number}:{self.game.me.halite_amount}")
command_queue = []
#TODO: Consider enemy positions when choosing to move
# If you can't grab a lis... |
def get_right_data_soket(data_socket, socket, mode):
if data_socket is not None:
data_socket.close()
if mode == "PASV":
return connect_to_pasv(socket)
else:
return connect_to_port(socket)
def test(name, socket, message, expected_code, double_cmd=False, mute = False):
global all_t... | The code performs RETR command tests on an FTP server using a socket, validating responses like 250, 150, 550, and 226 for file retrieval, directory navigation, and error handling. It checks data transfer correctness via read_data_socket after each test, ensuring proper handling of valid/invalid paths and mode-specific... | def retr_tests(socket, mode):
data_socket = None
data_socket = get_right_data_soket(data_socket, socket, mode)
if data_socket is None:
print_in_red("KO: PASV/PORT test failed, can't continue testing")
return
test("CWD ..", socket, "CWD ..", 250)
data_socket = get_right_data_soket(da... |
def get_right_data_soket(data_socket, socket, mode):
if data_socket is not None:
data_socket.close()
if mode == "PASV":
return connect_to_pasv(socket)
else:
return connect_to_port(socket)
def test(name, socket, message, expected_code, double_cmd=False, mute = False):
global all_t... | The main task of the code is to test the STOR (Store File) command in an FTP server implementation. It verifies the server's response to various STOR commands with different file paths, checks data transmission via a data socket, and ensures correct handling of valid/invalid paths, file creation, and response codes (e.... | def stor_test(socket, mode):
pwd = get_serv_pwd(socket)
data_socket = None
data_socket = get_right_data_soket(data_socket, socket, mode)
if data_socket is None:
print_in_red("KO: PASV/PORT test failed, can't continue testing")
return
test("STOR", socket, "STOR", 501)
test("S... |
def connect_client(socket):
print("Connecting new client with credentials")
test("USER Anonymous", socket, "USER Anonymous", 331, mute = True)
test("PASS", socket, "PASS", 230, mute = True)
print("")
def list_tests(socket, mode):
data_socket = None
data_socket = get_right_data_soket(data_socket,... | The code performs a series of FTP protocol tests using PASV (Passive) mode through a provided socket. It connects a client, tests directory listing (`LIST`), file retrieval (`RETR`), and file storage (`STOR`) commands in passive mode, ensuring proper functionality and compliance with FTP standards for passive data conn... | def pasv_tests(socket):
connect_client(socket)
list_tests(socket, mode="PASV")
retr_tests(socket, mode="PASV")
stor_test(socket, mode="PASV") |
def connect_client(socket):
print("Connecting new client with credentials")
test("USER Anonymous", socket, "USER Anonymous", 331, mute = True)
test("PASS", socket, "PASS", 230, mute = True)
print("")
def list_tests(socket, mode):
data_socket = None
data_socket = get_right_data_soket(data_socket,... | The code executes a series of tests on a socket connection using PORT mode. It connects a client, then runs tests for listing directory contents, retrieving files, and storing files, all in PORT mode. The main task is to verify the socket's functionality for data transfer operations in PORT mode, ensuring proper commun... | def port_tests(socket):
connect_client(socket)
list_tests(socket, mode="PORT")
retr_tests(socket, mode="PORT")
stor_test(socket, mode="PORT") |
def sanitize(s):
'''
Replaces all the weird KX syntax with python syntax
'''
replaces = {"&":" and ","|":" or ","^":"**","!":"not "}
for k in replaces:
s=s.replace(k,replaces[k])
return s
def firstInt(s):
for i in range(len(s)):
if s[i].isdigit():return i
return -1
def matchParen... | The code parses a Keymaera program to extract variables, constants, pre/postconditions, and the Hoare Triple (HP) syntax tree. It sanitizes input, removes comments, identifies program sections, processes variable definitions, builds a state with values, and separates HP logic into a syntax tree. It returns parsed state... | def parse(s):
'''
Takes in an entire Keymaera program and parses the variables, constants,
program, and pre/post conditions
returns: State * Form * Form * HP * robot list
(state, precons, postcons, HP syntax tree, list of Robot objects)
'''
#do some sanitation
if s.find("!=")>=0:
... |
def hideButtons(self):
self.buttons['auto'].pack_forget()
self.buttons['manual'].p1ack_forget()
def onClick(self,event,loop):
if not self.choosing:return
for i in range(len(self.traces)):
_,end_state = self.traces[i]
for r in self.robots:
if r.clic... | This code switches the application to manual mode by clearing the canvas, hiding buttons, updating the label to "Manual Mode", and preparing for trace selection. It checks if the current tree structure is a Loop; if so, it adjusts the tree and binds mouse clicks to handle trace selection with a flag set to True. Otherw... | def start_manual(self):
self.canvas.delete(ALL)
self.hideButtons()
self.labelText.set("Manual Mode")
self.choosing=False
if isinstance(self.tree, Loop):
# If loop, strip off top level, go to choose_trace
self.tree = self.tree.arg
self.window.... |
def _gbs(option_type, fs, x, t, r, b, v):
# _debug("Debugging Information: _gbs()")
# -----------
# Test Inputs (throwing an exception on failure)
_gbs_test_inputs(option_type, fs, x, t, r, b, v)
# -----------
# Create preliminary calculations
t__sqrt = math.sqrt(t)
d1 = (math.log(fs / ... | This function calculates the price of an American option using the Bjerksund-Stensland 2002 model, incorporating early exercise adjustments. It initializes values with the Garman-Kohlhagen (GBS) model, checks for early exercise optimality, computes parameters like beta, i1/i2 thresholds, and combines phi/psi functions ... | def _bjerksund_stensland_2002(fs, x, t, r, b, v):
# -----------
# initialize output
# using GBS greeks (TO DO: update greek calculations)
my_output = _gbs("c", fs, x, t, r, b, v)
e_value = my_output[0]
delta = my_output[1]
gamma = my_output[2]
theta = my_output[3]
vega = my_output[4... |
def _gbs_test_inputs(option_type, fs, x, t, r, b, v):
# -----------
# Test inputs are reasonable
_test_option_type(option_type)
if (x < _GBS_Limits.MIN_X) or (x > _GBS_Limits.MAX_X):
raise GBS_InputError(
"Invalid Input Strike Price (X). Acceptable range for inputs is {1} to {2}".fo... | The function calculates the price of an American option using the Bjerksund-Stensland 2002 model. It first validates inputs, then applies the model directly for call options. For put options, it transforms the put into a call via parameter adjustments (swapping strike/underlying prices, adjusting risk-free rate and cos... | def _american_option(option_type, fs, x, t, r, b, v):
# -----------
# Test Inputs (throwing an exception on failure)
# _debug("Debugging Information: _american_option()")
_gbs_test_inputs(option_type, fs, x, t, r, b, v)
# -----------
if option_type == "c":
# Call Option
_debug("... |
def play_spells(me, boss, active_spells):
for k in active_spells:
play_spell(me, boss, k)
def decrement(active_spells, me):
for k in list(active_spells):
active_spells[k] -= 1
if active_spells[k] == 0:
del active_spells[k]
if k == 'shield':
me[2] =... | The code recursively determines the minimum mana cost required to defeat a boss in a turn-based game by simulating spellcasting sequences, tracking active spells, and updating the global minimum cost when a successful defeat is achieved with lower expenditure. | def play(me, boss, active_spells, spent, played_spells):
# print(played_spells, me, boss)
global minimum
if spent >= minimum:
return False
# ME
me[0] -= 1
if me[0] <= 0:
return False
play_spells(me, boss, active_spells)
decrement(active_spells, me)
if boss[0] <= 0:
... |
def cleanPhoneNumber(phone_number):
pattern = "[^\d]+"
cleaned_phone_number = re.sub(pattern,"", phone_number)[-9:]
return cleaned_phone_number
def cleanModelNumber(string):
cleaned = string.lower()
pattern = "[-, ,/]"
cleaned = re.sub(pattern,"", cleaned)
return cleaned
def groupmatching(at... | This function compares product attributes between two product IDs (pid and pid_2) using exact and fuzzy matching logic. It calculates similarity scores for attributes like phone numbers, model numbers, and other fields, then stores top 3 matches in a dictionary with scores and matched attributes. The core task is produ... | def applyDictionaryLogic(pid, pid_2_list, prod_pid, prod_df, identifier, exactAtt, fuzzyAtt, Attributes, similar_exact, phone_fields,group,group_types, condition):
pid_2_list = np.array(pid_2_list)
Dict[pid] = []
matching_Score_Dict = {}
matching_Attributes_Dict = {}
group_att_dict = {}
for pid_... |
def _move(self, direction):
x = self.head.x
y = self.head.y
if self.food.x > self.head.x:
x += BLOCK_SIZE
elif self.food.x < self.head.x:
x -= BLOCK_SIZE
elif self.food.y > self.head.y:
y += BLOCK_SIZE
elif self.food.y < self.head.y:
... | This code handles a single step in a game loop by processing user input for direction, moving the game object (likely a snake), checking collisions, updating the game state (score, food placement), rendering the UI, and returning the game status and score. | def play_step(self):
# 1. collect user input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.direction = Di... |
def singleCall(note_model, vel_model, time_model):
folder_list = os.listdir("dataset-v4/train")
random.shuffle(folder_list)
note_data, vel_data, time_data = process(note_model, vel_model, time_model, 0, "dataset-v4/train", folder_list)
train_loop(note_model, note_data)
train_loop(vel_model, vel_dat... | The main task of the code is to generate MIDI files using pre-trained Transformer models for note, velocity, and time sequences. It loads model weights from files, skips training/testing (flags set to False), and generates 5 MIDI files by extending a predefined start sequence through the models, converting outputs to M... | def main():
train_model = False
test_model = False
generate = True
note_model = Transformer(256)
vel_model = Transformer(32)
time_model = Transformer(125)
singleCall(note_model, vel_model, time_model)
#model.load_weights("/home/dante_rousseve/model_midtrain_weights_1")
note... |
def singleCall(model):
masking_func = np.vectorize(lambda x: x != model.padding_index.numpy())
train_data, batch_max = process(model, 0, "dataset-v4/train")
inputs = train_data[:, :-1]
labels = train_data[:, 1:]
mask = masking_func(labels)
# Forward pass
with tf.GradientTape() as tape:
... | The code's main task is to generate MIDI files using a pre-trained Transformer model. It loads weights, disables training, and iteratively creates MIDI sequences by extending a starting note pattern. The model generates musical sequences, converts them to vector format, and encodes them into MIDI files (15 total). The ... | def main():
model = Transformer()
singleCall(model)
model.load_weights("/home/dante_rousseve/model_midtrain_weights_1")
# Train and Test Model
if False:
for i in range(model.num_epochs.numpy()):
loss_array = train(model)
#plex, acc = test(model)
... |
def get_video_info(url):
with ydl:
try:
result = ydl.extract_info(
url,
download=False
)
except DownloadError:
return None
if result :
video = result
if "entries" in result :
video = result["entries"][0]
... | The main task of the code is to extract audio from a video using a given URL, process the video's title by removing colons and spaces, then save the transcript with sentiment analysis enabled. It retrieves video metadata, locates the audio URL, and stores the analyzed transcript under a sanitized title. | def save_video_sentiments(url):
video_info = get_video_info(url)
url = get_audio_url(video_info)
if url:
title = video_info['title']
title = title.strip(':').replace(" ", "_").replace(':','')
save_transcript(url, title, sentiment_analysis=True) |
def find_actions(state, current_color):
""" Find all possible actions from the current state
args:
state: numpy vector represents state
current_color: color code of current player
return: all possible actions as the locations of next moves
each action is in r... | The function `my_selection` selects an action to generate a new state using either random choice or a Q-network, based on a given probability. It evaluates possible actions, updates the Q-network weights via forward propagation and error terms, and returns the chosen action and next state. If no actions are available, ... | def my_selection(state, prob):
""" Select an action to create a new state. The Q-networks is also updated in this function
args:
state: the current state
prob: the probability to choos a randomized action or not
return: a pair of action and next state
""... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.