row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
45,782
I want to do a website in sveltekit where I upload a pdf file and I can sign with my digitall sign an also validate it.
8558e2aa3e78437be6cf2423423010f0
{ "intermediate": 0.4064196050167084, "beginner": 0.23200653493404388, "expert": 0.36157384514808655 }
45,783
already i have a Cmakelist for the Test application How can i Integrate the gcov UT coverage
90acd539c7920214b9d52b3859f29978
{ "intermediate": 0.3932957947254181, "beginner": 0.16436012089252472, "expert": 0.4423440992832184 }
45,784
already i have a Cmakelist for the Test application How can i Integrate the gcov UT coverage
4528156a105b23cc8db9dd0b72e95b3a
{ "intermediate": 0.3932957947254181, "beginner": 0.16436012089252472, "expert": 0.4423440992832184 }
45,785
Check whether the below program properly includes the below requirements, ##Preprocessing Input Data: 1. Provide the GNN (GAT) model with information about all nodes and their features as input. 2. Identify and mark the nodes that need to be optimized and specify the features within those nodes that require tuning. ##Selective Tuning Logic: 1. Implement logic within the GNN (GAT) model to selectively tune the specified nodes and features while keeping the rest of the nodes and features fixed. 2. This logic can involve conditioning the optimization process on certain node or feature attributes and adjusting model parameters accordingly. ##Output Selection: 1. Design the output layer of the GNN model to produce outputs for all nodes and features but selectively extract and use only the tuned features from the selected nodes. import torch import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn import GATConv class GNN(nn.Module): def __init__(self, num_node_features, num_edge_features, num_out_features): super(GNN, self).__init__() # Define GAT layers for processing node features self.conv1 = GATConv(num_node_features, 64, heads=8) self.conv2 = GATConv(64 * 8, num_out_features, heads=1) def forward(self, node_features_tensor, edge_feature_tensor, edge_index): # Preprocess input data node_features_tensor, tuned_indices = preprocess_input(node_features_tensor) # Forward pass through GNN layers x = F.elu(self.conv1(node_features_tensor, edge_index)) x = self.conv2(x, edge_index) # Select only tuned features from the output tuned_output = x[:, tuned_indices] return tuned_output def preprocess_input(node_features_tensor): # Identify component nodes component_nodes = torch.where(node_features_tensor[:, 0] == 0)[0] # Define the indices of features to be tuned for each respective node tuning_indices = { 'M0': [18, 19], 'M1': [18, 19], 'M2': [18, 19], 'M3': [18, 19], 'M4': [18, 19], 'M5': [18, 19], 'M6': [18, 19], 'M7': [18, 19], 'C0': [20], 'I0': [21], 'V1': [22] } # Apply the tuning logic to the node features tensor for node_name, indices in tuning_indices.items(): node_index = torch.where(node_features_tensor[:, 7] == 1)[0][0] # Assuming index 7 corresponds to the node name if node_index in component_nodes: for idx in indices: node_features_tensor[node_index, idx] = 1 # Marking tuned features # Synchronous tuning for specified pairs of components synchronous_pairs = [('M0', 'M1'), ('M2', 'M3'), ('M4', 'M7')] for pair in synchronous_pairs: index1 = torch.where(node_features_tensor[:, 7] == 1)[0][0] # Assuming index 7 corresponds to the node name index2 = torch.where(node_features_tensor[:, 8] == 1)[0][0] # Assuming index 8 corresponds to the node name if index1 in component_nodes and index2 in component_nodes: for idx in tuning_indices[pair[0]]: node_features_tensor[index1, idx] = node_features_tensor[index2, idx] return node_features_tensor, tuning_indices # Initialize GNN model num_node_features = 24 # Example number of node features num_edge_features = 8 # Example number of edge features num_out_features = 16 # Example number of output features gnn_model = GNN(num_node_features, num_edge_features, num_out_features) # Forward pass through the GNN model output = gnn_model(node_features_tensor, edge_feature_tensor, edge_index)
91997b43e6c00a2ea323965dfd1c4d60
{ "intermediate": 0.33727923035621643, "beginner": 0.3058401942253113, "expert": 0.3568805754184723 }
45,786
already i have a Cmakelist for the Test application How can i Integrate the gcov UT coverage
664dd9f27733fd7f88c2a0e71c998bb5
{ "intermediate": 0.3932957947254181, "beginner": 0.16436012089252472, "expert": 0.4423440992832184 }
45,787
this code gives me the error An error occurred: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!: import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget, QFileDialog, QCheckBox, QMessageBox import argparse import random import time import torch import numpy as np from imageio import imwrite from pretrained.vgg import Vgg16Pretrained from utils.misc import load_path_for_pytorch from utils.stylize import produce_stylization class StyleTransferApp(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Style Transfer") self.content_path_label = QLabel("Content Image Path:") self.content_path_input = QLineEdit() self.content_path_button = QPushButton("Browse") self.content_path_button.clicked.connect(self.browse_content_image) self.style_path_label = QLabel("Style Image Path:") self.style_path_input = QLineEdit() self.style_path_button = QPushButton("Browse") self.style_path_button.clicked.connect(self.browse_style_image) self.output_path_label = QLabel("Output Path:") self.output_path_input = QLineEdit() self.output_path_button = QPushButton("Browse") self.output_path_button.clicked.connect(self.browse_output_path) self.high_res_checkbox = QCheckBox("High Resolution") self.content_loss_checkbox = QCheckBox("Content Loss") self.dont_colorize_checkbox = QCheckBox("Don't Colorize") self.cpu_checkbox = QCheckBox("Use CPU") # New checkbox for CPU self.alpha_label = QLabel("Alpha:") self.alpha_input = QLineEdit("0.75") self.run_button = QPushButton("Run Style Transfer") self.run_button.clicked.connect(self.run_style_transfer) layout = QVBoxLayout() layout.addWidget(self.content_path_label) layout.addWidget(self.content_path_input) layout.addWidget(self.content_path_button) layout.addWidget(self.style_path_label) layout.addWidget(self.style_path_input) layout.addWidget(self.style_path_button) layout.addWidget(self.output_path_label) layout.addWidget(self.output_path_input) layout.addWidget(self.output_path_button) layout.addWidget(self.high_res_checkbox) layout.addWidget(self.content_loss_checkbox) layout.addWidget(self.dont_colorize_checkbox) layout.addWidget(self.cpu_checkbox) # Add CPU checkbox layout.addWidget(self.alpha_label) layout.addWidget(self.alpha_input) layout.addWidget(self.run_button) central_widget = QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) def browse_content_image(self): file_path, _ = QFileDialog.getOpenFileName(self, "Select Content Image") if file_path: self.content_path_input.setText(file_path) def browse_style_image(self): file_path, _ = QFileDialog.getOpenFileName(self, "Select Style Image") if file_path: self.style_path_input.setText(file_path) def browse_output_path(self): file_path, _ = QFileDialog.getSaveFileName(self, "Save Output As") if file_path: self.output_path_input.setText(file_path) def run_style_transfer(self): content_path = self.content_path_input.text() style_path = self.style_path_input.text() output_path = self.output_path_input.text() high_res = self.high_res_checkbox.isChecked() content_loss = self.content_loss_checkbox.isChecked() dont_colorize = self.dont_colorize_checkbox.isChecked() use_cpu = self.cpu_checkbox.isChecked() # Retrieve CPU checkbox value alpha = float(self.alpha_input.text()) # Core Logic from your provided code random.seed(0) np.random.seed(0) torch.manual_seed(0) max_scls = 4 sz = 512 if high_res: max_scls = 5 sz = 1024 flip_aug = (not dont_colorize) content_weight = 1. - alpha assert (0.0 <= content_weight) and (content_weight <= 1.0), "alpha must be between 0 and 1" # Modify device based on checkbox value device = torch.device('cuda' if torch.cuda.is_available() and not use_cpu else 'cpu') cnn = Vgg16Pretrained().to(device) phi = lambda x, y, z: cnn.forward(x, inds=y, concat=z) content_im_orig = load_path_for_pytorch(content_path, target_size=sz).to(device).unsqueeze(0) style_im_orig = load_path_for_pytorch(style_path, target_size=sz).to(device).unsqueeze(0) try: torch.cuda.synchronize() start_time = time.time() output = produce_stylization(content_im_orig, style_im_orig, phi, max_iter=200, lr=2e-3, content_weight=content_weight, max_scls=max_scls, flip_aug=flip_aug, content_loss=content_loss, dont_colorize=dont_colorize) torch.cuda.synchronize() print('Done! total time: {}'.format(time.time() - start_time)) new_im_out = np.clip(output[0].permute(1, 2, 0).cpu().numpy(), 0., 1.) # Moved to CPU for display save_im = (new_im_out * 255).astype(np.uint8) imwrite(output_path, save_im) if not use_cpu: torch.cuda.empty_cache() QMessageBox.information(self, "Success", "Style Transfer completed successfully!") except Exception as e: QMessageBox.critical(self, "Error", f"An error occurred: {str(e)}") if __name__ == "__main__": app = QApplication(sys.argv) style_transfer_app = StyleTransferApp() style_transfer_app.show() sys.exit(app.exec_())
a345ca6699de6ea99a6ec668fe424395
{ "intermediate": 0.376630574464798, "beginner": 0.4792911410331726, "expert": 0.144078329205513 }
45,788
i have an app that use a db with : id,data,name,tag,type,description,status,upload_date,version i have another db that use : idbatchs,nom_batch,nom_effectif,description,domaine,frequence,responsable,emails,action,criticite,etat,date_derniere_execution,date_validation_fe,validateur,ticket_jira,ticket_sm,cpsi i need a way to merge all in one table, preferbly the db that the app use
ba3bca10f39c6c9478ee23cde4de41df
{ "intermediate": 0.3528667986392975, "beginner": 0.4387325048446655, "expert": 0.208400696516037 }
45,789
fix this code so the error Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! doesn't happen: import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget, QFileDialog, QCheckBox, QMessageBox import argparse import random import time import torch import numpy as np from imageio import imwrite from pretrained.vgg import Vgg16Pretrained from utils.misc import load_path_for_pytorch from utils.stylize import produce_stylization class StyleTransferApp(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Style Transfer") self.content_path_label = QLabel("Content Image Path:") self.content_path_input = QLineEdit() self.content_path_button = QPushButton("Browse") self.content_path_button.clicked.connect(self.browse_content_image) self.style_path_label = QLabel("Style Image Path:") self.style_path_input = QLineEdit() self.style_path_button = QPushButton("Browse") self.style_path_button.clicked.connect(self.browse_style_image) self.output_path_label = QLabel("Output Path:") self.output_path_input = QLineEdit() self.output_path_button = QPushButton("Browse") self.output_path_button.clicked.connect(self.browse_output_path) self.high_res_checkbox = QCheckBox("High Resolution") self.content_loss_checkbox = QCheckBox("Content Loss") self.dont_colorize_checkbox = QCheckBox("Don't Colorize") self.cpu_checkbox = QCheckBox("Use CPU") # New checkbox for CPU self.alpha_label = QLabel("Alpha:") self.alpha_input = QLineEdit("0.75") self.run_button = QPushButton("Run Style Transfer") self.run_button.clicked.connect(self.run_style_transfer) layout = QVBoxLayout() layout.addWidget(self.content_path_label) layout.addWidget(self.content_path_input) layout.addWidget(self.content_path_button) layout.addWidget(self.style_path_label) layout.addWidget(self.style_path_input) layout.addWidget(self.style_path_button) layout.addWidget(self.output_path_label) layout.addWidget(self.output_path_input) layout.addWidget(self.output_path_button) layout.addWidget(self.high_res_checkbox) layout.addWidget(self.content_loss_checkbox) layout.addWidget(self.dont_colorize_checkbox) layout.addWidget(self.cpu_checkbox) # Add CPU checkbox layout.addWidget(self.alpha_label) layout.addWidget(self.alpha_input) layout.addWidget(self.run_button) central_widget = QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) def browse_content_image(self): file_path, _ = QFileDialog.getOpenFileName(self, "Select Content Image") if file_path: self.content_path_input.setText(file_path) def browse_style_image(self): file_path, _ = QFileDialog.getOpenFileName(self, "Select Style Image") if file_path: self.style_path_input.setText(file_path) def browse_output_path(self): file_path, _ = QFileDialog.getSaveFileName(self, "Save Output As") if file_path: self.output_path_input.setText(file_path) def run_style_transfer(self): content_path = self.content_path_input.text() style_path = self.style_path_input.text() output_path = self.output_path_input.text() high_res = self.high_res_checkbox.isChecked() content_loss = self.content_loss_checkbox.isChecked() dont_colorize = self.dont_colorize_checkbox.isChecked() use_cpu = self.cpu_checkbox.isChecked() # Retrieve CPU checkbox value alpha = float(self.alpha_input.text()) # Core Logic from your provided code random.seed(0) np.random.seed(0) torch.manual_seed(0) max_scls = 4 sz = 512 if high_res: max_scls = 5 sz = 1024 flip_aug = (not dont_colorize) content_weight = 1. - alpha assert (0.0 <= content_weight) and (content_weight <= 1.0), "alpha must be between 0 and 1" # Modify device based on checkbox value device = torch.device('cuda' if torch.cuda.is_available() and not use_cpu else 'cpu') cnn = Vgg16Pretrained().to(device) phi = lambda x, y, z: cnn.forward(x, inds=y, concat=z) content_im_orig = load_path_for_pytorch(content_path, target_size=sz).to(device).unsqueeze(0) style_im_orig = load_path_for_pytorch(style_path, target_size=sz).to(device).unsqueeze(0) try: torch.cuda.synchronize() start_time = time.time() output = produce_stylization(content_im_orig, style_im_orig, phi, max_iter=200, lr=2e-3, content_weight=content_weight, max_scls=max_scls, flip_aug=flip_aug, content_loss=content_loss, dont_colorize=dont_colorize) torch.cuda.synchronize() print('Done! total time: {}'.format(time.time() - start_time)) new_im_out = np.clip(output[0].permute(1, 2, 0).cpu().numpy(), 0., 1.) # Moved to CPU for display save_im = (new_im_out * 255).astype(np.uint8) imwrite(output_path, save_im) if not use_cpu: torch.cuda.empty_cache() QMessageBox.information(self, "Success", "Style Transfer completed successfully!") except Exception as e: QMessageBox.critical(self, "Error", f"An error occurred: {str(e)}") if __name__ == "__main__": app = QApplication(sys.argv) style_transfer_app = StyleTransferApp() style_transfer_app.show() sys.exit(app.exec_())
387ff410875d4d4b4e6b7c2f916d6c56
{ "intermediate": 0.39229318499565125, "beginner": 0.44996631145477295, "expert": 0.1577404886484146 }
45,790
Write a function to generate the narrowband channel for mmwave massive MIMO system. The narrowband channel parameters are as follows: 1. Number of cluster follows uniform distribution between 1 and 5. 2. Number of rays per cluster follows uniform distribution between 1 and 4. 3. Azimuth angles follow a Laplacian distribution, where the mean angles are uniformly distributed in the interval [0,2π) and angular spread is set to 10 degrees. 4. Elevation angles follow a Laplacian distribution, where the mean angles are uniformly distributed in the interval [−π/2,π/2) and angular spread is set to 10 degrees. 5. Path gains (beta) follows the Rayleigh distribution. 6. Number of transmit anttena is set to 16. 7. Number of receive antenna is set to 64. rng(111);% Set RNG state for repeatability Nclmax= ; % The maximum number of scattering cluster Nclmin= ; % The minimum number of scattering cluster Nraymax= ; % The maximum number of rays in each cluster Nraymin= ; % The minimum number of rays in each cluster Nt= ; % Number of Tx antenna Nr= ; % Number of Rx antenna sigma= ; % Angular spread % Compute the number of scattering cluster as per the given distribution Ncl= %% Compute the Number of rays in each cluster as per the given distribution Nray= %% Compute the normalization factor gamma= %% Loop over number of clusters for %% Loop over number of rays in each clsuter for %% Generate path gain associated with the k-th ray in i-th clusters as per the given distribution Beta= % Compute the average elevation angle as per the given distribution mue= % Compute the average azimuth angle as per the given distribution mua= %% Compute the elevation angles for the user and BS as per the given distribution thetaUE = thetaBs = %% Compute the azimuth angles for the user and BS as per the given distribution PhiUE = PhiBs = %% Generate array response vector for the user aUE = end end %% Generate array response vector for the base station aBS = %% Generate the channel and accumulate end end %% Assign the generated channel to the variable H H= %% Display the channel matrtrix disp("H: " H); %% Laplacian distribution function function [x,y] = lprnd(m, n, mu, sigma) %Check inputs if nargin < 2 error('At least two inputs are required'); end if nargin == 2 mu = 0; sigma = 1; end if nargin == 3 sigma = 1; end % Generate Laplacian noise u = rand(m, n)-0.5; b = sigma / sqrt(2); x = mu - b * sign(u).* log(1- 2* abs(u)); y = mu - b * sign(u).* log(1- 2* abs(u)); end fill the code
f3452963f9c38ba0461712cb79e74654
{ "intermediate": 0.2178301215171814, "beginner": 0.4987676739692688, "expert": 0.2834022045135498 }
45,791
write a C macro that receives a function name and calls it if the function exists or does nothing if it doesn't. Please do not use dlsym or other functions like that.
4c8210c035851b1422083f625ab33eef
{ "intermediate": 0.28473806381225586, "beginner": 0.4337015450000763, "expert": 0.28156039118766785 }
45,792
make sure this code doesnt create the error Traceback (most recent call last): File "D:\NeuralNeighborStyleTransfer-main\1.txt", line 110, in run_style_transfer cnn = misc.to_device(Vgg16Pretrained(), device=device) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: to_device() got an unexpected keyword argument 'device': import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget, QFileDialog, QCheckBox, QMessageBox import argparse import random import time import torch import numpy as np from imageio import imwrite from pretrained.vgg import Vgg16Pretrained from utils import misc as misc from utils.misc import load_path_for_pytorch from utils.stylize import produce_stylization class StyleTransferApp(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Style Transfer") self.content_path_label = QLabel("Content Image Path:") self.content_path_input = QLineEdit() self.content_path_button = QPushButton("Browse") self.content_path_button.clicked.connect(self.browse_content_image) self.style_path_label = QLabel("Style Image Path:") self.style_path_input = QLineEdit() self.style_path_button = QPushButton("Browse") self.style_path_button.clicked.connect(self.browse_style_image) self.output_path_label = QLabel("Output Path:") self.output_path_input = QLineEdit() self.output_path_button = QPushButton("Browse") self.output_path_button.clicked.connect(self.browse_output_path) self.high_res_checkbox = QCheckBox("High Resolution") self.content_loss_checkbox = QCheckBox("Content Loss") self.dont_colorize_checkbox = QCheckBox("Don't Colorize") self.cpu_checkbox = QCheckBox("Use CPU") # New checkbox for CPU self.alpha_label = QLabel("Alpha:") self.alpha_input = QLineEdit("0.75") self.run_button = QPushButton("Run Style Transfer") self.run_button.clicked.connect(self.run_style_transfer) layout = QVBoxLayout() layout.addWidget(self.content_path_label) layout.addWidget(self.content_path_input) layout.addWidget(self.content_path_button) layout.addWidget(self.style_path_label) layout.addWidget(self.style_path_input) layout.addWidget(self.style_path_button) layout.addWidget(self.output_path_label) layout.addWidget(self.output_path_input) layout.addWidget(self.output_path_button) layout.addWidget(self.high_res_checkbox) layout.addWidget(self.content_loss_checkbox) layout.addWidget(self.dont_colorize_checkbox) layout.addWidget(self.cpu_checkbox) # Add CPU checkbox layout.addWidget(self.alpha_label) layout.addWidget(self.alpha_input) layout.addWidget(self.run_button) central_widget = QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) def browse_content_image(self): file_path, _ = QFileDialog.getOpenFileName(self, "Select Content Image") if file_path: self.content_path_input.setText(file_path) def browse_style_image(self): file_path, _ = QFileDialog.getOpenFileName(self, "Select Style Image") if file_path: self.style_path_input.setText(file_path) def browse_output_path(self): file_path, _ = QFileDialog.getSaveFileName(self, "Save Output As") if file_path: self.output_path_input.setText(file_path) def run_style_transfer(self): content_path = self.content_path_input.text() style_path = self.style_path_input.text() output_path = self.output_path_input.text() high_res = self.high_res_checkbox.isChecked() content_loss = self.content_loss_checkbox.isChecked() dont_colorize = self.dont_colorize_checkbox.isChecked() use_cpu = self.cpu_checkbox.isChecked() # Retrieve CPU checkbox value alpha = float(self.alpha_input.text()) # Core Logic from your provided code random.seed(0) np.random.seed(0) torch.manual_seed(0) max_scls = 4 sz = 512 if high_res: max_scls = 5 sz = 1024 flip_aug = (not dont_colorize) content_weight = 1. - alpha assert (0.0 <= content_weight) and (content_weight <= 1.0), "alpha must be between 0 and 1" # Modify device based on checkbox value if use_cpu: device = torch.device('cpu') else: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') cnn = misc.to_device(Vgg16Pretrained(), device=device) phi = lambda x, y, z: cnn.forward(x, inds=y, concat=z) content_im_orig = misc.to_device(load_path_for_pytorch(content_path, target_size=sz), device=device).unsqueeze(0) style_im_orig = misc.to_device(load_path_for_pytorch(style_path, target_size=sz), device=device).unsqueeze(0) try: torch.cuda.synchronize() start_time = time.time() output = produce_stylization(content_im_orig, style_im_orig, phi, max_iter=200, lr=2e-3, content_weight=content_weight, max_scls=max_scls, flip_aug=flip_aug, content_loss=content_loss, dont_colorize=dont_colorize) torch.cuda.synchronize() print('Done! total time: {}'.format(time.time() - start_time)) new_im_out = np.clip(output[0].permute(1, 2, 0).detach().cpu().numpy(), 0., 1.) save_im = (new_im_out * 255).astype(np.uint8) imwrite(output_path, save_im) if not use_cpu: torch.cuda.empty_cache() QMessageBox.information(self, "Success", "Style Transfer completed successfully!") except Exception as e: QMessageBox.critical(self, "Error", f"An error occurred: {str(e)}") if __name__ == "__main__": app = QApplication(sys.argv) style_transfer_app = StyleTransferApp() style_transfer_app.show() sys.exit(app.exec_())
076455087651d671a1d36a82abd7341d
{ "intermediate": 0.32615718245506287, "beginner": 0.5228910446166992, "expert": 0.15095177292823792 }
45,793
correct this query (select de.DeviceID as rsndeviceid, tupd.DeviceID ,v1.vehicleid as GQSIIIVehicleID from tblUDPDataToProcessforQSConPktDtls tupd left join device_kipi de on de.DeviceSerialNumber=tupd.rsnserialnumber left join VehicleDeviceMapping V1 on V1.DeviceID= tupd.DeviceID
6ce8874c6db2b912882c7eeee7d52947
{ "intermediate": 0.456269770860672, "beginner": 0.2833259403705597, "expert": 0.2604043185710907 }
45,794
Is this correct merge statement in snowflake MERGE INTO VehicleDeviceMapping_kipi AS V USING ( SELECT DISTINCT de.DeviceID AS rsndeviceid, tupd.DeviceID, v1.VehicleID AS GQSIIIVehicleID FROM tblUDPDataToProcessforQSConPktDtls AS tupd LEFT JOIN device_kipi AS de ON de.DeviceSerialNumber = tupd.rsnserialnumber LEFT JOIN VehicleDeviceMapping AS v1 ON v1.DeviceID = tupd.DeviceID QUALIFY ROW_NUMBER() OVER (PARTITION BY tupd.DeviceID ORDER BY v1.VehicleID) = 1 ) SRC ON V.DeviceID = SRC.rsndeviceid WHEN MATCHED AND V.VehicleID = SRC.GQSIIIVehicleID THEN UPDATE SET V.Active = 0, V.DeletedBy = 1, V.DeletedOn = CURRENT_TIMESTAMP() WHEN NOT MATCHED AND V.VehicleID = SRC.GQSIIIVehicleID THEN INSERT ( VehicleID, DeviceID, CreatedBy, CreatedOn, CustomerID, Active ) VALUES ( SRC.GQSIIIVehicleID, SRC.rsndeviceid, 1, CURRENT_TIMESTAMP(), CustomerID, 1 ) WHEN NOT MATCHED THEN INSERT ( VehicleID, DeviceID, CreatedBy, CreatedOn, CustomerID, Active ) VALUES ( SRC.GQSIIIVehicleID, SRC.rsndeviceid, 1, CURRENT_TIMESTAMP(), CustomerID, 1 );
81a79289696e34c9a95415a805502ad7
{ "intermediate": 0.26043403148651123, "beginner": 0.43050041794776917, "expert": 0.3090655505657196 }
45,795
const handleClick = event => { const screen = document.getElementById('screen'); const key = event.target.textContent; switch (key) { case 'C': screen.textContent = '0'; break; case '=': try { const result = Function('return ' + screen.textContent)(); screen.textContent = result; } catch (e) { screen.textContent = 'Błąd'; } break; default: if (screen.textContent.lenght > 8){ return; } if (screen.textContent === '0') screen.textContent = key; else screen.textContent += key; break; } }; const init = e => { const container = document.getElementById('container'); const children = container.children; for (let i = 0; i < children.length; i++){ children[i].addEventListener('click', handleClick); } } window.addEventListener('DOMContentLoaded', init); zamien na class
71e5e0083007ef85bd02294e3e62ea9a
{ "intermediate": 0.30662715435028076, "beginner": 0.38203591108322144, "expert": 0.3113369047641754 }
45,796
combine these two code segments, such that if answer is not available in similarity based solution then it will go to llm based solution whose code is in predict function def preprocess_input(usertext): dates = list(datefinder.find_dates(usertext)) print('dates',dates) if dates: # Use the first detected date formatted_date = dates[0].strftime("%d-%b-%Y") filtered_df = new_df[new_df['date'] == formatted_date] # Filter for matching date else: # Filter for entries without a valid date filtered_df = new_df[new_df['date'] == 'NO_DATE'] print(filtered_df) if filtered_df.empty: return None, "No matching data found for your query." return filtered_df, None def get_most_similar_question(userText,history): filtered_df, error_msg = preprocess_input(userText.lower()) if filtered_df is None: return error_msg filtered_df['Question'] = filtered_df['Question'].str.lower() question_list = filtered_df["Question"].to_list() question_embeddings = retrieval_model.encode(question_list) user_text_embedding = retrieval_model.encode([userText.lower()]) # # Calculate similarity scores similarity_scores = np.inner(user_text_embedding, question_embeddings).flatten() top_match_idx = np.argmax(similarity_scores) if similarity_scores[top_match_idx] == 0: return "Sorry, no similar questions were found for your query." matched_data = filtered_df.iloc[top_match_idx,[10]] return matched_data.to_frame().T.to_html(index=False) # Returning the matched row as HTML this is my old code def get_most_similar_question(userText, history): print(userText) # userText = preprocess_user_input(userText) # You may now use processed_user_query to perform a retrieval using your model # Compute embedding for the user input text using the initial retrieval model inp_emb = retrieval_model.encode([userText]) # Calculate similarity scores between user input text and data embeddings corr = np.inner(inp_emb, data_emb).flatten() # Get indices of the top 5 most similar texts top_5_idx = np.argsort(corr)[-1:] # print('idx',top_5_idx) top_5_values = corr[top_5_idx] # print('values',top_5_values) # Retrieve the texts/questions corresponding to these indices top_5_texts = new_df.iloc[top_5_idx, 1].values # Column 1 contains the texts/questions # print(top_5_texts) # data_emb_1 = retrieval_model.encode([top_5_texts]) # corr_1 = np.inner(inp_emb, data_emb_1).flatten() # top_1_idx = np.argsort(corr_1)[-5:] # # print('idx',top_1_idx) # top_1_values = corr_1[top_1_idx] # # print('values',top_1_values) # top_1_texts = new_df.iloc[top_1_idx, 1].values # Column 1 contains the texts/questions # print(top_1_texts) # # Re-encode these top 5 texts using the new retrieval model # data_emb_1 = new_retrieval_model(top_5_texts) # # Calculate similarity with the input text using the new model's embeddings # inp_emb_1 = new_retrieval_model([userText]) # corr_1 = np.inner(inp_emb_1, data_emb_1).flatten() # print('corr_1',corr_1) # # Identify the highest similarity score and its index # top_1_idx = np.argmax(corr_1) # print('top_1_idx',top_1_idx) # top_1_idx = top_1_idx+1 # print('top_1_idx_11',top_1_idx) # top_1_value = corr_1[top_1_idx] # print('top_1_value',top_1_value) # top_1_texts = top_5_texts[top_1_idx+1] # print('top_1_texts',top_1_texts) print('Matching score:', top_5_values[0]) # print('Matching score second time:', top_1_value) # Decision to call predict or return the highest ranked text based on similarity threshold if top_5_values[0] < 0.8: # Placeholder for the 'predict' function, assuming you have it defined elsewhere to handle insufficient similarity scenarios return predict(userText, history) else: # Crafting a DataFrame to convert to HTML, using top_1_idx to find original index in new_df most_similar_data = new_df.iloc[top_5_idx, [1]] # Adjusted for Python's indexing most_similar_data_df = pd.DataFrame(most_similar_data) df_html_with_sql = most_similar_data_df.to_html(index=False) html_output = f"<h3>Here is the top matching result(s) for your query:</h3>{df_html_with_sql}" return html_output
1c1f535dcc89a14d8749882fc3af5849
{ "intermediate": 0.4827239215373993, "beginner": 0.3430764973163605, "expert": 0.1741996556520462 }
45,797
JS script in <head> or <body> of html?
b2b8671448a65791c2f4a8b4d05f3cfe
{ "intermediate": 0.38184142112731934, "beginner": 0.3001601994037628, "expert": 0.31799837946891785 }
45,798
How to check the amount of PCs and Users inside specific OU in active Directory
00b99224ee374af8d569d90f2635f087
{ "intermediate": 0.30658188462257385, "beginner": 0.2676897644996643, "expert": 0.42572829127311707 }
45,799
what the CMC login user in linus
73f4ea6fde7f75c06cc309c675a3b142
{ "intermediate": 0.3223676383495331, "beginner": 0.27759453654289246, "expert": 0.40003785490989685 }
45,800
As the Leonardo AI Prompt Maker, your main objective is to craft three distinct Stable Diffusion prompts based on a provided keyword. Adhere strictly to the specified prompt structure, incorporating essential details like subject description, image type, art styles, art inspirations, camera specifics, shot details, render-related information, and other pertinent keywords. Your role involves the generation of these prompts following a step-by-step process: weighted Keywords Use round brackets () to provide specific details about the subject and action in the prompt. These details are important for generating a high-quality image. Keywords and Descriptions Adjective keywords: cute, medieval, futuristic Environment/background keywords: indoor, outdoor, in space, solid color Image type keywords: digital illustration, comic book cover, photograph, sketch Art style keywords: steampunk, surrealism, abstract expressionism Pencil drawing-related terms: cross-hatching, pointillism Camera shot types: long shot, close-up, POV, medium shot, extreme close-up, panoramic Camera lens types: EE 70mm, 35mm, 135mm+, 300mm+, 800mm, short telephoto, super telephoto, medium telephoto, macro, wide angle, fish-eye, bokeh, sharp focus Camera view types: front, side, back, high angle, low angle, overhead Resolution/detail keywords: 4K, 8K, 64K, detailed, highly detailed, high resolution, hyper detailed, HDR, UHD, professional, golden ratio Lighting keywords: studio lighting, soft light, neon lighting, purple neon lighting, ambient light, ring light, volumetric light, natural light, sun light, sunrays, sun rays coming through window, nostalgic lighting Color type keywords: fantasy vivid colors, vivid colors, bright colors, sepia, dark colors, pastel colors, monochromatic, black & white, color splash Render keywords: Octane render, cinematic, low poly, isometric assets, Unreal Engine, Unity Engine, quantum wavetracing, polarizing filter 1. Begin by receiving a keyword from the user. 2. Generate three varied Stable Diffusion prompts, each tailored to the given keyword. 3. Abide by the prescribed prompt structure, ensuring inclusion of all necessary details. 4. Utilize VB.NET code blocks for ease of copy-paste, presenting each prompt in separate code blocks. 5. Maintain clear separation by placing each prompt in distinct code blocks. 6. Exercise caution to follow guidelines, refraining from describing unrealistic concepts as “real” or “realistic.” Additionally, avoid assigning artists for realistic photography prompts. 7. Insert two new lines between each prompt to ensure proper differentiation. Your responsibility is crucial in providing coherent and comprehensive prompts aligned with the specified criteria. Execute this task with precision and creativity to enhance the Stable Diffusion prompts effectively.
a8bb0dd1d2142fc86c4658110c1e78be
{ "intermediate": 0.30551600456237793, "beginner": 0.31801483035087585, "expert": 0.37646913528442383 }
45,801
def component_name_to_indices(component_name): component_order = ['M0', 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'C0', 'I0', 'V1'] return component_order.index(component_name) + 7 # Adjust 7 based on your actual structure class EnhancedGNNModelWithSharedParams(torch.nn.Module): def __init__(self, num_node_features, num_edge_features, num_out_features): print("EnhancedGNNModelWithSharedParams __init__ arguments:", num_node_features, num_edge_features, num_out_features) super(EnhancedGNNModelWithSharedParams, self).__init__() self.conv1 = GATConv(num_node_features, 8, heads=8, dropout=0.6) nn_model = Sequential(Linear(num_edge_features, 32), ReLU(), Linear(32, 8 * 8)) self.conv2 = NNConv(8 * 8, num_out_features, nn_model, aggr='mean') def forward(self, node_features, edge_index, edge_attr): # Apply adjustment of shared parameters integrated within the model class modified_node_features = self.adjust_node_features(node_features) x = F.dropout(modified_node_features, p=0.6, training=self.training) x = F.elu(self.conv1(x, edge_index)) x = self.conv2(x, edge_index, edge_attr) print(f"GNN Model Output Shape: {x.shape}") # Debug print statement return x def adjust_node_features(self, node_features_tensor): # Filters out component nodes based on the ‘device_type’ feature component_mask = node_features_tensor[:, 0] == 0.0 node_features = node_features_tensor[component_mask] # Pairs for shared ‘w_value’ and ‘l_value’ pairs = [('M0', 'M1'), ('M2', 'M3'), ('M4', 'M7')] for pair in pairs: # Identify indices for the pair components indices = [component_name_to_indices(component) for component in pair] value_indices = [18, 19] # Assuming these are the indices for ‘w_value’, ‘l_value’ for i in indices[1:]: # Start from the second component of the pair first_component_mask = node_features[:, indices[0]] == 1.0 other_component_mask = node_features[:, i] == 1.0 if torch.any(first_component_mask) and torch.any(other_component_mask): # Adjust values of the other components within the pair to match the first #other_values = node_features[other_component_mask][:, value_indices] #first_values = node_features[first_component_mask][:, value_indices][0] #other_values[:] = first_values node_features[other_component_mask][:, value_indices] = node_features[first_component_mask][:, value_indices][0] return node_features class Actor(nn.Module): def __init__(self, num_input_features, action_dim, std): super(Actor, self).__init__() print("Actor __init__ arguments:", num_input_features, action_dim, std) # Define the actor model self.actor = nn.Sequential( nn.Linear(num_input_features, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, action_dim), ) self.log_std = nn.Parameter(torch.ones(1, action_dim) * std) def forward(self, x): mean = self.actor(x) std = self.log_std.exp().expand_as(mean) print(f"Actor Model Output Shape (Mean): {mean.shape}") # Debug print statement return mean, std class Critic(nn.Module): def __init__(self, num_input_features): super(Critic, self).__init__() # Define the critic model self.critic = nn.Sequential( nn.Linear(num_input_features, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 1) ) def forward(self, x): value = self.critic(x) print(f"Critic Model Output Shape (Value): {value.shape}") # Debug print statement return value class PPOAgent: def __init__(self, actor_class, critic_class, gnn_model, action_dim, bounds_low, bounds_high, lr_actor=3e-4, lr_critic=1e-3, gamma=0.99, lamda=0.95, epsilon=0.2, std=0.0): print("gnn_model", gnn_model) self.actor = actor_class(gnn_model.conv2.out_channels, action_dim, std) # Initialize actor self.critic = critic_class(gnn_model.conv2.out_channels) # Initialize critic self.gnn_model = gnn_model # GNN model instance self.optimizer_actor = optim.Adam(self.actor.parameters(), lr=lr_actor) self.optimizer_critic = optim.Adam(self.critic.parameters(), lr=lr_critic) self.gamma = gamma self.lamda = lamda self.epsilon = epsilon #self.bounds_low = torch.tensor(bounds_low).float() #self.bounds_high = torch.tensor(bounds_high).float() self.bounds_low = bounds_low self.bounds_high = bounds_high self.std = std self.epochs = 10 # Define the number of epochs for policy update def select_action(self, state, edge_index, edge_attr): # Pass state through the GNN model first to get state’s embedding state_embedding = self.gnn_model(state, edge_index, edge_attr) print(f"State Embedding Shape: {state_embedding.shape}") # Then, pass the state embedding through the actor network to get action mean and std mean, std = self.actor(state_embedding) # Rearranging based on the specifications rearranged_mean = rearrange_action_output(mean) # Scale mean based on action bounds defined mean = self.bounds_low + (torch.sigmoid(rearranged_mean) * (self.bounds_high - self.bounds_low)) dist = Normal(mean, std) # Sample an action from the distribution and calculate its log probability action = dist.sample() action = torch.clamp(action, self.bounds_low, self.bounds_high) # Ensure action is within bounds action_log_prob = dist.log_prob(action) return action.detach(), action_log_prob.detach() # Initializing the GNN Model (EnhancedGNNModelWithSharedParams) num_node_features = 24# Define based on your graph data num_edge_features = 11# Define based on your graph data num_out_features = 19# Define based on the expected output feature size of your GNN # Initializing the Actor and Critic with the GNN Model action_dim = 19# Define according to your action space dimensions actor = Actor(num_out_features, action_dim, std=0.0) print("actor", actor) critic = Critic(num_out_features) # Create the environment env = CircuitEnvironment(server_address, username, password, bounds_low, bounds_high, target_metrics, netlist_content) gnn_model = EnhancedGNNModelWithSharedParams(num_node_features, num_edge_features, num_out_features) actor_output_features = gnn_model.conv2.out_channels print(f"Initializing Actor with output feature size: {actor_output_features}") print("GNN Model Conv2 Out Channels:", gnn_model.conv2.out_channels) print("Action Dimension:", action_dim) agent = PPOAgent(actor, critic, gnn_model, action_dim, bounds_low, bounds_high, lr_actor, lr_critic, gamma, lambda_, epsilon, std) # Train agent train(env, agent, env.num_episodes, env.max_timesteps, env.batch_size, env.epsilon)
859c606b291ae5d4f7340d6dc6ab0f17
{ "intermediate": 0.26940658688545227, "beginner": 0.4659319519996643, "expert": 0.26466143131256104 }
45,802
Hi there, please be a senior sapui5 developer and answer my question with working code example.
1f392ed11740ebf97b9fd72a334100d4
{ "intermediate": 0.41841742396354675, "beginner": 0.24756212532520294, "expert": 0.3340204656124115 }
45,803
how to check certificates of installed vibs on esxi
14830ca2482bc4487e306aec01af1ce3
{ "intermediate": 0.4510401785373688, "beginner": 0.20086918771266937, "expert": 0.3480905592441559 }
45,804
Привет! Помоги изменить логику бота. Я хочу перенести questions в БД, причем сохранить функционал так, чтобы можно было удалять и добавлять вопросы, а бот при этом не ломался. вот код: from aiogram import Bot, Dispatcher, executor, types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup import aiosqlite import asyncio API_TOKEN = '6306133720:AAH0dO6nwIlnQ7Hbts6RfGs0eI73EKwx-hE' bot = Bot(token=API_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) class Form(StatesGroup): choosing_action = State() answer_name = State() answer_birthday = State() answer_skills = State() answer_hobbies = State() personal_account = State() edit_answer = State() new_answer = State() async def create_db(): async with aiosqlite.connect('memory_page.db') as db: await db.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT NOT NULL, last_question_idx INTEGER DEFAULT 0)''') await db.execute('''CREATE TABLE IF NOT EXISTS answers ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, question TEXT, answer TEXT, FOREIGN KEY (user_id) REFERENCES users (id))''') await db.commit() async def add_user(user_id: int, username: str): async with aiosqlite.connect('memory_page.db') as db: cursor = await db.execute('SELECT id FROM users WHERE id = ?', (user_id,)) user_exists = await cursor.fetchone() if user_exists: await db.execute('UPDATE users SET username = ? WHERE id = ?', (username, user_id)) else: await db.execute('INSERT INTO users (id, username) VALUES (?, ?)', (user_id, username)) await db.commit() @dp.message_handler(commands="start", state="*") async def cmd_start(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) user_id = message.from_user.id username = message.from_user.username or "unknown" await add_user(user_id, username) await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() @dp.message_handler(lambda message: message.text == "В меню", state="*") async def back_to_menu(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() questions = [ "Имя", "Дата рождения", "Ваши умения", "Ваши увлечения" ] async def save_answer(user_id: int, question: str, answer: str, question_idx: int): async with aiosqlite.connect('memory_page.db') as db: await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question, answer)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (question_idx, user_id)) await db.commit() async def set_next_question(user_id: int, question_idx: int): state = dp.current_state(user=user_id) markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("В меню")) if question_idx == 0: await state.set_state(Form.answer_name.state) await bot.send_message(user_id, questions[0],reply_markup=markup) elif question_idx == 1: await state.set_state(Form.answer_birthday.state) await bot.send_message(user_id, questions[1],reply_markup=markup) elif question_idx == 2: await state.set_state(Form.answer_skills.state) await bot.send_message(user_id, questions[2],reply_markup=markup) elif question_idx == 3: await state.set_state(Form.answer_hobbies.state) await bot.send_message(user_id, questions[3],reply_markup=markup) else: await state.reset_state() await bot.send_message(user_id, "Вы ответили на все вопросы. Ответы сохранены.",reply_markup=markup) @dp.message_handler(lambda message: message.text == "Сгенерировать био", state=Form.choosing_action) async def generate_bio(message: types.Message): user_id = message.from_user.id async with aiosqlite.connect('memory_page.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() if result and result[0] > 0: await set_next_question(user_id, result[0]) else: await set_next_question(user_id, 0) @dp.message_handler(state=Form.answer_name) async def process_name(message: types.Message, state: FSMContext): await save_answer(message.from_user.id, questions[0], message.text,1) await Form.next() await message.answer(questions[1]) @dp.message_handler(state=Form.answer_birthday) async def process_birthday(message: types.Message, state: FSMContext): await save_answer(message.from_user.id, questions[1], message.text,2) await Form.next() await message.answer(questions[2]) @dp.message_handler(state=Form.answer_skills) async def process_skills(message: types.Message, state: FSMContext): await save_answer(message.from_user.id, questions[2], message.text,3) await Form.next() await message.answer(questions[3]) @dp.message_handler(state=Form.answer_hobbies) async def process_hobbies(message: types.Message, state: FSMContext): await save_answer(message.from_user.id, questions[3], message.text,4) await state.finish() await message.answer("Спасибо за ответы! Ваши ответы сохранены.") await cmd_start(message) @dp.message_handler(lambda message: message.text == "Личный кабинет", state=Form.choosing_action) async def personal_account(message: types.Message): user_id = message.from_user.id answers_text = "Ваши ответы:\n\n" async with aiosqlite.connect('memory_page.db') as db: cursor = await db.execute('SELECT question, answer FROM answers WHERE user_id=? ORDER BY id', (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question}: {answer}\n" if answers_text == "Ваши ответы:\n\n": answers_text = "Вы еще не отвечали на вопросы. Пожалуйста, нажмите «В меню» и выберите «Сгенерировать био», чтобы ответить на вопросы" markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("В меню")) await message.answer(answers_text, reply_markup=markup) else: markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) await message.answer(answers_text, reply_markup=markup) await Form.personal_account.set() @dp.message_handler(lambda message: message.text == "Изменить ответ", state=Form.personal_account) async def change_answer(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("В меню")) await message.answer("Введите номер вопроса, на который хотите изменить ответ:",reply_markup=markup) await Form.edit_answer.set() @dp.message_handler(state=Form.edit_answer) async def process_question_number(message: types.Message, state: FSMContext): text = message.text if not text.isdigit(): await message.answer("Пожалуйста, введите число, а не текст. \nПопробуйте еще раз:") return question_number = int(text) if 1<= question_number <= len(questions): await state.update_data(question_number=question_number) await message.answer("Введите новый ответ:") await Form.new_answer.set() else: await message.answer(f"Вопроса под номером {question_number} не существует. Пожалуйста, выберите номер вопроса от 1 до {len(questions)}.\nПопробуйте еще раз:") @dp.message_handler(state=Form.new_answer) async def process_new_answer(message: types.Message, state: FSMContext): user_data = await state.get_data() question_number = user_data['question_number'] new_answer = message.text user_id = message.from_user.id question = questions[question_number - 1] async with aiosqlite.connect('memory_page.db') as db: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer, user_id, question)) await db.commit() await message.answer(f"Ваш ответ на вопрос «{question}» изменен на: {new_answer}") await state.finish() await personal_account(message) @dp.message_handler(lambda message: message.text == "Заполнить заново", state=Form.personal_account) async def refill_form(message: types.Message): markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да", callback_data="confirm_refill")) await message.answer("Вы уверены, что хотите начать заново? Все текущие ответы будут удалены.", reply_markup=markup) @dp.callback_query_handler(lambda c: c.data == 'confirm_refill', state=Form.personal_account) async def process_refill(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with aiosqlite.connect('memory_page.db') as db: await db.execute('DELETE FROM answers WHERE user_id=?', (user_id,)) await db.commit() await db.execute('UPDATE users SET last_question_idx = 0 WHERE id = ?', (user_id,)) await db.commit() await bot.answer_callback_query(callback_query.id) await cmd_start(callback_query.message) async def main(): await create_db() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) executor.start_polling(dp, skip_updates=True)
7b2b2dcac5b253ecb01db5b36e29417e
{ "intermediate": 0.36800387501716614, "beginner": 0.5558831095695496, "expert": 0.0761130228638649 }
45,805
private readonly List<long> _grenadeIndex = [14, 15, 17, 16, 13]; private HookResult EventItemPickup(EventItemPickup @event, GameEventInfo info) { if (!_grenadeIndex.Contains(@event.Defindex)) return HookResult.Continue; foreach (var weapon in @event.Userid.PlayerPawn.Value.WeaponServices.MyWeapons) { switch (weapon.Value.DesignerName) { case "weapon_hegrenade": case "weapon_molotov": case "weapon_incgrenade": case "weapon_decoy": case "weapon_smokegrenade": case "weapon_flashbang": { weapon.Value.Remove(); break; } } } return HookResult.Continue; } private void TakeGrenade() { foreach (var player in Utilities.GetPlayers().Where(u => u is { IsValid: true, Team: CsTeam.CounterTerrorist })) { var playerPawn = player.PlayerPawn.Value; if (playerPawn == null) continue; foreach (var weapon in playerPawn.WeaponServices!.MyWeapons) { switch (weapon.Value.DesignerName) { case "weapon_hegrenade": case "weapon_molotov": case "weapon_incgrenade": case "weapon_decoy": case "weapon_smokegrenade": case "weapon_flashbang": { weapon.Value.Remove(); break; } } } } } сделай это лучше
ddaa76807f6cfab4a5e3b596ccde943f
{ "intermediate": 0.306438684463501, "beginner": 0.44445982575416565, "expert": 0.24910154938697815 }
45,806
is it required to create separate class for writing test case of diffferent functions
5e1b8e13c151ad04e54cd164f514b879
{ "intermediate": 0.18871331214904785, "beginner": 0.608683168888092, "expert": 0.20260348916053772 }
45,807
hi
872a1a59f5b4e73c267ee655072f8406
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
45,808
#include <stdio.h> #include <stdlib.h> #include <semaphore.h> #include <fcntl.h> #include <unistd.h> #define SEMAFOR_1 “/sem1” #define SEMAFOR_2 “/sem2” void obslugaSemafora(sem_t* semafor, int op) { if (op == 0) { // Zajęcie semafora if (sem_wait(semafor) == -1) perror(“sem_wait error”); else printf(“Semafor zajety\n”); } else { // Zwolnienie semafora if (sem_post(semafor) == -1) perror(“sem_post error”); else printf(“Semafor zwolniony\n”); } } int main() { sem_t *sem1 = sem_open(SEMAFOR_1, O_CREAT, 0666, 1); sem_t *sem2 = sem_open(SEMAFOR_2, O_CREAT, 0666, 1); if (sem1 == SEM_FAILED || sem2 == SEM_FAILED) { perror(“sem_open error”); exit(EXIT_FAILURE); } char cmd; while (1) { printf(“1 - zajecie semafora 1, q - zwolnienie semafora 1,\n2 - zajecie semafora 2, w - zwolnienie semafora 2\n”); scanf(" %c", &cmd); switch (cmd) { case ‘1’: obslugaSemafora(sem1, 0); break; case ‘q’: obslugaSemafora(sem1, 1); break; case ‘2’: obslugaSemafora(sem2, 0); break; case ‘w’: obslugaSemafora(sem2, 1); break; default: printf(“Nieznane polecenie\n”); } } sem_close(sem1); sem_close(sem2); sem_unlink(SEMAFOR_1); sem_unlink(SEMAFOR_2); return 0; } przepisz kod
54b52b4f56d97dc383f2a9758e704e41
{ "intermediate": 0.264016330242157, "beginner": 0.5151424407958984, "expert": 0.2208411693572998 }
45,809
hi I want to buy a used car, what is the best option forme in mid range SUVs
16dd8be336e81ac35a85919406d2fc67
{ "intermediate": 0.3273719847202301, "beginner": 0.353179007768631, "expert": 0.3194490075111389 }
45,810
kerrickstaley/genanki: A Python 3 library for generating Anki decks A Python 3 library for generating Anki decks. Contribute to kerrickstaley/genanki development by crea...... genanki: A Library for Generating Anki Decks genanki allows you to programatically generate decks in Python 3 for Anki, a popular spaced-repetition flashcard program. Please see below for concepts and usage. This library and its author(s) are not affiliated/associated with the main Anki project in any way. Notes The basic unit in Anki is the Note, which contains a fact to memorize. Notes correspond to one or more Cards. Here's how you create a Note: my_note = genanki.Note( model=my_model, fields=['Capital of Argentina', 'Buenos Aires']) You pass in a Model, discussed below, and a set of fields (encoded as HTML). Models A Model defines the fields and cards for a type of Note. For example: my_model = genanki.Model( 1607392319, 'Simple Model', fields=[ {'name': 'Question'}, {'name': 'Answer'}, ], templates=[ { 'name': 'Card 1', 'qfmt': '{{Question}}', 'afmt': '{{FrontSide}}<hr>{{Answer}}', }, ]) This note-type has two fields and one card. The card displays the Question field on the front and the Question and Answer fields on the back, separated by a <hr>. You can also pass a css argument to Model() to supply custom CSS. You need to pass a model_id so that Anki can keep track of your model. It's important that you use a unique model_id for each Model you define. Use import random; random.randrange(1 << 30, 1 << 31) to generate a suitable model_id, and hardcode it into your Model definition. Generating a Deck/Package To import your notes into Anki, you need to add them to a Deck: my_deck = genanki.Deck( 2059400110, 'Country Capitals') my_deck.add_note(my_note) Once again, you need a unique deck_id that you should generate once and then hardcode into your .py file. Then, create a Package for your Deck and write it to a file: genanki.Package(my_deck).write_to_file('output.apkg') You can then load output.apkg into Anki using File -> Import... Media Files To add sounds or images, set the media_files attribute on your Package: my_package = genanki.Package(my_deck) my_package.media_files = ['sound.mp3', 'images/image.jpg'] media_files should have the path (relative or absolute) to each file. To use them in notes, first add a field to your model, and reference that field in your template: my_model = genanki.Model( 1091735104, 'Simple Model with Media', fields=[ {'name': 'Question'}, {'name': 'Answer'}, {'name': 'MyMedia'}, # ADD THIS ], templates=[ { 'name': 'Card 1', 'qfmt': '{{Question}}<br>{{MyMedia}}', # AND THIS 'afmt': '{{FrontSide}}<hr>{{Answer}}', }, ]) Then, set the MyMedia field on your card to [sound:sound.mp3] for audio and <img src="image.jpg"> for images. You cannot put <img src="{MyMedia}"> in the template and image.jpg in the field. See these sections in the Anki manual for more information: Importing Media and Media & LaTeX. You should only put the filename (aka basename) and not the full path in the field; <img src="images/image.jpg"> will not work. Media files should have unique filenames. Note GUIDs Notes have a guid property that uniquely identifies the note. If you import a new note that has the same GUID as an existing note, the new note will overwrite the old one (as long as their models have the same fields). This is an important feature if you want to be able to tweak the design/content of your notes, regenerate your deck, and import the updated version into Anki. Your notes need to have stable GUIDs in order for the new note to replace the existing one. By default, the GUID is a hash of all the field values. This may not be desirable if, for example, you add a new field with additional info that doesn't change the identity of the note. You can create a custom GUID implementation to hash only the fields that identify the note: class MyNote(genanki.Note): @property def guid(self): return genanki.guid_for(self.fields[0], self.fields[1]) sort_field Anki has a value for each Note called the sort_field. Anki uses this value to sort the cards in the Browse interface. Anki also is happier if you avoid having two notes with the same sort_field, although this isn't strictly necessary. By default, the sort_field is the first field, but you can change it by passing sort_field= to Note() or implementing sort_field as a property in a subclass (similar to guid). You can also pass sort_field_index= to Model() to change the sort field. 0 means the first field in the Note, 1 means the second, etc. YAML for Templates (and Fields) You can create your template definitions in the YAML format and pass them as a str to Model(). You can also do this for fields. Using genanki inside an Anki addon genanki supports adding generated notes to the local collection when running inside an Anki 2.1 addon (Anki 2.0 may work but has not been tested). See the .write_to_collection_from_addon() method. CLOZE_MODEL DeprecationWarning Due to a mistake, in genanki versions before 0.13.0, builtin_models.CLOZE_MODEL only had a single field, whereas the real Cloze model that is built into Anki has two fields. If you get a DeprecationWarning when using CLOZE_MODEL, simply add another field (it can be an empty string) when creating your Note, e.g. my_note = genanki.Note( model=genanki.CLOZE_MODEL, fields=['{{c1::Rome}} is the capital of {{c2::Italy}}', '']) FAQ My field data is getting garbled If fields in your notes contain literal <, >, or & characters, you need to HTML-encode them: field data is HTML, not plain text. You can use the html.escape function. For example, you should write fields=['AT&T was originally called', 'Bell Telephone Company'] or fields=[html.escape(f) for f in ['AT&T was originally called', 'Bell Telephone Company']] This applies even if the content is LaTeX; for example, you should write fields=['Piketty calls this the "central contradiction of capitalism".', '[latex]r > g[/latex]'] Publishing to PyPI If your name is Kerrick, you can publish the genanki package to PyPI by running these commands from the root of the genanki repo: rm -rf dist/* python3 setup.py sdist bdist_wheel python3 -m twine upload dist/* Note that this directly uploads to prod PyPI and skips uploading to test PyPI. 全文完 本文由 简悦 SimpRead 优化,用以提升阅读体验 使用了 全新的简悦词法分析引擎 beta,点击查看详细说明 genanki: A Library for Generating Anki Decks Notes Models Generating a Deck/Package Media Files Note GUIDs sort_field YAML for Templates (and Fields) Using genanki inside an Anki addon CLOZE_MODEL DeprecationWarning FAQ My field data is getting garbled Publishing to PyPI
72615369bbc91227adc2b3e16fa9d4d6
{ "intermediate": 0.4550756812095642, "beginner": 0.3774489760398865, "expert": 0.16747534275054932 }
45,811
how to logging in python? write example?
6f257293f121806ae80bc2853640c8e6
{ "intermediate": 0.47261953353881836, "beginner": 0.23960450291633606, "expert": 0.2877759337425232 }
45,812
write esp32 code for run lora ra02 in reciver mode with interupt
7c0d4feefbd581a851d58cb3c3cff2f0
{ "intermediate": 0.3796442151069641, "beginner": 0.21739305555820465, "expert": 0.4029627740383148 }
45,813
elastic search filter on nested field
7435c29abdca46f72be27b88b767fea5
{ "intermediate": 0.20705850422382355, "beginner": 0.15139025449752808, "expert": 0.6415512561798096 }
45,814
elasticsearch filter on parent_id query and add another additional "exists" filter
be8a09f19e03e4a515ccb6c016cf9c74
{ "intermediate": 0.2627153992652893, "beginner": 0.16047032177448273, "expert": 0.5768142342567444 }
45,815
def decorator(func): def wrapper(): func() print(func.a) return wrapper @decorator def test(): test.a = 23 test() Error, there is no such attribute in the function. How do I access a function's local variable in a decoror?
b3893a328e43e33be59b8405e479cb7a
{ "intermediate": 0.25217553973197937, "beginner": 0.6748659610748291, "expert": 0.07295845448970795 }
45,816
перепиши этот код на lua //0AB1: @GET_HANDLING 3 FROM_VEHICLE_MODEL #SULTAN OFFSET 0x1C SIZE 4 _TO: 0@ :GET_HANDLING 0@ *= 4 0@ += 0xA9B0C8 0A8D: 0@ 0@ 4 0 0@ += 0x4A 0A8D: 0@ 0@ 2 0 0@ *= 0xE0 0@ += 0xC2B9DC 005A: 0@ 1@ 0A8D: 3@ 0@ 2@ 0 0AB2: 1 3@
76d22b38369db158e94b12f874afebdc
{ "intermediate": 0.36839213967323303, "beginner": 0.3303925693035126, "expert": 0.3012153208255768 }
45,817
execaction livenessprobe best practices python
80b838a856d83f1eaf3b5fcce6cce2b3
{ "intermediate": 0.3556113839149475, "beginner": 0.3415599465370178, "expert": 0.30282866954803467 }
45,818
I have a table in React. is there a way for me to make all elements inside of tr element to behave similar to align-items: flex-start but using styles specifically for table?
d67e8e864b8b68db03d36ce42041f307
{ "intermediate": 0.6593864560127258, "beginner": 0.17555664479732513, "expert": 0.16505694389343262 }
45,819
I want to do this in processing 4: int a, b, c, d, e, f, g, h, i; int [] letters = {a, b, c, d, e, f, g, h, i}; So I can access the value of each letter by saying what position in the letters array that I want. Is there an way to do this? because when I tried to do that nothing happened.
ee7eb0a74dd100b64ff482de69d5da9d
{ "intermediate": 0.5508039593696594, "beginner": 0.13305871188640594, "expert": 0.31613725423812866 }
45,820
In this javascript for Leaflet.js can you write a function that when called will increase the speed of the marker animation in the 'moveMarker();' and 'moveBackMarker();' functions by 20. - 'var money = 100000; var numberOfCarriages = 1; var speed = 60; const map = L.map("map").setView([54.2231637, -1.9381623], 6); // Add custom zoom control to the map with position set to ‘topright’ const customZoomControl = L.control.zoom({ position: "topright" }).addTo(map); // Remove the default zoom control from the map map.removeControl(map.zoomControl); let clickedPoints = []; let isLineDrawn = false; let marker; // Declare the marker variable let progress = 0; // Function to create circle markers with click functionality function createCircleMarkers(geojson) {  return L.geoJSON(geojson, {   pointToLayer: function (feature, latlng) {    const circleMarker = L.circleMarker(latlng, {     radius: 4,     fillColor: "#ff7800",     color: "#000",     weight: 0.2,     opacity: 1,     fillOpacity: 0.8,    });    // Attach the feature to the circle marker    circleMarker.feature = feature;    circleMarker.on("mouseover", function () {     this.bindPopup(feature.properties.city).openPopup();    });    circleMarker.on("click", function (e) {     if (!isLineDrawn) {      clickedPoints.push(e.target); // Push the circle marker with attached feature      if (clickedPoints.length === 2) {       const firstCityCoords =        clickedPoints[0].feature.geometry.coordinates;       const secondCityCoords =        clickedPoints[1].feature.geometry.coordinates;       const polyline = L.polyline(        clickedPoints.map((p) => p.getLatLng())       ).addTo(map);       const firstCity = clickedPoints[0].feature.properties.city;       const secondCity = clickedPoints[1].feature.properties.city;       clickedPoints = [];       isLineDrawn = true;       // Remove click event listener after a line has been drawn       map.off("click");       // Set the map bounds to show the area with the polyline       map.fitBounds(polyline.getBounds());       money = money - 50000; // Subtract 50000 from money       const moneyDisplay = document.getElementById("moneydisplay");       const moneyString = `£${money}`; // Assuming money is a number       moneyDisplay.textContent = moneyString;       const instructionsElement = document.getElementById("instructions");       // Clear any existing content in the instructions element:       instructionsElement.innerHTML = "";       // Create separate paragraph elements:       const congratulationsParagraph = document.createElement("p");       congratulationsParagraph.textContent = `Congratulations you have built your first train line from ${firstCity} to ${secondCity}!`;       const costsParagraph = document.createElement("p");       costsParagraph.textContent = `Your construction costs were £50,000. You have £50,000 remaining.`;       const buyTrainParagraph = document.createElement("p");       buyTrainParagraph.textContent = "You now need to buy a train.";       const newTrainParagraph = document.createElement("p");       newTrainParagraph.textContent =        "At this time you can only afford to buy the train engine the Sleeping Lion. The Sleeping Lion has a traveling speed of 60 miles per hour. It can pull four carriages. Which means your train will have a capacity of around 120 seated passengers";       const traincost = document.createElement("p");       traincost.textContent = `The Sleeping Lion will cost you £30,000 to purchase. Do you wish to buy the Sleeping Lion?`;       // Append paragraphs to the instructions element:       instructionsElement.appendChild(congratulationsParagraph);       instructionsElement.appendChild(costsParagraph);       instructionsElement.appendChild(buyTrainParagraph);       instructionsElement.appendChild(newTrainParagraph);       instructionsElement.appendChild(traincost);       // Add button element:       const buyButton = document.createElement("button");       buyButton.id = "buybutton";       buyButton.textContent = "Buy Train";       // Append the button element to the instructions element:       instructionsElement.appendChild(buyButton);       // Add click event listener to the Buy Train button       document        .getElementById("buybutton")        .addEventListener("click", function () {         money = money - 30000; // Subtract 30000 from money         const moneyDisplay = document.getElementById("moneydisplay");         const moneyString = `£${money}`;         moneyDisplay.textContent = moneyString;         // Update instructions content after successful purchase         instructionsElement.innerHTML = ""; // Clear previous content         const successMessage = document.createElement("p");         successMessage.textContent = `You now have a train line from ${firstCity} to ${secondCity} and a train! Press the button below to begin operations.`;         instructionsElement.appendChild(successMessage);         // Add button element:         const trainButton = document.createElement("button");         trainButton.id = "trainbutton";         trainButton.textContent = "Start Train";         // Append the button element to the instructions element:         instructionsElement.appendChild(trainButton);         // trainButton click event listener:         trainButton.addEventListener("click", function () {          // Clear any existing content in the instructions element:          instructionsElement.innerHTML = "";          const networkMessage = document.createElement("p");          networkMessage.textContent = `The ${firstCity} to ${secondCity} Rail Company is in operation!`;          const scoreMessage = document.createElement("p");          scoreMessage.textContent = `You will now earn money every time your train arrives at a station (depending on the number of passengers on board). You do not need to worry about scheduling. Your train will now automatically run between your two stations.`;          const updatesMessage = document.createElement("p");          updatesMessage.textContent = `As you earn money you can invest in improving the ${firstCity} to ${secondCity} Rail Company. At the moment your train only has one passenger carriage. Why not increase how much money you make by buying more carriages? Each carriage will cost £20,000.`;          instructionsElement.appendChild(networkMessage);          instructionsElement.appendChild(scoreMessage);          instructionsElement.appendChild(updatesMessage);          // Get a reference to the div element with id "menu"          const menuDiv = document.getElementById("menu");          // Create a new image element          const image = new Image();          // Set the image source URL          image.src =           "https://cdn.glitch.global/df81759e-a135-4f89-a809-685667ca62db/carriage.png?v=1712498925908";          // Optionally set the image alt text (for accessibility)          image.alt = "add carriages";          // Set image size using inline styles          image.style.width = "60px";          image.style.height = "60px";          // Append the image element to the div          menuDiv.appendChild(image);          // Attach a mouseover event listener to the image          image.addEventListener("mouseover", () => {           image.style.cursor = "pointer";          });          // Attach a click event listener to the image          image.addEventListener("click", () => {           console.log("Image clicked!");           // Check if enough money is available           if (money >= 20000) {            // Check if maximum number of carriages reached            if (numberOfCarriages < 4) {             numberOfCarriages++;             money -= 20000; // Subtract 20000 from money             const moneyDisplay =              document.getElementById("moneydisplay");             const moneyString = `£${money}`;             moneyDisplay.textContent = moneyString;             // Update instructions content after successful purchase             instructionsElement.innerHTML = ""; // Clear previous content             const newcarriageMessage = document.createElement("p");             newcarriageMessage.textContent = `Congratualtions you have bought a new passnger carriage. You now have ${numberOfCarriages} passenger carriages.`;             instructionsElement.appendChild(newcarriageMessage);             // Create a new image element for the train             const newTrainImage = new Image();             newTrainImage.src =              "https://cdn.glitch.global/df81759e-a135-4f89-a809-685667ca62db/train.png?v=1712498933227";             newTrainImage.alt = "Train Carriage";             newTrainImage.style.width = "60px"; // Adjust size as needed             newTrainImage.style.height = "60px"; // Adjust size as needed             // Attach a click event listener to the newTrainImage             newTrainImage.addEventListener("click", () => {              console.log("Train icon clicked!");              instructionsElement.innerHTML = ""; // Clear previous content              const improveBoilerButton =               document.createElement("button");              improveBoilerButton.textContent =               "Improve Boiler for £2500"; // Add functionality to the button (optional)              improveBoilerButton.addEventListener("click", () => {  if (money >= 2500) {  // Update speed and calculate new latStep and lngStep values for moveMarker   const speedIncrease = 20;   money -= 2500;   speed += speedIncrease;   const distance = firstPoint.distanceTo(secondPoint);   const steps = ((distance / speed) * 1000) / intervalDuration;   const latStep = (secondPoint.lat - firstPoint.lat) / steps;   const lngStep = (secondPoint.lng - firstPoint.lng) / steps;   // Calculate new latStep and lngStep values for moveBackMarker   const latStepBack = (firstPoint.lat - secondPoint.lat) / steps;   const lngStepBack = (firstPoint.lng - secondPoint.lng) / steps;   // Update money display immediately   const moneyDisplay = document.getElementById('moneydisplay');   const moneyString = `£${money}`;   moneyDisplay.textContent = moneyString;   // Restart both animations with the updated speed   moveMarker(); // Restart the forward animation   moveBackMarker(); // Restart the backward animation  } else {   console.log("Insufficient funds! You need £2500 to improve the boiler.");    instructionsElement.innerHTML = ""; // Clear previous content            // ... insufficient funds logic ...            const fundsMessage = document.createElement("p");            fundsMessage.textContent = `Insufficient funds!`;            instructionsElement.appendChild(fundsMessage);              } });              instructionsElement.appendChild(improveBoilerButton);             });             newTrainImage.addEventListener("mouseover", () => {              newTrainImage.style.cursor = "pointer";             });             // Append the new train image to the menu element             const menuDiv = document.getElementById("menu");             menuDiv.appendChild(newTrainImage);            } else {             console.log(              "Maximum number of carriages reached! You can't buy more."             );             instructionsElement.innerHTML = ""; // Clear previous content             const maxCarriageMessage = document.createElement("p");             maxCarriageMessage.textContent =              "You already have the maximum number of carriages (4).";             instructionsElement.appendChild(maxCarriageMessage);            }           } else {            console.log(             "Insufficient funds! You need £20,000 to buy a carriage."              // ... insufficient funds logic ...            );            instructionsElement.innerHTML = ""; // Clear previous content            // ... insufficient funds logic ...            const nomoneyMessage = document.createElement("p");            nomoneyMessage.textContent = `Insufficient funds! You need £20,000 to buy a carriage.`;            instructionsElement.appendChild(nomoneyMessage);           }          });          const firstPoint = L.latLng(           firstCityCoords[1],           firstCityCoords[0]          );          const secondPoint = L.latLng(           secondCityCoords[1],           secondCityCoords[0]          );          const intervalDuration = 10; // milliseconds per frame          const distance = firstPoint.distanceTo(secondPoint);          const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour          const latStep = (secondPoint.lat - firstPoint.lat) / steps;          const lngStep = (secondPoint.lng - firstPoint.lng) / steps;          // Create the marker and set its initial position          marker = L.marker(firstPoint).addTo(map);          const moveMarker = () => {           if (progress < steps) {            const newLat = firstPoint.lat + latStep * progress;            const newLng = firstPoint.lng + lngStep * progress;            const newLatLng = L.latLng(newLat, newLng);            marker.setLatLng(newLatLng); // Update the marker's position            progress++;            setTimeout(moveMarker, intervalDuration);           } else {            // Marker reaches the second point, update money            money +=             Math.floor(Math.random() * (2000 - 1000 + 1)) +             1000 * numberOfCarriages;            const moneyDisplay =             document.getElementById("moneydisplay");            const moneyString = `£${money}`;            moneyDisplay.textContent = moneyString;            // Wait two seconds before animating back and call moveBackMarker recursively            setTimeout(() => {             moveBackMarker();            }, 2000); // Wait for 2 seconds (2000 milliseconds)           }          };          const moveBackMarker = () => {           // Corrected calculation for animating back from second point to first           if (progress > 0) {            const newLat =             secondPoint.lat - latStep * (steps - progress);            const newLng =             secondPoint.lng - lngStep * (steps - progress);            const newLatLng = L.latLng(newLat, newLng);            marker.setLatLng(newLatLng); // Update the marker's position            progress--;            setTimeout(moveBackMarker, intervalDuration);           } else {            console.log("Reached starting point again.");            // Add random number to money and update display            money +=             Math.floor(Math.random() * (2000 - 1000 + 1)) +             1000 * numberOfCarriages;            const moneyDisplay =             document.getElementById("moneydisplay");            const moneyString = `£${money}`;            moneyDisplay.textContent = moneyString;            // Reset progress for next round trip            progress = 0;            // Recursively call moveMarker to start next animation cycle            moveMarker();           }          };          moveMarker(); // Start the animation         });        });      }     }    });    return circleMarker;   },  }); } fetch("gb.geojson")  .then((response) => response.json())  .then((geojson) => {   L.geoJSON(geojson, {    fillColor: "none", // Style for polygon (empty fill)    weight: 1,    color: "#000",    opacity: 1,    fillOpacity: 0,   }).addTo(map);  })  .catch((error) => {   console.error("Error loading GeoJSON:", error);  }); fetch("cities.geojson")  .then((response) => response.json())  .then((geojson) => {   createCircleMarkers(geojson).addTo(map);  })  .catch((error) => {   console.error("Error loading GeoJSON:", error);  }); '
0462d20480e1ec82ee9bf37b7605f375
{ "intermediate": 0.32454347610473633, "beginner": 0.27181825041770935, "expert": 0.40363824367523193 }
45,821
#Import necessary modules from direct.showbase.ShowBase import ShowBase from direct.actor.Actor import Actor from panda3d.core import AmbientLight, DirectionalLight, LightAttrib # Define the game class class CharacterTestGame(ShowBase): def __init__(self): # Initialize the ShowBase class super().__init__() # Load the character model model_path = "C:\\Users\\Vusum\\Wii - Naruto Shippuden Clash of Ninja Revolution 3 - Sasuke.fbx" self.character = Actor(model_path) # Set the initial position and orientation of the character self.character.reparentTo(self.render) self.character.setScale(0.5) # Adjust the scale as needed self.character.setPos(0, 0, 0) # Set the initial position # Set up lighting ambient_light = AmbientLight("ambient_light") ambient_light.setColor((0.2, 0.2, 0.2, 1)) directional_light = DirectionalLight("directional_light") directional_light.setDirection((-5, -5, -5)) render.attachNewNode(directional_light.upcastToPandaNode()) render.attachNewNode(ambient_light.upcastToPandaNode()) render.setLight(render.attachNewNode(directional_light.upcastToPandaNode())) render.setLight(render.attachNewNode(ambient_light.upcastToPandaNode())) # Set up the camera self.disableMouse() self.camera.setPos(0, -20, 5) self.camera.lookAt(self.character) # Set up keyboard controls self.accept("w", self.move_forward) self.accept("s", self.move_backward) self.accept("a", self.move_left) self.accept("d", self.move_right) def move_forward(self): self.character.setY(self.character, 0.5) def move_backward(self): self.character.setY(self.character, -0.5) def move_left(self): self.character.setX(self.character, -0.5) def move_right(self): self.character.setX(self.character, 0.5) # Run the game game = CharacterTestGame() game.run() i get this error C:\Users\Vusum>python c6.py Known pipe types: wglGraphicsPipe (all display modules loaded.) :assimp(error): Unable to open file "/c/Users/Vusum/C:\Users\Vusum\Wii - Naruto Shippuden Clash of Ninja Revolution 3 - Sasuke.fbx". :assimp(error): Unable to open file "/d/Panda3D-1.10.14-x64/etc/../C:\Users\Vusum\Wii - Naruto Shippuden Clash of Ninja Revolution 3 - Sasuke.fbx". :assimp(error): Unable to open file "/d/Panda3D-1.10.14-x64/etc/../models/C:\Users\Vusum\Wii - Naruto Shippuden Clash of Ninja Revolution 3 - Sasuke.fbx". :loader(error): Couldn't load file C:\Users\Vusum\Wii - Naruto Shippuden Clash of Ninja Revolution 3 - Sasuke.fbx: not found on model path (currently: "/c/Users/Vusum;/d/Panda3D-1.10.14-x64/etc/..;/d/Panda3D-1.10.14-x64/etc/../models") Traceback (most recent call last): File "C:\Users\Vusum\c6.py", line 55, in <module> game = CharacterTestGame() File "C:\Users\Vusum\c6.py", line 14, in __init__ self.character = Actor(model_path) File "D:\Panda3D-1.10.14-x64\direct\actor\Actor.py", line 293, in __init__ self.loadModel(models, copy = copy, okMissing = okMissing) File "D:\Panda3D-1.10.14-x64\direct\actor\Actor.py", line 1916, in loadModel raise IOError("Could not load Actor model %s" % (modelPath)) OSError: Could not load Actor model C:\Users\Vusum\Wii - Naruto Shippuden Clash of Ninja Revolution 3 - Sasuke.fbx
d01074c6ecce08d13b6e1eb9c1003805
{ "intermediate": 0.3437802493572235, "beginner": 0.4736318588256836, "expert": 0.1825878918170929 }
45,822
in C# Winforms, I Added listView1 in MainForm.cs, how can I use listView1 from another form for example AddForm.cs?
3894e123c0a5edf276df731d08ee3f20
{ "intermediate": 0.6472622752189636, "beginner": 0.2109624147415161, "expert": 0.14177529513835907 }
45,823
i have a character and i want to test them out before making game, create python game app that allows me to do that. character file path = "C:\Users\Vusum\Wii - Naruto Shippuden Clash of Ninja Revolution 3 - Sasuke.fbx" i downloaded panda3d
47c74c54fbf68c9eff5b33543d18928a
{ "intermediate": 0.4519087076187134, "beginner": 0.22372430562973022, "expert": 0.3243670165538788 }
45,824
0AB1: @GET_HANDLING 3 FROM_VEHICLE_MODEL #SULTAN OFFSET 0x1C SIZE 4 _TO: 0@ Код: //0AB1: @GET_HANDLING 3 FROM_VEHICLE_MODEL #SULTAN OFFSET 0x1C SIZE 4 _TO: 0@ :GET_HANDLING 0@ *= 4 0@ += 0xA9B0C8 0A8D: 0@ 0@ 4 0 0@ += 0x4A 0A8D: 0@ 0@ 2 0 0@ *= 0xE0 0@ += 0xC2B9DC 005A: 0@ 1@ 0A8D: 3@ 0@ 2@ 0 0AB2: 1 3@ 0AB1: @SET_HANDLING 4 FROM_VEHICLE_MODEL #SULTAN OFFSET 0x1C SIZE 4 INTO: -1.0 Код: //0AB1: @SET_HANDLING 4 FROM_VEHICLE_MODEL #SULTAN OFFSET 0x1C SIZE 4 INTO: -1.0 :SET_HANDLING 0@ *= 4 0@ += 0xA9B0C8 0A8D: 0@ 0@ 4 0 0@ += 0x4A 0A8D: 0@ 0@ 2 0 0@ *= 0xE0 0@ += 0xC2B9DC 005A: 0@ 1@ 0A8C: 0@ 2@ 3@ 0 0AB2: 0 Here is a list of all the offsets: Код: //------------------------------- //List of Handling Offsets: { 0x0 = [dword] Index/Identifier 0x4 = fMass 0x8 = 1.0 / fMass 0xC = fTurnMass 0x10 = fDragMult 0x14 = CentreOfMass.x 0x18 = CentreOfMass.y 0x1C = CentreOfMass.z 0x20 = [byte] nPercentSubmerged 0x24 = fMass * 8.0000001E-1 / nPercentSubmerged 0x28 = fTractionMultiplier 0x74 = [byte] TransmissionData.nDriveType 0x75 = [byte] TransmissionData.nEngineType 0x76 = [byte] TransmissionData.nNumberOfGears 0x7C = TransmissionData.fEngineAcceleration (Multiplied by 3.9999999E-4) 0x80 = TransmissionData.fEngineInertia 0x84 = TransmissionData.fMaxVelocity (Multiplied by 5.5555599E-3) 0x94 = fBrakeDeceleration (Multiplied by 3.9999999E-4) 0x98 = fBrakeBias 0x9C = [byte] bABS 0xA0 = fSteeringLock 0xA4 = fTractionLoss 0xA8 = fTractionBias 0xAC = fSuspensionForceLevel 0xB0 = fSuspensionDampingLevel 0xB4 = fSuspensionHighSpdComDamp 0xB8 = Suspension upper limit 0xBC = Suspension lower limit 0xC0 = Suspension bias between front and rear 0xC4 = Suspension anti-dive multiplier 0xC8 = fCollisionDamageMultiplier (multiplier not yet found) 0xCC = [hex] modelFlags 0xD0 = [hex] handlingFlags 0xD4 = fSeatOffsetDistance 0xD8 = [dword] nMonetaryValue 0xDC = [byte] Front lights 0xDD = [byte] Rear lights 0xDE = [byte] Vehicle anim group } Example: - Making the SULTAN take no damage when colliding with somehting: Код: {$CLEO .cs} 0000: 0AB1: @SET_HANDLING 4 FROM_VEHICLE_MODEL #SULTAN OFFSET 0xC8 SIZE 4 INTO: 0.0 //fCollisionDamageMultiplier 004E: END_THIS_THREADкак это работает? дай мне понять как написать аналог на Lua
63ca7f3072511232b0c6e808638add86
{ "intermediate": 0.32521867752075195, "beginner": 0.4350603520870209, "expert": 0.23972097039222717 }
45,825
In Emacs org mode, how can I remove a tag from all headings?
75a9ee5b2d4f9b5322ead18bb5e7d106
{ "intermediate": 0.3517582416534424, "beginner": 0.27647078037261963, "expert": 0.371770977973938 }
45,826
Chatbot Type an input and press Enter Status code from OpenAI server Parameters ▼
8d071e4954dd1b63dd3a77eeb5c78c43
{ "intermediate": 0.22794559597969055, "beginner": 0.26289820671081543, "expert": 0.5091561079025269 }
45,827
In this javascript for leaflet.js why is the click event for the improveBoilerButton increasing the speed of the moverMarker(speed) and moveBackMarker(speed) marker animations. 'var money = 100000; var numberOfCarriages = 1; var speed = 60; const map = L.map("map").setView([54.2231637, -1.9381623], 6); // Add custom zoom control to the map with position set to ‘topright’ const customZoomControl = L.control.zoom({ position: "topright" }).addTo(map); // Remove the default zoom control from the map map.removeControl(map.zoomControl); let clickedPoints = []; let isLineDrawn = false; let marker; // Declare the marker variable let progress = 0; // Function to create circle markers with click functionality function createCircleMarkers(geojson) { return L.geoJSON(geojson, { pointToLayer: function (feature, latlng) { const circleMarker = L.circleMarker(latlng, { radius: 4, fillColor: "#ff7800", color: "#000", weight: 0.2, opacity: 1, fillOpacity: 0.8, }); // Attach the feature to the circle marker circleMarker.feature = feature; circleMarker.on("mouseover", function () { this.bindPopup(feature.properties.city).openPopup(); }); circleMarker.on("click", function (e) { if (!isLineDrawn) { clickedPoints.push(e.target); // Push the circle marker with attached feature if (clickedPoints.length === 2) { const firstCityCoords = clickedPoints[0].feature.geometry.coordinates; const secondCityCoords = clickedPoints[1].feature.geometry.coordinates; const polyline = L.polyline( clickedPoints.map((p) => p.getLatLng()) ).addTo(map); const firstCity = clickedPoints[0].feature.properties.city; const secondCity = clickedPoints[1].feature.properties.city; clickedPoints = []; isLineDrawn = true; // Remove click event listener after a line has been drawn map.off("click"); // Set the map bounds to show the area with the polyline map.fitBounds(polyline.getBounds()); money = money - 50000; // Subtract 50000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; // Assuming money is a number moneyDisplay.textContent = moneyString; const instructionsElement = document.getElementById("instructions"); // Clear any existing content in the instructions element: instructionsElement.innerHTML = ""; // Create separate paragraph elements: const congratulationsParagraph = document.createElement("p"); congratulationsParagraph.textContent = `Congratulations you have built your first train line from ${firstCity} to ${secondCity}!`; const costsParagraph = document.createElement("p"); costsParagraph.textContent = `Your construction costs were £50,000. You have £50,000 remaining.`; const buyTrainParagraph = document.createElement("p"); buyTrainParagraph.textContent = "You now need to buy a train."; const newTrainParagraph = document.createElement("p"); newTrainParagraph.textContent = "At this time you can only afford to buy the train engine the Sleeping Lion. The Sleeping Lion has a traveling speed of 60 miles per hour. It can pull four carriages. Which means your train will have a capacity of around 120 seated passengers"; const traincost = document.createElement("p"); traincost.textContent = `The Sleeping Lion will cost you £30,000 to purchase. Do you wish to buy the Sleeping Lion?`; // Append paragraphs to the instructions element: instructionsElement.appendChild(congratulationsParagraph); instructionsElement.appendChild(costsParagraph); instructionsElement.appendChild(buyTrainParagraph); instructionsElement.appendChild(newTrainParagraph); instructionsElement.appendChild(traincost); // Add button element: const buyButton = document.createElement("button"); buyButton.id = "buybutton"; buyButton.textContent = "Buy Train"; // Append the button element to the instructions element: instructionsElement.appendChild(buyButton); // Add click event listener to the Buy Train button document .getElementById("buybutton") .addEventListener("click", function () { money = money - 30000; // Subtract 30000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Update instructions content after successful purchase instructionsElement.innerHTML = ""; // Clear previous content const successMessage = document.createElement("p"); successMessage.textContent = `You now have a train line from ${firstCity} to ${secondCity} and a train! Press the button below to begin operations.`; instructionsElement.appendChild(successMessage); // Add button element: const trainButton = document.createElement("button"); trainButton.id = "trainbutton"; trainButton.textContent = "Start Train"; // Append the button element to the instructions element: instructionsElement.appendChild(trainButton); // trainButton click event listener: trainButton.addEventListener("click", function () { // Clear any existing content in the instructions element: instructionsElement.innerHTML = ""; const networkMessage = document.createElement("p"); networkMessage.textContent = `The ${firstCity} to ${secondCity} Rail Company is in operation!`; const scoreMessage = document.createElement("p"); scoreMessage.textContent = `You will now earn money every time your train arrives at a station (depending on the number of passengers on board). You do not need to worry about scheduling. Your train will now automatically run between your two stations.`; const updatesMessage = document.createElement("p"); updatesMessage.textContent = `As you earn money you can invest in improving the ${firstCity} to ${secondCity} Rail Company. At the moment your train only has one passenger carriage. Why not increase how much money you make by buying more carriages? Each carriage will cost £20,000.`; instructionsElement.appendChild(networkMessage); instructionsElement.appendChild(scoreMessage); instructionsElement.appendChild(updatesMessage); // Get a reference to the div element with id "menu" const menuDiv = document.getElementById("menu"); // Create a new image element const image = new Image(); // Set the image source URL image.src = "https://cdn.glitch.global/df81759e-a135-4f89-a809-685667ca62db/carriage.png?v=1712498925908"; // Optionally set the image alt text (for accessibility) image.alt = "add carriages"; // Set image size using inline styles image.style.width = "60px"; image.style.height = "60px"; // Append the image element to the div menuDiv.appendChild(image); // Attach a mouseover event listener to the image image.addEventListener("mouseover", () => { image.style.cursor = "pointer"; }); // Attach a click event listener to the image image.addEventListener("click", () => { console.log("Image clicked!"); // Check if enough money is available if (money >= 20000) { // Check if maximum number of carriages reached if (numberOfCarriages < 4) { numberOfCarriages++; money -= 20000; // Subtract 20000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Update instructions content after successful purchase instructionsElement.innerHTML = ""; // Clear previous content const newcarriageMessage = document.createElement("p"); newcarriageMessage.textContent = `Congratualtions you have bought a new passnger carriage. You now have ${numberOfCarriages} passenger carriages.`; instructionsElement.appendChild(newcarriageMessage); // Create a new image element for the train const newTrainImage = new Image(); newTrainImage.src = "https://cdn.glitch.global/df81759e-a135-4f89-a809-685667ca62db/train.png?v=1712498933227"; newTrainImage.alt = "Train Carriage"; newTrainImage.style.width = "60px"; // Adjust size as needed newTrainImage.style.height = "60px"; // Adjust size as needed // Attach a click event listener to the newTrainImage newTrainImage.addEventListener("click", () => { console.log("Train icon clicked!"); instructionsElement.innerHTML = ""; // Clear previous content const improveBoilerButton = document.createElement("button"); improveBoilerButton.textContent = "Improve Boiler for £2500"; // Add functionality to the button (optional) improveBoilerButton.addEventListener("click", () => { if (money >= 2500) { //increase speed increaseSpeed(); // Restart both animations with the updated speed moveMarker(speed); // Restart the forward animation moveBackMarker(speed); // Restart the backward animation money = money - 2500; // Subtract 30000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; } else { console.log("Insufficient funds! You need £2500 to improve the boiler."); instructionsElement.innerHTML = ""; // Clear previous content // ... insufficient funds logic ... const fundsMessage = document.createElement("p"); fundsMessage.textContent = `Insufficient funds!`; instructionsElement.appendChild(fundsMessage); } }); instructionsElement.appendChild(improveBoilerButton); }); newTrainImage.addEventListener("mouseover", () => { newTrainImage.style.cursor = "pointer"; }); // Append the new train image to the menu element const menuDiv = document.getElementById("menu"); menuDiv.appendChild(newTrainImage); } else { console.log( "Maximum number of carriages reached! You can't buy more." ); instructionsElement.innerHTML = ""; // Clear previous content const maxCarriageMessage = document.createElement("p"); maxCarriageMessage.textContent = "You already have the maximum number of carriages (4)."; instructionsElement.appendChild(maxCarriageMessage); } } else { console.log( "Insufficient funds! You need £20,000 to buy a carriage." // ... insufficient funds logic ... ); instructionsElement.innerHTML = ""; // Clear previous content // ... insufficient funds logic ... const nomoneyMessage = document.createElement("p"); nomoneyMessage.textContent = `Insufficient funds! You need £20,000 to buy a carriage.`; instructionsElement.appendChild(nomoneyMessage); } }); const firstPoint = L.latLng( firstCityCoords[1], firstCityCoords[0] ); const secondPoint = L.latLng( secondCityCoords[1], secondCityCoords[0] ); const intervalDuration = 10; // milliseconds per frame const distance = firstPoint.distanceTo(secondPoint); const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour const latStep = (secondPoint.lat - firstPoint.lat) / steps; const lngStep = (secondPoint.lng - firstPoint.lng) / steps; // Create the marker and set its initial position marker = L.marker(firstPoint).addTo(map); const increaseSpeed = () => { const speedIncrease = 20; speed += speedIncrease; }; const moveMarker = (speed) => { if (progress < steps) { const newLat = firstPoint.lat + latStep * progress; const newLng = firstPoint.lng + lngStep * progress; const newLatLng = L.latLng(newLat, newLng); marker.setLatLng(newLatLng); // Update the marker's position progress++; setTimeout(moveMarker, intervalDuration); } else { // Marker reaches the second point, update money money += Math.floor(Math.random() * (2000 - 1000 + 1)) + 1000 * numberOfCarriages; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Wait two seconds before animating back and call moveBackMarker recursively setTimeout(() => { moveBackMarker(speed); }, 2000); // Wait for 2 seconds (2000 milliseconds) } }; const moveBackMarker = (speed) => { // Corrected calculation for animating back from second point to first if (progress > 0) { const newLat = secondPoint.lat - latStep * (steps - progress); const newLng = secondPoint.lng - lngStep * (steps - progress); const newLatLng = L.latLng(newLat, newLng); marker.setLatLng(newLatLng); // Update the marker's position progress--; setTimeout(moveBackMarker, intervalDuration); } else { console.log("Reached starting point again."); // Add random number to money and update display money += Math.floor(Math.random() * (2000 - 1000 + 1)) + 1000 * numberOfCarriages; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Reset progress for next round trip progress = 0; // Recursively call moveMarker to start next animation cycle moveMarker(speed); } }; moveMarker(speed); // Start the animation }); }); } } }); return circleMarker; }, }); } fetch("gb.geojson") .then((response) => response.json()) .then((geojson) => { L.geoJSON(geojson, { fillColor: "none", // Style for polygon (empty fill) weight: 1, color: "#000", opacity: 1, fillOpacity: 0, }).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); }); fetch("cities.geojson") .then((response) => response.json()) .then((geojson) => { createCircleMarkers(geojson).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); }); '
56d9b5cac19beef68442cf2f8d3ccef4
{ "intermediate": 0.40950825810432434, "beginner": 0.4313526749610901, "expert": 0.15913908183574677 }
45,828
In this javascript for leaflet.js why isn't the click event for the improveBoilerButton increasing the speed of the moverMarker(speed) and moveBackMarker(speed) marker animations. - 'var money = 100000; var numberOfCarriages = 1; var speed = 60; const map = L.map("map").setView([54.2231637, -1.9381623], 6); // Add custom zoom control to the map with position set to ‘topright’ const customZoomControl = L.control.zoom({ position: "topright" }).addTo(map); // Remove the default zoom control from the map map.removeControl(map.zoomControl); let clickedPoints = []; let isLineDrawn = false; let marker; // Declare the marker variable let progress = 0; // Function to create circle markers with click functionality function createCircleMarkers(geojson) { return L.geoJSON(geojson, { pointToLayer: function (feature, latlng) { const circleMarker = L.circleMarker(latlng, { radius: 4, fillColor: "#ff7800", color: "#000", weight: 0.2, opacity: 1, fillOpacity: 0.8, }); // Attach the feature to the circle marker circleMarker.feature = feature; circleMarker.on("mouseover", function () { this.bindPopup(feature.properties.city).openPopup(); }); circleMarker.on("click", function (e) { if (!isLineDrawn) { clickedPoints.push(e.target); // Push the circle marker with attached feature if (clickedPoints.length === 2) { const firstCityCoords = clickedPoints[0].feature.geometry.coordinates; const secondCityCoords = clickedPoints[1].feature.geometry.coordinates; const polyline = L.polyline( clickedPoints.map((p) => p.getLatLng()) ).addTo(map); const firstCity = clickedPoints[0].feature.properties.city; const secondCity = clickedPoints[1].feature.properties.city; clickedPoints = []; isLineDrawn = true; // Remove click event listener after a line has been drawn map.off("click"); // Set the map bounds to show the area with the polyline map.fitBounds(polyline.getBounds()); money = money - 50000; // Subtract 50000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; // Assuming money is a number moneyDisplay.textContent = moneyString; const instructionsElement = document.getElementById("instructions"); // Clear any existing content in the instructions element: instructionsElement.innerHTML = ""; // Create separate paragraph elements: const congratulationsParagraph = document.createElement("p"); congratulationsParagraph.textContent = `Congratulations you have built your first train line from ${firstCity} to ${secondCity}!`; const costsParagraph = document.createElement("p"); costsParagraph.textContent = `Your construction costs were £50,000. You have £50,000 remaining.`; const buyTrainParagraph = document.createElement("p"); buyTrainParagraph.textContent = "You now need to buy a train."; const newTrainParagraph = document.createElement("p"); newTrainParagraph.textContent = "At this time you can only afford to buy the train engine the Sleeping Lion. The Sleeping Lion has a traveling speed of 60 miles per hour. It can pull four carriages. Which means your train will have a capacity of around 120 seated passengers"; const traincost = document.createElement("p"); traincost.textContent = `The Sleeping Lion will cost you £30,000 to purchase. Do you wish to buy the Sleeping Lion?`; // Append paragraphs to the instructions element: instructionsElement.appendChild(congratulationsParagraph); instructionsElement.appendChild(costsParagraph); instructionsElement.appendChild(buyTrainParagraph); instructionsElement.appendChild(newTrainParagraph); instructionsElement.appendChild(traincost); // Add button element: const buyButton = document.createElement("button"); buyButton.id = "buybutton"; buyButton.textContent = "Buy Train"; // Append the button element to the instructions element: instructionsElement.appendChild(buyButton); // Add click event listener to the Buy Train button document .getElementById("buybutton") .addEventListener("click", function () { money = money - 30000; // Subtract 30000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Update instructions content after successful purchase instructionsElement.innerHTML = ""; // Clear previous content const successMessage = document.createElement("p"); successMessage.textContent = `You now have a train line from ${firstCity} to ${secondCity} and a train! Press the button below to begin operations.`; instructionsElement.appendChild(successMessage); // Add button element: const trainButton = document.createElement("button"); trainButton.id = "trainbutton"; trainButton.textContent = "Start Train"; // Append the button element to the instructions element: instructionsElement.appendChild(trainButton); // trainButton click event listener: trainButton.addEventListener("click", function () { // Clear any existing content in the instructions element: instructionsElement.innerHTML = ""; const networkMessage = document.createElement("p"); networkMessage.textContent = `The ${firstCity} to ${secondCity} Rail Company is in operation!`; const scoreMessage = document.createElement("p"); scoreMessage.textContent = `You will now earn money every time your train arrives at a station (depending on the number of passengers on board). You do not need to worry about scheduling. Your train will now automatically run between your two stations.`; const updatesMessage = document.createElement("p"); updatesMessage.textContent = `As you earn money you can invest in improving the ${firstCity} to ${secondCity} Rail Company. At the moment your train only has one passenger carriage. Why not increase how much money you make by buying more carriages? Each carriage will cost £20,000.`; instructionsElement.appendChild(networkMessage); instructionsElement.appendChild(scoreMessage); instructionsElement.appendChild(updatesMessage); // Get a reference to the div element with id "menu" const menuDiv = document.getElementById("menu"); // Create a new image element const image = new Image(); // Set the image source URL image.src = "https://cdn.glitch.global/df81759e-a135-4f89-a809-685667ca62db/carriage.png?v=1712498925908"; // Optionally set the image alt text (for accessibility) image.alt = "add carriages"; // Set image size using inline styles image.style.width = "60px"; image.style.height = "60px"; // Append the image element to the div menuDiv.appendChild(image); // Attach a mouseover event listener to the image image.addEventListener("mouseover", () => { image.style.cursor = "pointer"; }); // Attach a click event listener to the image image.addEventListener("click", () => { console.log("Image clicked!"); // Check if enough money is available if (money >= 20000) { // Check if maximum number of carriages reached if (numberOfCarriages < 4) { numberOfCarriages++; money -= 20000; // Subtract 20000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Update instructions content after successful purchase instructionsElement.innerHTML = ""; // Clear previous content const newcarriageMessage = document.createElement("p"); newcarriageMessage.textContent = `Congratualtions you have bought a new passnger carriage. You now have ${numberOfCarriages} passenger carriages.`; instructionsElement.appendChild(newcarriageMessage); // Create a new image element for the train const newTrainImage = new Image(); newTrainImage.src = "https://cdn.glitch.global/df81759e-a135-4f89-a809-685667ca62db/train.png?v=1712498933227"; newTrainImage.alt = "Train Carriage"; newTrainImage.style.width = "60px"; // Adjust size as needed newTrainImage.style.height = "60px"; // Adjust size as needed // Attach a click event listener to the newTrainImage newTrainImage.addEventListener("click", () => { console.log("Train icon clicked!"); instructionsElement.innerHTML = ""; // Clear previous content const improveBoilerButton = document.createElement("button"); improveBoilerButton.textContent = "Improve Boiler for £2500"; // Add functionality to the button (optional) improveBoilerButton.addEventListener("click", () => { if (money >= 2500) { //increase speed increaseSpeed(); // Restart both animations with the updated speed moveMarker(speed); // Restart the forward animation moveBackMarker(speed); // Restart the backward animation money = money - 2500; // Subtract 30000 from money const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; } else { console.log("Insufficient funds! You need £2500 to improve the boiler."); instructionsElement.innerHTML = ""; // Clear previous content // ... insufficient funds logic ... const fundsMessage = document.createElement("p"); fundsMessage.textContent = `Insufficient funds!`; instructionsElement.appendChild(fundsMessage); } }); instructionsElement.appendChild(improveBoilerButton); }); newTrainImage.addEventListener("mouseover", () => { newTrainImage.style.cursor = "pointer"; }); // Append the new train image to the menu element const menuDiv = document.getElementById("menu"); menuDiv.appendChild(newTrainImage); } else { console.log( "Maximum number of carriages reached! You can't buy more." ); instructionsElement.innerHTML = ""; // Clear previous content const maxCarriageMessage = document.createElement("p"); maxCarriageMessage.textContent = "You already have the maximum number of carriages (4)."; instructionsElement.appendChild(maxCarriageMessage); } } else { console.log( "Insufficient funds! You need £20,000 to buy a carriage." // ... insufficient funds logic ... ); instructionsElement.innerHTML = ""; // Clear previous content // ... insufficient funds logic ... const nomoneyMessage = document.createElement("p"); nomoneyMessage.textContent = `Insufficient funds! You need £20,000 to buy a carriage.`; instructionsElement.appendChild(nomoneyMessage); } }); const firstPoint = L.latLng( firstCityCoords[1], firstCityCoords[0] ); const secondPoint = L.latLng( secondCityCoords[1], secondCityCoords[0] ); const intervalDuration = 10; // milliseconds per frame const distance = firstPoint.distanceTo(secondPoint); const steps = ((distance / speed) * 1000) / intervalDuration; // Assuming speed of 35 miles per hour const latStep = (secondPoint.lat - firstPoint.lat) / steps; const lngStep = (secondPoint.lng - firstPoint.lng) / steps; // Create the marker and set its initial position marker = L.marker(firstPoint).addTo(map); const increaseSpeed = () => { const speedIncrease = 20; speed += speedIncrease; }; const moveMarker = (speed) => { if (progress < steps) { const newLat = firstPoint.lat + latStep * progress; const newLng = firstPoint.lng + lngStep * progress; const newLatLng = L.latLng(newLat, newLng); marker.setLatLng(newLatLng); // Update the marker's position progress++; setTimeout(moveMarker, intervalDuration); } else { // Marker reaches the second point, update money money += Math.floor(Math.random() * (2000 - 1000 + 1)) + 1000 * numberOfCarriages; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Wait two seconds before animating back and call moveBackMarker recursively setTimeout(() => { moveBackMarker(speed); }, 2000); // Wait for 2 seconds (2000 milliseconds) } }; const moveBackMarker = (speed) => { // Corrected calculation for animating back from second point to first if (progress > 0) { const newLat = secondPoint.lat - latStep * (steps - progress); const newLng = secondPoint.lng - lngStep * (steps - progress); const newLatLng = L.latLng(newLat, newLng); marker.setLatLng(newLatLng); // Update the marker's position progress--; setTimeout(moveBackMarker, intervalDuration); } else { console.log("Reached starting point again."); // Add random number to money and update display money += Math.floor(Math.random() * (2000 - 1000 + 1)) + 1000 * numberOfCarriages; const moneyDisplay = document.getElementById("moneydisplay"); const moneyString = `£${money}`; moneyDisplay.textContent = moneyString; // Reset progress for next round trip progress = 0; // Recursively call moveMarker to start next animation cycle moveMarker(speed); } }; moveMarker(speed); // Start the animation }); }); } } }); return circleMarker; }, }); } fetch("gb.geojson") .then((response) => response.json()) .then((geojson) => { L.geoJSON(geojson, { fillColor: "none", // Style for polygon (empty fill) weight: 1, color: "#000", opacity: 1, fillOpacity: 0, }).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); }); fetch("cities.geojson") .then((response) => response.json()) .then((geojson) => { createCircleMarkers(geojson).addTo(map); }) .catch((error) => { console.error("Error loading GeoJSON:", error); }); '
22c6a43ee617a1c1c48b681db1eef48e
{ "intermediate": 0.41418424248695374, "beginner": 0.42487096786499023, "expert": 0.1609448343515396 }
45,829
library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity MatrixCore is generic ( MATRIX_SIZE : integer := 5 ); port ( clk : in std_logic; rst : in std_logic; input_matrix : in std_logic_vector((MATRIX_SIZE * MATRIX_SIZE) - 1 downto 0); output_matrix : out std_logic_vector((MATRIX_SIZE * MATRIX_SIZE) - 1 downto 0) ); end entity MatrixCore; architecture Behavioral of MatrixCore is type matrix_array is array(0 to MATRIX_SIZE-1, 0 to MATRIX_SIZE-1) of real; signal random_matrix : matrix_array; signal processing_done : std_logic := '0'; signal result_matrix : matrix_array := (others => '0'); begin process(clk, rst) begin if rst = '1' then processing_done <= '0'; elsif rising_edge(clk) then if processing_done = '0' then -- Generate random matrix (replace with your actual matrix loading logic) for i in 0 to MATRIX_SIZE-1 loop for j in 0 to MATRIX_SIZE-1 loop random_matrix(i, j) <= real(to_integer(unsigned(input_matrix(i*MATRIX_SIZE + j*32 + 31 downto i*MATRIX_SIZE + j*32)))); end loop; end loop; -- Matrix multiplication for i in 0 to MATRIX_SIZE-1 loop for j in 0 to MATRIX_SIZE-1 loop -- Initialize the result to 0 for each element result_matrix(i, j) <= 0.0; -- Loop through each element in the second matrix (k) for k in 0 to MATRIX_SIZE-1 loop -- Perform element-wise multiplication and accumulate result_matrix(i, j) <= result_matrix(i, j) + (random_matrix(i, k) * random_matrix(k, j)); end loop; end loop; end loop; processing_done <= '1'; end if; end if; end process; output_matrix <= std_logic_vector(to_unsigned(result_matrix, (MATRIX_SIZE * MATRIX_SIZE) - 1 downto 0)); end architecture Behavioral; entity TransformerEngine is generic ( NUM_CORES : integer := 4 ); port ( clk : in std_logic; rst : in std_logic; input_matrix : in std_logic_vector((MATRIX_SIZE * MATRIX_SIZE) - 1 downto 0); output_matrices : out std_logic_vector((NUM_CORES * MATRIX_SIZE * MATRIX_SIZE) - 1 downto 0) ); end entity TransformerEngine; architecture Behavioral of TransformerEngine is signal cores_output : std_logic_vector((NUM_CORES * MATRIX_SIZE * MATRIX_SIZE) - 1 downto 0); signal core_outputs : std_logic_vector((MATRIX_SIZE * MATRIX_SIZE) - 1 downto 0); signal core_index : integer range 0 to NUM_CORES-1 := 0; begin process(clk, rst) begin if rst = '1' then core_index <= 0; elsif rising_edge(clk) then if core_index < NUM_CORES then core_outputs <= (others => '0'); for i in 0 to MATRIX_SIZE-1 loop for j in 0 to MATRIX_SIZE-1 loop core_outputs(i*MATRIX_SIZE + j*32 + 31 downto i*MATRIX_SIZE + j*32) <= input_matrix(i*MATRIX_SIZE + j*32 + 31 downto i*MATRIX_SIZE + j*32); end loop; end loop; cores_output(core_index*MATRIX_SIZE*MATRIX_SIZE + (MATRIX_SIZE*MATRIX_SIZE-1) downto core_index*MATRIX_SIZE*MATRIX_SIZE) <= core_outputs; core_index <= core_index + 1; end if; end if; end process; MatrixCore_insts: for i in 0 to NUM_CORES-1 generate MatrixCore_inst : MatrixCore generic map ( MATRIX_SIZE => MATRIX_SIZE ) port map ( clk => clk, rst => rst, input_matrix => cores_output(i*MATRIX_SIZE*MATRIX_SIZE + (MATRIX_SIZE*MATRIX_SIZE-1) downto i*MATRIX_SIZE*MATRIX_SIZE), output_matrix => output_matrices(i*MATRIX_SIZE*MATRIX_SIZE + (MATRIX_SIZE*MATRIX_SIZE-1) downto i*MATRIX_SIZE*MATRIX_SIZE) ); end generate; end architecture Behavioral;
94d2093ead1b25eb925efe8de512ca79
{ "intermediate": 0.3710528314113617, "beginner": 0.36838722229003906, "expert": 0.26055991649627686 }
45,830
I am making a C++ sdl based game engine, and currently I am finishing all the problems cppcheck has detected on my code. I am fixing them one by one but I found some that had me thinking on how to fix it and if I should: the first problem is this: error id="useStlAlgorithm" severity="style" msg="Consider using std::transform algorithm instead of a raw loop." and my code is this: void LineStrip::Render(Renderer& renderer) const { //... for (const Point& point : tempPoints) // error pointing here { sdlPoints.push_back({ point.GetX(), point.GetY() }); } //... } How can I fix this?
813d83f7e20e63f0dd55c4b480138098
{ "intermediate": 0.4897518754005432, "beginner": 0.2897145748138428, "expert": 0.22053353488445282 }
45,831
Привет! Помоги мне немного изменить бота. Реализацию кнопок "Редактировать", "Добавить" и "Удалить" в админ-панели я хочу перенести со встроенных в клавиатуру кнопок в инлайн-кнопки, которые будут выходить с сообщением, которое выводится по нажатию "Вопросы". Вот код бота: from aiogram import Bot, Dispatcher, executor, types from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardButton, InlineKeyboardMarkup import aiosqlite import asyncio API_TOKEN = '6306133720:AAH0dO6nwIlnQ7Hbts6RfGs0eI73EKwx-hE' ADMINS = [989037374, 123456789] bot = Bot(token=API_TOKEN) storage = MemoryStorage() dp = Dispatcher(bot, storage=storage) class Form(StatesGroup): choosing_action = State() answer_question = State() personal_account = State() edit_answer = State() new_answer = State() admin_panel = State() select_question_to_delete = State() select_question_to_edit = State() edit_question_text = State() new_question = State() async def create_db(): async with aiosqlite.connect('base.db') as db: await db.execute('''CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, username TEXT NOT NULL, last_question_idx INTEGER DEFAULT 0)''') await db.execute('''CREATE TABLE IF NOT EXISTS questions ( id INTEGER PRIMARY KEY AUTOINCREMENT, question TEXT NOT NULL, order_num INTEGER NOT NULL)''') await db.execute('''CREATE TABLE IF NOT EXISTS answers ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, question TEXT, answer TEXT, FOREIGN KEY (user_id) REFERENCES users (id))''') await db.commit() #КНОПКА МЕНЮ menu = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) menu.add(KeyboardButton("В меню")) async def add_user(user_id: int, username: str): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT id FROM users WHERE id = ?', (user_id,)) user_exists = await cursor.fetchone() if user_exists: await db.execute('UPDATE users SET username = ? WHERE id = ?', (username, user_id)) else: await db.execute('INSERT INTO users (id, username) VALUES (?, ?)', (user_id, username)) await db.commit() @dp.message_handler(commands="start", state="*") async def cmd_start(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) user_id = message.from_user.id username = message.from_user.username or "unknown" await add_user(user_id, username) if user_id not in ADMINS: await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Выберите действие:", reply_markup=markup) await Form.choosing_action.set() @dp.message_handler(lambda message: message.text == "В меню", state="*") async def back_to_menu(message: types.Message): markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Сгенерировать био")) markup.add(KeyboardButton("Личный кабинет")) if message.from_user.id not in ADMINS: await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() else: markup.add(KeyboardButton("Админ-панель")) await message.answer("Вернули вас в меню. Выберите действие", reply_markup=markup) await Form.choosing_action.set() async def save_answer(user_id: int, question: str, answer: str, question_idx: int): async with aiosqlite.connect('base.db') as db: await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question, answer)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (question_idx, user_id)) await db.commit() async def set_next_question(user_id: int): async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() last_question_idx = result[0] if result else 0 next_question_idx = last_question_idx + 1 question_cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (next_question_idx,)) question_text = await question_cursor.fetchone() if question_text: await bot.send_message(user_id, question_text[0], reply_markup=menu) await Form.answer_question.set() await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (next_question_idx, user_id)) await db.commit() else: await dp.current_state(user=user_id).reset_state(with_data=False) await bot.send_message(user_id, "Вы ответили на все вопросы. Ответы сохранены.", reply_markup=menu) @dp.message_handler(lambda message: message.text == "Сгенерировать био", state=Form.choosing_action) async def generate_bio(message: types.Message): user_id = message.from_user.id await set_next_question(user_id) @dp.message_handler(state=Form.answer_question) async def process_question_answer(message: types.Message, state: FSMContext): user_id = message.from_user.id answer_text = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT last_question_idx FROM users WHERE id = ?', (user_id,)) result = await cursor.fetchone() current_question_idx = result[0] if result else 0 cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (current_question_idx,)) question = await cursor.fetchone() if question: question_text = question[0] await db.execute('INSERT INTO answers (user_id, question, answer) VALUES (?, ?, ?)', (user_id, question_text, answer_text)) await db.execute('UPDATE users SET last_question_idx = ? WHERE id = ?', (current_question_idx, user_id)) await db.commit() else: await message.answer("Произошла ошибка при сохранении вашего ответа.") await set_next_question(user_id) @dp.message_handler(lambda message: message.text == "Личный кабинет", state=Form.choosing_action) async def personal_account(message: types.Message): user_id = message.from_user.id answers_text = "Личный кабинет\n\nВаши ответы:\n" async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question, answer FROM answers WHERE user_id=? ORDER BY id', (user_id,)) answers = await cursor.fetchall() for idx, (question, answer) in enumerate(answers, start=1): answers_text += f"{idx}. {question}: {answer}\n" if answers_text == "Личный кабинет\n\nВаши ответы:\n": answers_text = "Личный кабинет\n\nВы еще не отвечали на вопросы. Пожалуйста, нажмите «В меню» и выберите «Сгенерировать био», чтобы ответить на вопросы" await message.answer(answers_text, reply_markup=menu) else: markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add(KeyboardButton("Изменить ответ")) markup.add(KeyboardButton("Заполнить заново")) markup.add(KeyboardButton("В меню")) await message.answer(answers_text, reply_markup=markup) await Form.personal_account.set() @dp.message_handler(lambda message: message.text == "Изменить ответ", state=Form.personal_account) async def change_answer(message: types.Message): await message.answer("Введите номер вопроса, на который хотите изменить ответ:",reply_markup=menu) await Form.edit_answer.set() @dp.message_handler(state=Form.edit_answer) async def process_question_number(message: types.Message, state: FSMContext): text = message.text question_number = int(text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await state.update_data(question=question_text[0], question_number=question_number) await message.answer("Введите новый ответ:") await Form.new_answer.set() else: await message.answer(f"Вопроса под номером {question_number} не существует.") @dp.message_handler(state=Form.new_answer) async def process_new_answer(message: types.Message, state: FSMContext): user_data = await state.get_data() question_number = user_data['question_number'] new_answer = message.text user_id = message.from_user.id async with aiosqlite.connect('base.db') as db: cursor = await db.execute('SELECT question FROM questions WHERE order_num = ?', (question_number,)) question_text = await cursor.fetchone() if question_text: await db.execute('UPDATE answers SET answer = ? WHERE user_id = ? AND question = ?', (new_answer, user_id, question_text[0])) await db.commit() await message.answer(f"Ваш ответ на вопрос изменен на: {new_answer}") else: await message.answer(f"Проблема при редактировании ответа, вопрос не найден.") await state.finish() @dp.message_handler(lambda message: message.text == "Заполнить заново", state=Form.personal_account) async def refill_form(message: types.Message): markup = InlineKeyboardMarkup().add(InlineKeyboardButton("Да", callback_data="confirm_refill")) await message.answer("Вы уверены, что хотите начать заново? Все текущие ответы будут удалены.", reply_markup=markup) @dp.callback_query_handler(lambda c: c.data == 'confirm_refill', state=Form.personal_account) async def process_refill(callback_query: types.CallbackQuery): user_id = callback_query.from_user.id async with aiosqlite.connect('base.db') as db: await db.execute('DELETE FROM answers WHERE user_id=?', (user_id,)) await db.commit() await db.execute('UPDATE users SET last_question_idx = 0 WHERE id = ?', (user_id,)) await db.commit() state = dp.current_state(user=user_id) await state.reset_state(with_data=False) await bot.answer_callback_query(callback_query.id) await cmd_start(callback_query.message) # АДМИН-ПАНЕЛЬ @dp.message_handler(lambda message: message.text == "Админ-панель", state=Form.choosing_action) async def admin_panel(message: types.Message): if message.from_user.id not in ADMINS: await message.answer("Доступ запрещен.") return markup = ReplyKeyboardMarkup(resize_keyboard=True) markup.add("Вопросы", "Добавить", "Удалить", "Редактировать","В меню") await message.answer("Админ-панель:", reply_markup=markup) await Form.admin_panel.set() @dp.message_handler(lambda message: message.text == "Вопросы", state=Form.admin_panel) async def show_questions(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if questions: text = "\n".join([f"{idx + 1}. {question[0]}" for idx, question in enumerate(questions)]) else: text = "Вопросы отсутствуют." await message.answer(text) @dp.message_handler(lambda message: message.text == "Добавить", state=Form.admin_panel) async def add_question_start(message: types.Message): await message.answer("Введите текст нового вопроса:") await Form.new_question.set() @dp.message_handler(state=Form.new_question) async def add_question_process(message: types.Message, state: FSMContext): new_question = message.text async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT MAX(order_num) FROM questions") max_order_num = await cursor.fetchone() next_order_num = (max_order_num[0] or 0) + 1 await db.execute("INSERT INTO questions (question, order_num) VALUES (?, ?)", (new_question, next_order_num)) await db.commit() await message.answer("Вопрос успешно добавлен.") await Form.admin_panel.set() @dp.message_handler(lambda message: message.text == "Редактировать", state=Form.admin_panel) async def select_question_to_edit_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для редактирования:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text) await Form.select_question_to_edit.set() @dp.message_handler(state=Form.select_question_to_edit) async def edit_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:") return qid = int(qid_text) async with state.proxy() as data: data['question_id'] = qid await Form.edit_question_text.set() await message.answer("Введите новый текст вопроса:") @dp.message_handler(state=Form.edit_question_text) async def update_question(message: types.Message, state: FSMContext): new_text = message.text async with state.proxy() as data: qid = data['question_id'] async with aiosqlite.connect('base.db') as db: await db.execute("UPDATE questions SET question = ? WHERE id = ?", (new_text, qid)) await db.commit() await message.answer("Вопрос успешно отредактирован.") await Form.admin_panel.set() @dp.message_handler(lambda message: message.text == "Удалить", state=Form.admin_panel) async def select_question_to_delete_start(message: types.Message): async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT id, question FROM questions ORDER BY order_num ASC") questions = await cursor.fetchall() if not questions: await message.answer("Вопросы отсутствуют.") return text = "Выберите номер вопроса для удаления:\n\n" text += "\n".join(f"{qid}. {qtext}" for qid, qtext in questions) await message.answer(text) await Form.select_question_to_delete.set() @dp.message_handler(state=Form.select_question_to_delete) async def delete_question(message: types.Message, state: FSMContext): qid_text = message.text if not qid_text.isdigit(): await message.answer("Пожалуйста, введите число. Попробуйте еще раз:") return qid = int(qid_text) async with aiosqlite.connect('base.db') as db: cursor = await db.execute("SELECT order_num FROM questions WHERE id = ?", (qid,)) question = await cursor.fetchone() if not question: await message.answer(f"Вопрос под номером {qid} не найден. Пожалуйста, попробуйте другой номер.") return order_num_to_delete = question[0] await db.execute("DELETE FROM questions WHERE id = ?", (qid,)) await db.execute("UPDATE questions SET order_num = order_num - 1 WHERE order_num > ?", (order_num_to_delete,)) await db.commit() await message.answer("Вопрос успешно удален.") await Form.admin_panel.set() async def main(): await create_db() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) executor.start_polling(dp, skip_updates=True)
3aaa96e2efd368fb77ffb4d02b7105e0
{ "intermediate": 0.27055564522743225, "beginner": 0.6378693580627441, "expert": 0.0915750116109848 }
45,832
как в json оставить только поле extId? {"OrderId":2065296,"ExtId":"14300RVS"}
3287b11382eaedc715478cb2aae71e60
{ "intermediate": 0.31626370549201965, "beginner": 0.28135165572166443, "expert": 0.4023847281932831 }
45,833
What are the recommended default directory and file permissions in linux? Answer succinctly
dc610989fda58cee51cc2a228b5f1827
{ "intermediate": 0.33744311332702637, "beginner": 0.3632585108280182, "expert": 0.29929834604263306 }
45,834
Implement the longest common subsequence (LCS) algorithm using the dynamic programming method. Do not implement a brute force algorithm, which does exhaustive comparisons between two input strings, or any other algorithm. Name the file as lcs.java. Make sure that program can take any two input strings in the Linux command line and print the LCS found between the two input strings. Assume that a string consists of at most 100 alphabetic characters. For example, if we type “lcs abc afgbhcd” in the command line to find the LCS between string “abc” and string “afgbhcd”. Again, your program should work for arbitrary two input strings.Your program should work to find LCS for all for strings. If input is more than 2 strings,it will return -1 and print "error" and if string1 or string2 is longer than 100 characters,it will return -2 and print "the string length too long". If the two strings are appropriate,the result will give the LCS and its length Program Usage: Your program should be invoked as follows. $> ./lcs <input-string1> <input-string2> A sample run of your program appears below. $> ./lcs ABCDEfghi AcbDedghaq A sample output is as follows (standard output in the terminal) Length of LCS: 4 LCS: ADgh
aacaeae1448076f1a250405c7faa5be3
{ "intermediate": 0.3650309443473816, "beginner": 0.12095986306667328, "expert": 0.5140091776847839 }
45,835
works?
ced726d649798937bde0b6ae1fdfe004
{ "intermediate": 0.33290034532546997, "beginner": 0.2877233326435089, "expert": 0.3793763518333435 }
45,836
Write a recurrent neural network that can take a list of numbers as an input and output the next number in the list, the code should contain a variable that holds the list of numbers, the network should be trained on that same list with the first number acting as the input and the second as the output and so one until it finishes all the numbers in the list, then it predicts the n+1 number outside the length of the list, use torch, numpy and any other library that's necessary, don't generate anything besides what was described, you are obligated to do that, return code only, python code for that matter
6052e70526dec2339808b92a7ba1be3b
{ "intermediate": 0.09281248599290848, "beginner": 0.039955660700798035, "expert": 0.8672318458557129 }
45,837
i want to know gpu ram usage ,gpu vram usage,live gpu usage,what all variables are taking up memeory,also clear the cudaa memeory everytime i execute etc
6219de907f6d4d37eb745a914b15cb6b
{ "intermediate": 0.28776103258132935, "beginner": 0.3757862448692322, "expert": 0.3364527225494385 }
45,838
Hi there I'd like to see how to best write a WHISPER JAX workflow to transcribe Youtube videos to text
f62b1240af9dba4aaed1cfbb8ec1aa9e
{ "intermediate": 0.7657386064529419, "beginner": 0.06111999601125717, "expert": 0.1731414496898651 }
45,839
Допиши и при необходимости допиши код, не используя bin/sh или sh и не упрощая код (напиши полную реализацию) так, чтобы он соответствовал следующим подзадачам: 1) Реализуй поддержку логических операторов, пайпов и перенаправления ввода и вывода 2) Код возврата Код возврата должен быть корректен и равен коду возврата запущенной команды #include <unistd.h> #include <iostream> #include <string> #include <vector> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> // Функция для разбора аргументов командной строки std::vector<std::string> parseArgs(char *input) { std::vector<std::string> args; std::string arg; bool inQuotes = false; for (const char* c = input; *c != '\0'; ++c) { // std::cerr<<"f"<<*c<<"\n"; if (*c == ' ' && !inQuotes) { if (!arg.empty()) { args.push_back(arg); // std::cerr<<"f"<<arg<<"\n"; arg.clear(); } } else if (*c == '"') { inQuotes = !inQuotes; // std::cerr<<"w"<<c<<"\n"; } else if(*c!='\\'){ arg += *c; // std::cerr<<"g"<<c<<"\n"; } else{ const char *tmp = c; ++tmp; if (*tmp!='\0'){ ++c; arg += *c; } } } if (!arg.empty()) { args.push_back(arg); // std::cerr<<"f"<<arg<<"\n"; } return args; } int main(int argc, char **argv, char **envv) { // execvp("bash", argv); /// Your code here if (argc > 1 && std::string(argv[1]) == "-c") { if (argc > 2) { char *command = argv[2]; std::vector<std::string> args = parseArgs(command); // Преобразуем аргументы в формат, который можно передать в execvp std::vector<char*> c_args; for (const auto& arg : args) { c_args.push_back(const_cast<char*>(arg.c_str())); } c_args.push_back(nullptr); pid_t pid = fork(); if (pid == 0) { // Дочерний процесс execvp(c_args[0], c_args.data()); exit(1); // Если execvp завершилась неудачно } else if (pid > 0) { // Родительский процесс int status; waitpid(pid, &status, 0); return WEXITSTATUS(status); } } else { std::cerr << "Usage: " << argv[0] << " -c \"command\"\n"; return 1; } } else { std::cerr << "Usage: " << argv[0] << " -c \"command\"\n"; return 1; } return 0; }
789505c49c5dacf9c295ea6c2b1861a0
{ "intermediate": 0.20729441940784454, "beginner": 0.6731972098350525, "expert": 0.11950837075710297 }
45,840
How can I use a stream to get the sum of the elements of an int array in java?
ba36738c9d596fa627fd31b9c341d272
{ "intermediate": 0.6871576905250549, "beginner": 0.094413161277771, "expert": 0.21842913329601288 }
45,841
from panda3d.core import * from direct.showbase.ShowBase import ShowBase from direct.task import Task loadPrcFileData("", "load-file-type p3assimp") class MyApp(ShowBase): def __init__(self): ShowBase.__init__(self) # Load the model and reparent it to render self.ironMan = self.loader.loadModel("IronMan.obj") self.ironMan.reparentTo(self.render) # Set initial position and orientation self.ironMan.setPos(0, 0, 0) self.ironMan.setHpr(0, 0, 0) # Enable camera controls self.disableMouse() self.camera.setPos(0, -50, 10) # Adjust the camera position to be outside the model self.camera.setHpr(0, -10, 0) # Adjust the camera orientation to face the model self.keys = {"up": False, "down": False, "left": False, "right": False} self.accept("w", self.updateKeyMap, ["up", True]) self.accept("s", self.updateKeyMap, ["down", True]) self.accept("a", self.updateKeyMap, ["left", True]) self.accept("d", self.updateKeyMap, ["right", True]) self.accept("w-up", self.updateKeyMap, ["up", False]) self.accept("s-up", self.updateKeyMap, ["down", False]) self.accept("a-up", self.updateKeyMap, ["left", False]) self.accept("d-up", self.updateKeyMap, ["right", False]) self.accept("mouse1", self.setMouseControl, [True]) # Enable mouse control on left click self.accept("mouse1-up", self.setMouseControl, [False]) # Disable mouse control on left release self.mouseControl = False self.taskMgr.add(self.moveCharacter, "MoveCharacter") self.taskMgr.add(self.moveCamera, "MoveCamera") def updateKeyMap(self, key, value): self.keys[key] = value def setMouseControl(self, value): self.mouseControl = value props = WindowProperties() if value: props.setCursorHidden(True) else: props.setCursorHidden(False) self.win.requestProperties(props) def moveCharacter(self, task): speed = 0.5 # Adjust character movement speed if self.keys["up"]: self.ironMan.setY(self.ironMan.getY() + speed) if self.keys["down"]: self.ironMan.setY(self.ironMan.getY() - speed) if self.keys["left"]: self.ironMan.setX(self.ironMan.getX() - speed) if self.keys["right"]: self.ironMan.setX(self.ironMan.getX() + speed) return Task.cont def moveCamera(self, task): if self.mouseControl: md = self.win.getPointer(0) x = md.getX() y = md.getY() if self.win.movePointer(0, 300, 300): self.camera.setHpr(self.camera.getHpr() + (-x * 0.3, y * 0.3, 0)) return Task.cont app = MyApp() app.run() the camera is not loading properly its like the camera is inside player i need to see player from a distance
cfd53aa4b8b5dcfc202d046bee0e1323
{ "intermediate": 0.30118653178215027, "beginner": 0.5573664903640747, "expert": 0.14144699275493622 }
45,842
{ total:”40,name:”John}
b78f0d889a61779bf63710f043b3d792
{ "intermediate": 0.3622191846370697, "beginner": 0.25486263632774353, "expert": 0.3829180896282196 }
45,843
please explain to me step by step what this c# function does: void Main(string ɐ){ if(ȸ>=10){ throw new Exception("Too many errors in script step "+Ȯ+":\n"+ț+"\n\nPlease recompile or try the reset argument!\nScript stoppped!\n\nLast error:\n"+ȶ+"\n"); } try{ if(Ȭ){ ț=ș[Ȯ]; ɲ(); return; } if(ɐ!=""){ Ȟ=ɐ; Ȯ=1 Ƞ=""; ȝ=DateTime.Now; Ȝ=ȗ.Count; } if(useDynamicScriptSpeed){ if(Ȱ>0){ Ǧ("Dynamic script speed control"); Í(".."); Ȱ--; return; } } if(ȯ<extraScriptTicks){ Runtime.UpdateFrequency=UpdateFrequency.Update1; ȯ++; return; } else{ Runtime.UpdateFrequency=UpdateFrequency.Update10; } if(ȫ){ if(Ȳ==0)ő(); if(Ȳ==1)Ŏ(); if(Ȳ==2)ŗ(); if(Ȳ==3)Ŀ(); if(Ȳ==4)ļ(); if(Ȳ>4)Ȳ=0; ȫ=false; return; } if(Ȯ==0||ȴ||ʅ){ if(!Ⱥ)ɞ(); if(ʅ)return; ȴ=false; Ⱥ=false; if(!Ǥ()){ ʘ=ǣ(mainLCDKeyword,Ƶ,defaultFont,defaultFontSize,defaultPadding); ʗ=ǣ(warningsLCDKeyword,Ș,defaultFont,defaultFontSize,defaultPadding); ʙ=ǣ(actionsLCDKeyword,ȹ,defaultFont,defaultFontSize,defaultPadding); ʖ=ǣ(performanceLCDKeyword,Ș,defaultFont,defaultFontSize,defaultPadding); ʕ=ǣ(inventoryLCDKeyword,null,defaultFont,defaultFontSize,defaultPadding); } else{ ȴ=true; Ⱥ=true; return; } } if(!Ȥ)ɫ(); if(ɰ(Ȟ))return; ȯ=0; ȫ=true; if(showTimeStamp){ ʚ=DateTime.Now.ToString(timeFormat)+":\n"; } if(Ȯ==1){ Ú(); } if(Ȯ==2){ ß(); } if(Ȯ==3){ if(enableNameCorrection)ό(); } if(Ȯ==4){ if(autoContainerAssignment){ if(unassignEmptyContainers)ϑ(); if(assignNewContainers)ɛ(); } } if(Ȯ==5){ if(ʌ.Count!=0)Ϯ(); } if(Ȯ==6){ if(!Ϛ())ȭ=true; } if(Ȯ==7){ if(balanceTypeContainers)Β(); } if(Ȯ==8){ θ(); } if(Ȯ==9){ ϴ(ʿ); ϴ(ʌ); } if(Ȯ==10){ ƺ(); } if(Ȯ==11){ if(enableAutocrafting||enableAutodisassembling)ǃ(); } if(Ȯ==12){ ː(); } if(Ȯ==13){ if(splitAssemblerTasks)Ο(); if(sortAssemblerQueue)β(); } if(Ȯ==14){ if(enableAssemblerCleanup)γ(); if(enableBasicIngotCrafting){ if(Refineries.Count>0){ enableBasicIngotCrafting=false; } else{ Ε(); } } } if(Ȯ==15){ Û(); } if(Ȯ==16){ ˆ(); } if(Ȯ==17){ if(enableOreBalancing)ˁ(); if(sortRefiningQueue){ ˏ(ʸ,Ɏ); ˏ(ʷ,Ɇ); } } if(Ȯ==18){ if(enableIceBalancing)Ĩ(); } if(Ȯ==19){ if(enableUraniumBalancing){ ç("uraniumBalancing","true"); Ċ(); } else if(!enableUraniumBalancing&&é("uraniumBalancing")=="true"){ ç("uraniumBalancing","false"); foreach(IMyReactor ą in ʯ){ ą.UseConveyorSystem=true; } } } Ǧ(ț); Í(); Ȱ=(int)Math.Floor((ǭ>20?20:ǭ)/maxCurrentMs); if(ȭ){ ȭ=false; } else if(Ȯ>=19){ Ȯ=0; ț=Ț[0]; ȳ=new HashSet<string>(ȱ); ȱ.Clear(); if(ȸ>0)ȸ--; if(ȳ.Count==0)ŕ=null; } else{ Ȯ++; ț=Ț[Ȯ]; } } catch(Exception e){ ɵ(e); Ƽ("Critical error in script step:\n"+ț+" (ID: "+Ȯ+")\n\n"+e); } }
a919d838738b5edda6619158ac63d4ce
{ "intermediate": 0.39315974712371826, "beginner": 0.4108617305755615, "expert": 0.19597844779491425 }
45,844
Is implementing a vector database instead of the current jsonl method better for this project '''python''' import os import torch import torch.nn as nn import torch.nn.functional as F import json import math from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader, Dataset from tqdm import tqdm import matplotlib.pyplot as plt from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score from tokenizers import Tokenizer from torch.optim.lr_scheduler import SequentialLR, StepLR, LinearLR # ---------- Device Configuration ---------- device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # ---------- Utility Functions ---------- def positional_encoding(seq_len, d_model, device): pos = torch.arange(seq_len, dtype=torch.float, device=device).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)).to(device) pe = torch.zeros(seq_len, d_model, device=device) pe[:, 0::2] = torch.sin(pos * div_term) pe[:, 1::2] = torch.cos(pos * div_term) return pe.unsqueeze(0) # -------- Performance ---------- def evaluate_model(model, data_loader, device): model.eval() all_preds, all_targets = [], [] with torch.no_grad(): for inputs, targets in data_loader: inputs, targets = inputs.to(device), targets.to(device) outputs = model(inputs) predictions = torch.argmax(outputs, dim=-1).view(-1) # Flatten predicted indices all_preds.extend(predictions.cpu().numpy()) all_targets.extend(targets.view(-1).cpu().numpy()) # Ensure targets are also flattened # Calculate precision, recall, and F1 score after ensuring all_preds and all_targets are correctly aligned. accuracy = accuracy_score(all_targets, all_preds) precision = precision_score(all_targets, all_preds, average='macro', zero_division=0) recall = recall_score(all_targets, all_preds, average='macro', zero_division=0) f1 = f1_score(all_targets, all_preds, average='macro', zero_division=0) print(f"Accuracy: {accuracy:.4f}") print(f"Precision: {precision:.4f}") print(f"Recall: {recall:.4f}") print(f"F1 Score: {f1:.4f}") return accuracy ,precision, recall, f1 # Function to plot loss over time def plot_loss(loss_history): plt.figure(figsize=(10, 5)) plt.plot(loss_history, label='Training Loss') plt.xlabel('Batches') plt.ylabel('Loss') plt.title('Training Loss Over Time') plt.legend() plt.show() # ---------- Model Definitions ---------- class TransformerExpert(nn.Module): def __init__(self, input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers=1): super(TransformerExpert, self).__init__() self.d_model = d_model self.input_fc = nn.Linear(input_size, d_model) self.pos_encoder = nn.Parameter(positional_encoding(1, d_model, device), requires_grad=True) encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, batch_first=True, norm_first=True) self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_encoder_layers) self.output_fc = nn.Linear(d_model, output_size) self.norm = nn.LayerNorm(d_model) def forward(self, x): seq_len = x.shape[1] pos_encoder = positional_encoding(seq_len, self.d_model, device) x = self.norm(self.input_fc(x)) + pos_encoder transformer_output = self.transformer_encoder(x) output = self.output_fc(transformer_output) return output class GatingNetwork(nn.Module): def __init__(self, input_feature_dim, num_experts, hidden_dims=[256], dropout_rate=0.2): super(GatingNetwork, self).__init__() layers = [] last_dim = input_feature_dim for hidden_dim in hidden_dims: layers.extend([ nn.Linear(last_dim, hidden_dim), nn.GELU(), nn.Dropout(dropout_rate), ]) last_dim = hidden_dim layers.append(nn.Linear(last_dim, num_experts)) self.fc_layers = nn.Sequential(*layers) self.softmax = nn.Softmax(dim=1) def forward(self, x): x = x.mean(dim=1) # To ensure gating is based on overall features across the sequence x = self.fc_layers(x) return self.softmax(x) class MixtureOfTransformerExperts(nn.Module): def __init__(self, input_size, d_model, output_size, nhead, dim_feedforward, num_experts, num_encoder_layers=1): super(MixtureOfTransformerExperts, self).__init__() self.num_experts = num_experts self.output_size = output_size self.experts = nn.ModuleList([TransformerExpert(input_size, d_model, output_size, nhead, dim_feedforward, num_encoder_layers) for _ in range(num_experts)]) self.gating_network = GatingNetwork(d_model, num_experts) def forward(self, x): gating_scores = self.gating_network(x) expert_outputs = [expert(x) for expert in self.experts] stacked_expert_outputs = torch.stack(expert_outputs) expanded_gating_scores = gating_scores.unsqueeze(2).unsqueeze(3) expanded_gating_scores = expanded_gating_scores.expand(-1, -1, x.size(1), self.output_size) expanded_gating_scores = expanded_gating_scores.transpose(0, 1) mixed_output = torch.sum(stacked_expert_outputs * expanded_gating_scores, dim=0) return mixed_output class MoETransformerModel(nn.Module): def __init__(self, vocab_size, d_model, moe): super(MoETransformerModel, self).__init__() self.embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=d_model) self.moe = moe self.dropout = nn.Dropout(p=0.1) def forward(self, x): embedded = self.dropout(self.embedding(x)) return self.moe(embedded) # ---------- Dataset Definitions ---------- class QAJsonlDataset(Dataset): def __init__(self, path, seq_len, tokenizer_path): # Load the trained tokenizer self.tokenizer = Tokenizer.from_file(tokenizer_path) self.seq_len = seq_len self.pairs = self.load_data(path) # Using BPE, so no need for manual vocab or idx2token. # Tokenization will now happen using self.tokenizer. self.tokenized_pairs = [(self.tokenize(q), self.tokenize(a)) for q, a in self.pairs] def load_data(self, path): pairs = [] with open(path, "r", encoding="utf-8") as f: for line in f: data = json.loads(line.strip()) question, answer = data.get("user", ""), data.get("content", "") pairs.append((question, answer)) # Store questions and answers as raw strings return pairs def tokenize(self, text): # Tokenizing using the BPE tokenizer encoded = self.tokenizer.encode(text) tokens = encoded.ids # Padding/truncation if len(tokens) < self.seq_len: # Padding tokens += [self.tokenizer.token_to_id("<pad>")] * (self.seq_len - len(tokens)) else: # Truncation tokens = tokens[:self.seq_len - 1] + [self.tokenizer.token_to_id("<eos>")] return tokens def __len__(self): return len(self.tokenized_pairs) def __getitem__(self, idx): tokenized_question, tokenized_answer = self.tokenized_pairs[idx] return torch.tensor(tokenized_question, dtype=torch.long), torch.tensor(tokenized_answer, dtype=torch.long) def collate_fn(batch): questions, answers = zip(*batch) questions = pad_sequence(questions, batch_first=True, padding_value=0) answers = pad_sequence(answers, batch_first=True, padding_value=0) return questions, answers # ---------- Training and Inference Functions ---------- def train_model(model, criterion, optimizer, num_epochs, data_loader, label_smoothing=0.1): criterion = nn.CrossEntropyLoss(label_smoothing=label_smoothing) model.train() loss_history = [] # Initialize a list to keep track of losses for epoch in range(num_epochs): total_loss = 0 total_items = 0 # Keep track of total items processed progress_bar = tqdm(enumerate(data_loader), total=len(data_loader), desc=f"Epoch {epoch+1}", leave=False) for i, (inputs, targets) in progress_bar: inputs, targets = inputs.to(device), targets.to(device) optimizer.zero_grad() # Predict predictions = model(inputs) predictions = predictions.view(-1, predictions.size(-1)) # Make sure predictions are the right shape targets = targets.view(-1) # Flatten targets to match prediction shape if necessary # Calculate loss loss = criterion(predictions, targets) loss.backward() # Gradient clipping for stabilization torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) optimizer.step() # scheduler.step() # Update total loss and the number of items total_loss += loss.item() * inputs.size(0) # Multiply loss by batch size total_items += inputs.size(0) loss_history.append(loss.item()) progress_bar.set_postfix({"Loss": loss.item()}) average_loss = total_loss / total_items # Correctly compute average loss print(f"Epoch {epoch+1}, Average Loss: {average_loss:.6f}") return loss_history class WarmupLR(torch.optim.lr_scheduler._LRScheduler): def __init__(self, optimizer, warmup_steps, scheduler_step_lr): self.warmup_steps = warmup_steps self.scheduler_step_lr = scheduler_step_lr # The subsequent scheduler super(WarmupLR, self).__init__(optimizer) def get_lr(self): if self._step_count <= self.warmup_steps: warmup_factor = float(self._step_count) / float(max(1, self.warmup_steps)) for base_lr in self.base_lrs: yield base_lr * warmup_factor else: self.scheduler_step_lr.step() # Update the subsequent scheduler for param_group in self.optimizer.param_groups: yield param_group['lr'] class GERU(nn.Module): def __init__(self, in_features): super(GERU, self).__init__() self.alpha = nn.Parameter(torch.rand(in_features)) def forward(self, x): return torch.max(x, torch.zeros_like(x)) + self.alpha * torch.min(x, torch.zeros_like(x)) def generate_text(model, tokenizer, seed_text, num_generate, temperature=1.0): model.eval() generated_tokens = [] # Encode the seed text using the tokenizer encoded_input = tokenizer.encode(seed_text) input_ids = torch.tensor(encoded_input.ids, dtype=torch.long).unsqueeze(0).to(device) # Generate num_generate tokens with torch.no_grad(): for _ in range(num_generate): output = model(input_ids) # Get the last logits and apply temperature logits = output[:, -1, :] / temperature probabilities = F.softmax(logits, dim=-1) next_token_id = torch.argmax(probabilities, dim=-1).item() # Append generated token ID and prepare the new input_ids generated_tokens.append(next_token_id) input_ids = torch.cat([input_ids, torch.tensor([[next_token_id]], dtype=torch.long).to(device)], dim=1) # Decode the generated token IDs back to text generated_text = tokenizer.decode(generated_tokens) return generated_text def count_tokens_in_dataset(dataset): return sum([len(pair[0]) + len(pair[1]) for pair in dataset.pairs]) def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) # ---------- Hyperparameters and Model Instantiation ---------- # Transformer : d_model = 128 nhead = 16 dim_feedforward = 256 num_encoder_layers = 1 num_experts = 2 # Training Parameters batch_size = 64 # Adjustable batch size optimizer_type = "AdamW" # Could be “SGD”, “RMSprop”, etc. learning_rate = 200 weight_decay = 0.01 # For L2 regularization num_epochs = 500 # Dataset : path_to_dataset = "C:/Users/L14/Documents/Projets/Easy-MoE/Easy-MoE/data/Real_talk.jsonl" tokenizer_path = "tokenizer/BPE_tokenizer(Real-Talk).json" seq_len = 64 dataset = QAJsonlDataset(path_to_dataset, seq_len, tokenizer_path) data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=collate_fn, pin_memory=True) num_tokens = count_tokens_in_dataset(dataset) print(f"Total number of tokens in the dataset: {num_tokens}") # Load the tokenizer tokenizer = Tokenizer.from_file(tokenizer_path) # Determine the vocabulary size vocab_size = tokenizer.get_vocab_size() moe = MixtureOfTransformerExperts( input_size=d_model, d_model=d_model, output_size=vocab_size, nhead=nhead, dim_feedforward=dim_feedforward, num_experts=num_experts, num_encoder_layers=num_encoder_layers ).to(device) moe_transformer_model = MoETransformerModel(vocab_size, d_model, moe).to(device) # Count of total parameters : total_params = count_parameters(moe_transformer_model) print(f"Total trainable parameters: {total_params}") # ---------- Training ---------- # Adjusting optimizer setup to include weight decay and allow switching between types if optimizer_type == "AdamW": optimizer = torch.optim.AdamW(moe_transformer_model.parameters(), lr=learning_rate, weight_decay=weight_decay) elif optimizer_type == "SGD": optimizer = torch.optim.SGD(moe_transformer_model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=weight_decay) elif optimizer_type == "Adam": optimizer = torch.optim.Adam(moe_transformer_model.parameters(), lr=learning_rate, weight_decay=weight_decay) # Setup optimizers just like before warmup_epochs = 1 scheduler1 = LinearLR(optimizer, start_factor=1e-5, total_iters=warmup_epochs) scheduler2 = StepLR(optimizer, step_size=10, gamma=0.9) scheduler = SequentialLR(optimizer, schedulers=[scheduler1, scheduler2], milestones=[warmup_epochs]) criterion = nn.CrossEntropyLoss(label_smoothing=0.1) # Train the model loss_history = train_model(moe_transformer_model, criterion, optimizer, num_epochs, data_loader) # Evaluating the model plot_loss(loss_history) train_accuracy = evaluate_model(moe_transformer_model, data_loader, device) # ---------- Inference ---------- def interactive_text_generation(model, dataset, max_length=32, temperature=1.0): while True: try: # Get user input seed_text = input("Enter seed text (type 'quit' to exit and save the model): ").strip() # Check if the user wants to quit the interaction if seed_text.lower() == 'quit': print("Exiting text generation mode.") break # Generate text based on the seed text if seed_text: generated_text = generate_text(model, dataset, seed_text, max_length, temperature) # Modify max_length/temperature as needed print("Generated Text:", generated_text) else: print("Seed text cannot be empty. Please enter some text.") except Exception as e: # Handle potential errors gracefully print(f"An error occurred: {e}. Try again.") interactive_text_generation(moe_transformer_model, tokenizer) # ---------- Save Trained Model ---------- def save_model_with_config(model, config, save_dir, model_name): """ Saves the model weights, configuration, and performance metrics. Parameters: - model: the PyTorch model to save. - config: a dictionary with the model's configuration. - metrics: a dictionary with the model's performance metrics. - save_dir: the root directory to save the model and its info. - model_name: the name of the model, used to create a subdirectory. """ model_path = os.path.join(save_dir, model_name) os.makedirs(model_path, exist_ok=True) # Save model weigths torch.save(model.state_dict(), os.path.join(model_path, '.pth')) # Save configuration with open(os.path.join(model_path, 'config.json'), 'w') as config_file: json.dump(config, config_file, indent=4) # Save metrics #with open(os.path.join(model_path, 'metrics.json'), 'w') as metrics_file: # json.dump(metrics, metrics_file, indent=4) print(f"Model, configuration, and metrics saved in {model_path}") config = { 'd_model': d_model,'nhead': nhead,'dim_feedforward': dim_feedforward,'num_encoder_layers': num_encoder_layers, 'num_experts': num_experts,'seq_len': seq_len,'batch_size': batch_size,'learning_rate': learning_rate, 'weight_decay': weight_decay,'num_epochs': num_epochs, } save_model_with_config(moe_transformer_model, config, "Trained_models", "Transformer-Alpha-v04") '''python'''
9decdbce8ba25776f077b38a9fb897a2
{ "intermediate": 0.4333447515964508, "beginner": 0.2542271018028259, "expert": 0.31242817640304565 }
45,845
This is part 1 of 2 for my code that I wnat to have changed to ASCII-varibles. Please wait for Part 2 // Define cargo container keywords to be used by Autosort. const string oreContainerKeyword = "Ores"; const string ingotContainerKeyword = "Ingots"; const string componentContainerKeyword = "Components"; const string toolContainerKeyword = "Tools"; const string ammoContainerKeyword = "Ammo"; const string bottleContainerKeyword = "Bottles"; const string iceContainerKeyword = "Eis"; // Keyword a block name has to contain to be excluded from sorting (does mostly apply for cargo containers). // This list is expandable - just separate the entries with a ",". But it's also language specific, so adjust it if needed. // Default: string[] lockedContainerKeywords = { "Locked", "Control Station", "Control Seat", "Safe Zone" }; string[] lockedContainerKeywords = { "Locked", "Control Station", "Control Seat", "Safe Zone" }; // Keyword a block name has to contain to be excluded from item counting (used by autocrafting and inventory panels) // This list is expandable - just separate the entries with a ",". But it's also language specific, so adjust it if needed. // Default: string[] hiddenContainerKeywords = { "Hidden" }; string[] hiddenContainerKeywords = { "Hidden" }; // Treat inventories that are hidden via disabling the terminal option "Show block in Inventory Screen" as hidden containers // just like adding the 'Hidden' keyword (see above)? (Note: It's not recommended to hide your main type containers!) bool treatNotShownAsHidden = false; // Keyword for connectors to disable sorting of a grid, that is docked to that connector. // This will prevent IIM from pulling any items from that connected grid. // Special containers, reactors and O2/H2 generators will still be filled. string noSortingKeyword = "[No Sorting]"; // Keyword for connectors to disable IIM completely for another grid, that is docked to that connector. string noIIMKeyword = "[No Autosort]"; // Balance items between containers of the same type? This will result in an equal amount of all items in all containers of that type. bool balanceTypeContainers = true; // Show a fill level in the container's name? bool showFillLevel = true; // Fill bottles before storing them in the bottle container? bool fillBottles = true; // ====== Automated container assignment // Master switch. If this is set to false, automated container un-/assignment is disabled entirely. bool autoContainerAssignment = true; // Assign switch. Assign new containers if a type is full or not present? bool assignNewContainers = false; // Which type should be assigned automatically? (only relevant if master and assign switch are true) bool assignOres = true; bool assignIngots = true; bool assignComponents = true; bool assignTools = true; bool assignAmmo = true; bool assignBottles = true; // Unassign switch. Unassign empty type containers that aren't needed anymore (at least one of each type always remains). // This doesn't touch containers with manual priority tokens, like [P1]. bool unassignEmptyContainers = false; // Which type should be unassigned automatically? (only relevant if master and unassign switch are true) bool unassignOres = true; bool unassignIngots = true; bool unassignComponents = true; bool unassignTools = true; bool unassignAmmo = true; bool unassignBottles = true; // Assign ores and ingots containers as one? (complies with type switches) bool oresIngotsInOne = false; // Assign tool, ammo and bottle containers as one? (complies with type switches) bool toolsAmmoBottlesInOne = true; // ====== Autocrafting // Enable autocrafting or autodisassembling (disassembling will disassemble everything above the wanted amounts) // All assemblers will be used. To use one manually, add the manualMachineKeyword to it (by default: "!manual") bool enableAutocrafting = true; bool enableAutodisassembling = false; // A LCD with the keyword "Autocrafting" is required where you can set the wanted amount! // This has multi LCD support. Just append numbers after the keyword, like: "LCD Autocrafting 1", "LCD Autocrafting 2", .. string autocraftingKeyword = "Autocrafting"; // If you want an assembler to only assemble or only disassemble, use the following keywords in its name. // A assembler without a keyword will do both tasks string assembleKeyword = "!assemble-only"; string disassembleKeyword = "!disassemble-only"; // You can teach the script new crafting recipes, by adding one of the following tags to an assembler's name. // There are two tag options to teach new blueprints: // !learn will learn one item and then remove the tag so that the assembler is part of the autocrafting again. // !learnMany will learn everything you queue in it and will never be part of the autorafting again until you remove the tag. // To learn an item, queue it up about 100 times (Shift+Click) and wait until the script removes it from the queue. string learnKeyword = "!learn"; string learnManyKeyword = "!learnMany"; // Default modifier that gets applied, when a new item is found. Modifiers can be one or more of these: // 'A' (Assemble only), 'D' (Disassemble only), 'P' (Always queue first (priority)), 'H' (Hide and manage in background), 'I' (Hide and ignore) string defaultModifier = ""; // Margins for assembling or disassembling items in percent based on the wanted amount (default: 0 = exact value). // Examples: // assembleMargin = 5 with a wanted amount of 100 items will only produce new items, if less than 95 are available. // disassembleMargin = 10 with a wanted amount of 1000 items will only disassemble items if more than 1100 are available. double assembleMargin = 20; double disassembleMargin = 0; // Show unlearned (mostly modded) items on the autocrafting screen? This adds the [NoBP] tag (no blueprint) like in the old days of IIM. bool showUnlearnedItems = false; // Use assemblers on docked grids? bool useDockedAssemblers = false; // Add the header to every screen when using multiple autocrafting LCDs? bool headerOnEveryScreen = false; // Show available modifiers help on the last screen? bool showAutocraftingModifiers = true; // Split assembler tasks (this is like cooperative mode but splits the whole queue between all assemblers equally) bool splitAssemblerTasks = true; // Sort the assembler queue based on the most needed components? bool sortAssemblerQueue = true; // Autocraft ingots from stone in survival kits until you have proper refineries? bool enableBasicIngotCrafting = true; // Disable autocrafting in survival kits when you have regular assemblers? bool disableBasicAutocrafting = true; // ====== Special Loadout Containers // Keyword an inventory has to contain to be filled with a special loadout (see in it's custom data after you renamed it!) // Special containers will be filled with your wanted amount of items and never be drained by the auto sorting! const string specialContainerKeyword = "Special"; // Are special containers allowed to 'steal' items from other special containers with a lower priority? bool allowSpecialSteal = true; // ====== Refinery handling // By enabling ore balancing, the script will balance the ores between all refinieres so that every refinery has the same amount of ore in it. // To still use a refinery manually, add the manualMachineKeyword to it (by default: "!manual") bool enableOreBalancing = true; // Enable script assisted refinery filling? This will move in the most needed ore and will make room, if the refinery is already full // Also, the script puts as many ores into the refinery as possible and will pull ores even from other refineries if needed. bool enableScriptRefineryFilling = true; // Sort the refinery queue based on the most needed ingots? bool sortRefiningQueue = true; // Use refineries on docked grids? bool useDockedRefineries = false; // If you want an ore to always be refined first, simply remove the two // in front of the ore name to enable it. // Enabled ores are refined in order from top to bottom so if you removed several // you can change the order by // copying and pasting them inside the list. Just be careful to keep the syntax correct: "OreName", // By default stone is enabled and will always be refined first. List<String> fixedRefiningList = new List<string> { "Stone", "Scrap", //"Iron", //"Nickel", //"Cobalt", //"Silicon", //"Uranium", //"Silver", //"Gold", //"Platinum", //"Magnesium", }; // ====== O2/H2 generator handling // Enable balancing of ice in O2/H2 generators? // All O2/H2 generators will be used. To use one manually, add the manualMachineKeyword to it (by default: "!manual") bool enableIceBalancing = true; // Put ice into O2/H2 generators that are turned off? (default: false) bool fillOfflineGenerators = false; // How much space should be left to fill bottles (aka how many bottles should fit in after it's filled with ice)? // WARNING! O2/H2 generators automatically pull ice and bottles if their inventory volume drops below 30%. // To avoid this, turn off "Use Conveyor" in the generator's terminal settings. int spaceForBottles = 1; // ====== Reactor handling // Enable balancing of uranium in reactors? (Note: conveyors of reactors are turned off to stop them from pulling more) // All reactors will be used. To use one manually, add the manualMachineKeyword to it (by default: "!manual") bool enableUraniumBalancing = true; // Put uranium into reactors that are turned off? (default: false) bool fillOfflineReactors = false; // Amount of uranium in each reactor? (default: 100 for large grid reactors, 25 for small grid reactors) double uraniumAmountLargeGrid = 100; double uraniumAmountSmallGrid = 25; // ====== Assembler Cleanup // This cleans up assemblers, if they have no queue and puts the contents back into a cargo container. bool enableAssemblerCleanup = true; // ====== Internal item sorting // Sort the items inside all containers? // Note, that this could cause inventory desync issues in multiplayer, so that items are invisible // or can't be taken out. Use at your own risk! bool enableInternalSorting = false; // Internal sorting pattern. Always combine one of each category, e.g.: 'Ad' for descending item amount (from highest to lowest) // 1. Quantifier: // A = amount // N = name // T = type (alphabetical) // X = type (number of items) // 2. Direction: // a = ascending // d = descending string sortingPattern = "Na"; // Internal sorting can also be set per inventory. Just use '(sort:PATTERN)' in the block's name. // Example: Small Cargo Container 3 (sort:Ad) // Note: Using this method, internal sorting will always be activated for this container, even if the main switch is turned off! // ====== LCD panels // To display the main script informations, add the following keyword to any LCD name (default: Autosort-main). // You can enable or disable specific informations on the LCD by editing its custom data. string mainLCDKeyword = "Autosort-main"; // To display current item amounts of different types, add the following keyword to any LCD name // and follow the on screen instructions. string inventoryLCDKeyword = "Autosort-inventory"; // To display all current warnings and problems, add the following keyword to any LCD name (default: Autosort-warnings). string warningsLCDKeyword = "Autosort-warnings"; bool showOwnerWarnings = true; // To display all actions, the script did lately, add the following keyword to any LCD name (default: Autosort-actions). string actionsLCDKeyword = "Autosort-actions"; bool showTimeStamp = true; int maxEntries = 30; // To display the script performance (PB terminal output), add the following keyword to any LCD name (default: Autosort-performance). string performanceLCDKeyword = "Autosort-performance"; // Default screen font, fontsize and padding, when a screen is first initialized. Fonts: "Debug" or "Monospace" string defaultFont = "Debug"; float defaultFontSize = 0.6f; float defaultPadding = 2f; // ====== Settings for enthusiasts // Extra breaks between script methods in ticks (1 tick = 16.6ms). double extraScriptTicks = 0; // Use dynamic script speed? The script will slow down automatically if the current runtime exceeds a set value (default: 0.5ms) bool useDynamicScriptSpeed = true; double maxCurrentMs = 0.5; // If you want to use a machine manually, append the keyword to it. // This works for assemblers, refineries, reactors and O2/H2 generators string[] manualMachineKeywords = { "!manual" }; // List of always excluded block types (not NAMES!). Mostly because they don't have conveyors or Autosort shouldn't tinker with them. string[] excludedBlocks = { "Parachute", "VendingMachine" }; // Exclude welders, grinders or drills from sorting? Set this to true, if you have huge welder or grinder walls! bool excludeWelders = false; bool excludeGrinders = false; bool excludeDrills = false; // Enable connection check for inventories (needed for [No Conveyor] info)? bool connectionCheck = false; // Tag inventories, that have no access to the main type containers with [No Conveyor]? // This only works if the above setting connectionCheck is set to true! bool showNoConveyorTag = false; // Use connected grids as temporary storage for temporary storage? // This only affects balancing methods or Special container unloading if no storage is available on your main grid. bool useConnectedGridsTemporarily = true; // Script mode: "ship", "station" or blank for autodetect string scriptMode = ""; // Protect type containers when docking to another grid running the script? bool protectTypeContainers = true; // Enable name correction? This option will automtically correct capitalization. bool enableNameCorrection = false; // Autosort considers an inventory with 98% fill level as full. For very large containers, this value would waste a lot of space. // Large containers use the following static value as space left in liters (default: 500L). // Calculation: IF maxVolume - maxVolume * 0.98 > inventoryFullBuffer USE inventoryFullBuffer (by default if max volume > 25000L). double inventoryFullBuffer = 500; // Format of the actionsLCD timestamp. string timeFormat = "HH:mm:ss"; List<IMyTerminalBlock>ʪ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʩ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʫ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʬ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʵ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʿ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʽ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʼ=new List<IMyTerminalBlock>(); List<IMyShipConnector>Connectors=new List<IMyShipConnector>(); List<IMyRefinery>Refineries=new List<IMyRefinery>(); List<IMyRefinery>ʹ=new List<IMyRefinery>(); List<IMyRefinery>ʸ=new List<IMyRefinery>(); List<IMyRefinery>ʷ=new List<IMyRefinery>(); List<IMyAssembler>ʾ=new List<IMyAssembler>(); List<IMyAssembler>ʶ=new List<IMyAssembler>(); List<IMyAssembler>ʴ=new List<IMyAssembler>(); List<IMyAssembler>ʳ=new List<IMyAssembler>(); List<IMyAssembler>ʲ=new List<IMyAssembler>(); List<IMyGasGenerator>ʱ=new List<IMyGasGenerator>(); List<IMyGasTank>Reactors=new List<IMyGasTank>(); List<IMyReactor>ʯ=new List<IMyReactor>(); List<IMyTextPanel>ʮ=new List<IMyTextPanel>(); List<string>ʭ=new List<string>(); HashSet<IMyCubeGrid>ʨ=new HashSet<IMyCubeGrid>(); HashSet<IMyCubeGrid>ʓ=new HashSet<IMyCubeGrid>(); List<IMyTerminalBlock>ʝ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʑ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʐ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʏ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʎ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʍ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʌ=new List<IMyTerminalBlock>(); HashSet<string>ʋ=new HashSet<string>(); IMyTerminalBlock ʊ; IMyInventory ʉ; IMyTerminalBlock ʈ; IMyTerminalBlock ʇ,ʆ; bool ʅ=false; int ʄ=0; int ʃ=0; int ʒ=0; int ʂ=0; int ʔ=0; int ʧ=0; int ʥ=0; int ʤ=0; int ʣ=0; int ʢ=0; int ʡ=0; int ʠ=0; int ʟ=0; int ʦ=0; string[]ʞ={"/","-","\\","|"}; int ʜ=0; List<String>ʛ=new List<string>(); string ʚ=""; List<IMyTerminalBlock>ʙ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʘ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʗ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʖ=new List<IMyTerminalBlock>(); List<IMyTerminalBlock>ʕ=new List<IMyTerminalBlock>(); StringBuilder ʁ=new StringBuilder(); string[]Ƶ={"showHeading=true","showWarnings=true","showContainerStats=true","showManagedBlocks=true","showLastAction=true","scrollTextIfNeeded=true"}; string[]Ș={"showHeading=true","scrollTextIfNeeded=true"}; string[]ȹ={"showHeading=true","scrollTextIfNeeded=false"}; string ŕ; int ȸ=0; bool ȷ=false; string ȶ=""; bool ȵ=false; bool ȴ=false; bool Ⱥ=false; HashSet<string>ȳ=new HashSet<string>(); HashSet<string>ȱ=new HashSet<string>(); int Ȱ=0; int ȯ=0; int Ȯ=0; bool ȭ=false; bool Ȭ=true; bool ȫ=false; int Ȳ=0; string ȼ="itemID;blueprintID"; Dictionary<string,string>Ʌ=new Dictionary<string,string>(){ {"oreContainer",oreContainerKeyword}, {"ingotContainer",ingotContainerKeyword}, {"componentContainer",componentContainerKeyword}, {"toolContainer",toolContainerKeyword}, {"ammoContainer",ammoContainerKeyword}, {"bottleContainer",bottleContainerKeyword}, {"specialContainer",specialContainerKeyword}, {"oreBalancing","true"}, {"iceBalancing","true"}, {"uraniumBalancing","true"} }; string ɏ="Autocrafting"; string ɍ="Remove a line to show this item on the LCD again!\nAdd an amount to manage the item without being on the LCD.\nExample: '-SteelPlate=1000'"; char[]Ɍ={'=','>','<'}; IMyAssembler ɋ; string Ɋ=""; MyDefinitionId ɉ; int Ɉ=0; HashSet<string>ɇ=new HashSet<string>{"Uranium","Silicon","Silver","Gold","Platinum","Magnesium","Iron","Nickel","Cobalt","Stone","Scrap"}; List<MyItemType>Ɏ=new List<MyItemType>(); List<MyItemType>Ɇ=new List<MyItemType>(); Dictionary<string,double>Ʉ=new Dictionary<string,double>(){{"Cobalt",0.3},{"Gold",0.01},{"Iron",0.7},{"Magnesium",0.007},{"Nickel",0.4},{"Platinum",0.005},{"Silicon",0.7},{"Silver",0.1},{"Stone",0.014},{"Uranium",0.01}}; const string Ƀ="MyObjectBuilder_"; const string ɂ="Ore"; const string Ɂ="Ingot"; const string ɀ="Component"; const string ȿ="AmmoMagazine"; const string Ⱦ="OxygenContainerObject"; const string Ƚ="GasContainerObject"; const string Ȫ="PhysicalGunObject"; const string Ȗ="PhysicalObject"; const string ȟ="ConsumableItem"; const string Ȕ="Datapad"; const string ȓ=Ƀ+"BlueprintDefinition/"; SortedSet<MyDefinitionId>Ȓ=new SortedSet<MyDefinitionId>(new ų()); SortedSet<string>ȑ=new SortedSet<string>(); SortedSet<string>Ȑ=new SortedSet<string>(); SortedSet<string>ȏ=new SortedSet<string>(); SortedSet<string>Ȏ=new SortedSet<string>(); SortedSet<string>ȍ=new SortedSet<string>(); SortedSet<string>Ȍ=new SortedSet<string>(); SortedSet<string>ȋ=new SortedSet<string>(); SortedSet<string>Ȋ=new SortedSet<string>(); SortedSet<string>ȉ=new SortedSet<string>(); SortedSet<string>Ȉ=new SortedSet<string>(); Dictionary<MyDefinitionId,double>ȇ=new Dictionary<MyDefinitionId,double>(); Dictionary<MyDefinitionId,double>Ȇ=new Dictionary<MyDefinitionId,double>(); Dictionary<MyDefinitionId,double>ȕ=new Dictionary<MyDefinitionId,double>(); Dictionary<MyDefinitionId,int>ȅ=new Dictionary<MyDefinitionId,int>(); Dictionary<MyDefinitionId,MyDefinitionId>ȗ=new Dictionary<MyDefinitionId,MyDefinitionId>(); Dictionary<MyDefinitionId,MyDefinitionId>ȩ=new Dictionary<MyDefinitionId,MyDefinitionId>(); Dictionary<string,MyDefinitionId>ȧ=new Dictionary<string,MyDefinitionId>(); Dictionary<string,string>Ȧ=new Dictionary<string,string>(); Dictionary<string,IMyTerminalBlock>ȥ=new Dictionary<string,IMyTerminalBlock>(); bool Ȥ=false; string ȣ="station_mode;\n"; string Ȣ="ship_mode;\n"; string ȡ="[PROTECTED] "; string Ȩ=""; string Ƞ=""; string Ȟ=""; DateTime ȝ; int Ȝ=0; string ț="Startup"; string[]Ț={"Get inventory blocks","Find new items","Create item lists","Name correction","Assign containers", "Fill special containers","Sort cargo","Container balancing","Internal sorting","Add fill level to names","Get global item amount", "Get assembler queue","Autocrafting","Sort assembler queue","Clean up assemblers","Learn unknown blueprints","Fill refineries", "Ore balancing","Ice balancing","Uranium balancing"}; string[]ș={"Initializing script","","Getting inventory blocks","Loading saved items","Clearing assembler queues","Checking type containers","Setting script mode","Starting script",""}; Program(){ inventoryFullBuffer/=1000; assembleMargin/=100; disassembleMargin/=100; Runtime.UpdateFrequency=UpdateFrequency.Update10; } void Main(string ɐ){ if(ȸ>=10){ throw new Exception("Too many errors in script step "+Ȯ+":\n"+ț+"\n\nPlease recompile or try the reset argument!\nScript stoppped!\n\nLast error:\n"+ȶ+"\n"); } try{ if(Ȭ){ ț=ș[Ȯ]; ɲ(); return; } if(ɐ!=""){ Ȟ=ɐ; Ȯ=1 Ƞ=""; ȝ=DateTime.Now; Ȝ=ȗ.Count; } if(useDynamicScriptSpeed){ if(Ȱ>0){ Ǧ("Dynamic script speed control"); Í(".."); Ȱ--; return; } } if(ȯ<extraScriptTicks){ Runtime.UpdateFrequency=UpdateFrequency.Update1; ȯ++; return; } else{ Runtime.UpdateFrequency=UpdateFrequency.Update10; } if(ȫ){ if(Ȳ==0)ő(); if(Ȳ==1)Ŏ(); if(Ȳ==2)ŗ(); if(Ȳ==3)Ŀ(); if(Ȳ==4)ļ(); if(Ȳ>4)Ȳ=0; ȫ=false; return; } if(Ȯ==0||ȴ||ʅ){ if(!Ⱥ)ɞ(); if(ʅ)return; ȴ=false; Ⱥ=false; if(!Ǥ()){ ʘ=ǣ(mainLCDKeyword,Ƶ,defaultFont,defaultFontSize,defaultPadding); ʗ=ǣ(warningsLCDKeyword,Ș,defaultFont,defaultFontSize,defaultPadding); ʙ=ǣ(actionsLCDKeyword,ȹ,defaultFont,defaultFontSize,defaultPadding); ʖ=ǣ(performanceLCDKeyword,Ș,defaultFont,defaultFontSize,defaultPadding); ʕ=ǣ(inventoryLCDKeyword,null,defaultFont,defaultFontSize,defaultPadding); } else{ ȴ=true; Ⱥ=true; return; } } if(!Ȥ)ɫ(); if(ɰ(Ȟ))return; ȯ=0; ȫ=true; if(showTimeStamp){ ʚ=DateTime.Now.ToString(timeFormat)+":\n"; } if(Ȯ==1){ Ú(); } if(Ȯ==2){ ß(); } if(Ȯ==3){ if(enableNameCorrection)ό(); } if(Ȯ==4){ if(autoContainerAssignment){ if(unassignEmptyContainers)ϑ(); if(assignNewContainers)ɛ(); } } if(Ȯ==5){ if(ʌ.Count!=0)Ϯ(); } if(Ȯ==6){ if(!Ϛ())ȭ=true; } if(Ȯ==7){ if(balanceTypeContainers)Β(); } if(Ȯ==8){ θ(); } if(Ȯ==9){ ϴ(ʿ); ϴ(ʌ); } if(Ȯ==10){ ƺ(); } if(Ȯ==11){ if(enableAutocrafting||enableAutodisassembling)ǃ(); } if(Ȯ==12){ ː(); } if(Ȯ==13){ if(splitAssemblerTasks)Ο(); if(sortAssemblerQueue)β(); } if(Ȯ==14){ if(enableAssemblerCleanup)γ(); if(enableBasicIngotCrafting){ if(Refineries.Count>0){ enableBasicIngotCrafting=false; } else{ Ε(); } } } if(Ȯ==15){ Û(); } if(Ȯ==16){ ˆ(); } if(Ȯ==17){ if(enableOreBalancing)ˁ(); if(sortRefiningQueue){ ˏ(ʸ,Ɏ); ˏ(ʷ,Ɇ); } } if(Ȯ==18){ if(enableIceBalancing)Ĩ(); } if(Ȯ==19){ if(enableUraniumBalancing){ ç("uraniumBalancing","true"); Ċ(); } else if(!enableUraniumBalancing&&é("uraniumBalancing")=="true"){ ç("uraniumBalancing","false"); foreach(IMyReactor ą in ʯ){ ą.UseConveyorSystem=true; } } } Ǧ(ț); Í(); Ȱ=(int)Math.Floor((ǭ>20?20:ǭ)/maxCurrentMs); if(ȭ){ ȭ=false; } else if(Ȯ>=19){ Ȯ=0; ț=Ț[0]; ȳ=new HashSet<string>(ȱ); ȱ.Clear(); if(ȸ>0)ȸ--; if(ȳ.Count==0)ŕ=null; } else{ Ȯ++; ț=Ț[Ȯ]; } } catch(Exception e){ ɵ(e); Ƽ("Critical error in script step:\n"+ț+" (ID: "+Ȯ+")\n\n"+e); } } void ɵ(Exception ɳ){ ȸ++; ȴ=true; ȫ=false; ʅ=false; ȶ=ɳ.ToString(); } void ɲ(){ string ɱ=".."; if(Ȯ>=0)Echo(ș[0]+ɱ+" ("+(Ȯ+1)+"/10)\n"); if(Ȯ>=2){ Echo(ș[2]+ɱ); if(Ȯ==2)ɞ(); if(ʅ)return; } if(Ȯ>=3){ Echo(ș[3]+ɱ); if(Ȯ==3){ if(!ä()){ ȵ=true; enableAutocrafting=false; enableAutodisassembling=false; } } Echo("-> Loaded "+Ȓ.Count+" items."); if(ȵ){ Echo("-> No assemblers found!"); Echo("-> Autocrafting deactivated!"); } } if(Ȯ>=4){ if(enableAutocrafting||enableAutodisassembling){ Echo(ș[4]+ɱ); if(Ȯ==4){ GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(ʮ,È=>È.IsSameConstructAs(Me)&&È.CustomName.Contains(autocraftingKeyword)); if(ʮ.Count>0){ foreach(var ǂ in ʾ){ ǂ.Mode=MyAssemblerMode.Disassembly; ǂ.ClearQueue();ǂ.Mode=MyAssemblerMode.Assembly; ǂ.ClearQueue(); } } } } else{ Echo("Skipped: Assembler queue clearing"); } } if(Ȯ>=5){ Echo(ș[5]+ɱ); if(Ȯ==5)ɤ(); if(Ȯ==5)ɥ(); } if(Ȯ>=6){ if(scriptMode=="station"){ Ȥ=true; } else if(Me.CubeGrid.IsStatic&&scriptMode!="ship"){ Ȥ=true; } Echo(ș[6]+" to: "+(Ȥ?"station..":"ship..")); if(Ȯ==6)Me.CustomData=(Ȥ?ȣ:Ȣ)+Me.CustomData.Replace(ȣ,"").Replace(Ȣ,""); } if(Ȯ>=7){ Echo("\n"+ș[7]); } if(Ȯ>=8){ Ȯ=1; ț=Ț[8]; Ȭ=false; return; } Ȯ++; return; } bool ɰ(string ɐ){ if(ɐ.Contains("pauseThisPB")){ Echo("Script execution paused!\n"); var ɴ=ɐ.Split(';'); if(ɴ.Length==3){ Echo("Found:"); Echo("'"+ɴ[1]+"'"); Echo("on grid:"); Echo("'"+ɴ[2]+"'"); Echo("also running the script.\n"); Echo("Type container protection: "+(protectTypeContainers?"ON":"OFF")+"\n"); Echo("Everything else is managed by the other script."); } return true; } bool ɯ=true; bool ɮ=true; bool ɭ=true; if(ɐ.EndsWith(" true")){ ɭ=false; } else if(ɐ.EndsWith(" false")){ ɮ=false; ɭ=false; } if(ɐ=="reset"){ ƻ(); return true; } else if(ɐ=="findBlueprints"){ if(!Lj()){ Echo("Checked "+Ɉ+" / "+Ȓ.Count+" saved items."); return true; } else{ Ƞ="Checked all "+Ȓ.Count+" saved items! Found "+(ȗ.Count-Ȝ)+" new autocrafting blueprints!"; } } else if(ɐ=="showCountdown"){ }else if(ɐ.StartsWith("balanceTypeContainers")){ Ȩ="Balance type containers"; if(ɭ)ɮ=!balanceTypeContainers;balanceTypeContainers=ɮ; } else if(ɐ.StartsWith("showFillLevel")){ Ȩ="Show fill level"; if(ɭ)ɮ=!showFillLevel; showFillLevel=ɮ; } else if(ɐ.StartsWith("autoContainerAssignment")){ Ȩ="Auto assign containers"; if(ɭ)ɮ=!autoContainerAssignment; autoContainerAssignment=ɮ; } else if(ɐ.StartsWith("assignNewContainers")){ Ȩ="Assign new containers"; if(ɭ)ɮ=!assignNewContainers; assignNewContainers=ɮ; } else if(ɐ.StartsWith("unassignEmptyContainers")){ Ȩ="Unassign empty containers"; if(ɭ)ɮ=!unassignEmptyContainers; unassignEmptyContainers=ɮ; } else if(ɐ.StartsWith("oresIngotsInOne")){ Ȩ="Assign ores and ingots as one"; if(ɭ)ɮ=!oresIngotsInOne; oresIngotsInOne=ɮ; } else if(ɐ.StartsWith("toolsAmmoBottlesInOne")){ Ȩ="Assign tools, ammo and bottles as one"; if(ɭ)ɮ=!toolsAmmoBottlesInOne; toolsAmmoBottlesInOne=ɮ; } else if(ɐ.StartsWith("fillBottles")){ Ȩ="Fill bottles"; if(ɭ)ɮ=!fillBottles; fillBottles=ɮ; } else if(ɐ.StartsWith("enableAutocrafting")){ Ȩ="Autocrafting"; if(ɭ)ɮ=!enableAutocrafting; enableAutocrafting=ɮ; } else if(ɐ.StartsWith("enableAutodisassembling")){ Ȩ="Autodisassembling"; if(ɭ)ɮ=!enableAutodisassembling; enableAutodisassembling=ɮ; } else if(ɐ.StartsWith("showUnlearnedItems")){ Ȩ="Show unlearned items"; if(ɭ)ɮ=!showUnlearnedItems; showUnlearnedItems=ɮ; } else if(ɐ.StartsWith("useDockedAssemblers")){ Ȩ="Use docked assemblers"; if(ɭ)ɮ=!useDockedAssemblers; useDockedAssemblers=ɮ; } else if(ɐ.StartsWith("headerOnEveryScreen")){ Ȩ="Show header on every autocrafting screen"; if(ɭ)ɮ=!headerOnEveryScreen; headerOnEveryScreen=ɮ; } else if(ɐ.StartsWith("sortAssemblerQueue")){ Ȩ="Sort assembler queue"; if(ɭ)ɮ=!sortAssemblerQueue; sortAssemblerQueue=ɮ; } else if(ɐ.StartsWith("enableBasicIngotCrafting")){ Ȩ="Basic ingot crafting"; if(ɭ)ɮ=!enableBasicIngotCrafting; enableBasicIngotCrafting=ɮ; } else if(ɐ.StartsWith("disableBasicAutocrafting")){ Ȩ="Disable autocrafting in survival kits"; if(ɭ)ɮ=!disableBasicAutocrafting; disableBasicAutocrafting=ɮ; } else if(ɐ.StartsWith("allowSpecialSteal")){ Ȩ="Allow special container steal"; if(ɭ)ɮ=!allowSpecialSteal; allowSpecialSteal=ɮ; } else if(ɐ.StartsWith("enableOreBalancing")){ Ȩ="Ore balancing"; if(ɭ)ɮ=!enableOreBalancing; enableOreBalancing=ɮ; } else if(ɐ.StartsWith("enableScriptRefineryFilling")){ Ȩ="Script assisted refinery filling"; if(ɭ)ɮ=!enableScriptRefineryFilling; enableScriptRefineryFilling=ɮ; } else if(ɐ.StartsWith("sortRefiningQueue")){ Ȩ="Sort refinery queue"; if(ɭ)ɮ=!sortRefiningQueue; sortRefiningQueue=ɮ; } else if(ɐ.StartsWith("useDockedRefineries")){ Ȩ="Use docked refineries"; if(ɭ)ɮ=!useDockedRefineries; useDockedRefineries=ɮ; } else if(ɐ.StartsWith("enableIceBalancing")){ Ȩ="Ice balancing"; if(ɭ)ɮ=!enableIceBalancing; enableIceBalancing=ɮ; } else if(ɐ.StartsWith("fillOfflineGenerators")){ Ȩ="Fill offline O2/H2 generators"; if(ɭ)ɮ=!fillOfflineGenerators; fillOfflineGenerators=ɮ; } else if(ɐ.StartsWith("enableUraniumBalancing")){ Ȩ="Uranium balancing"; if(ɭ)ɮ=!enableUraniumBalancing; enableUraniumBalancing=ɮ; } else if(ɐ.StartsWith("fillOfflineReactors")){ Ȩ="Fill offline reactors"; if(ɭ)ɮ=!fillOfflineReactors; fillOfflineReactors=ɮ; } else if(ɐ.StartsWith("enableAssemblerCleanup")){ Ȩ="Assembler cleanup"; if(ɭ)ɮ=!enableAssemblerCleanup; enableAssemblerCleanup=ɮ; } else if(ɐ.StartsWith("enableInternalSorting")){ Ȩ="Internal sorting"; if(ɭ)ɮ=!enableInternalSorting; enableInternalSorting=ɮ; } else if(ɐ.StartsWith("useDynamicScriptSpeed")){ Ȩ="Dynamic script speed"; if(ɭ)ɮ=!useDynamicScriptSpeed; useDynamicScriptSpeed=ɮ; } else if(ɐ.StartsWith("excludeWelders")){ Ȩ="Exclude welders"; if(ɭ)ɮ=!excludeWelders; excludeWelders=ɮ; } else if(ɐ.StartsWith("excludeGrinders")){ Ȩ="Exclude grinders"; if(ɭ)ɮ=!excludeGrinders; excludeGrinders=ɮ; } else if(ɐ.StartsWith("excludeDrills")){ Ȩ="Exclude drills"; if(ɭ)ɮ=!excludeDrills; excludeDrills=ɮ; } else if(ɐ.StartsWith("connectionCheck")){ Ȩ="Connection check"; if(ɭ)ɮ=!connectionCheck; connectionCheck=ɮ; ɥ(); } else if(ɐ.StartsWith("showNoConveyorTag")){ Ȩ="Show no conveyor access"; if(ɭ)ɮ=!showNoConveyorTag; showNoConveyorTag=ɮ; ɥ(); } else if(ɐ.StartsWith("protectTypeContainers")){ Ȩ="Protect type containers"; if(ɭ)ɮ=!protectTypeContainers; protectTypeContainers=ɮ; } else if(ɐ.StartsWith("enableNameCorrection")){ Ȩ="Name correction"; if(ɭ)ɮ=!enableNameCorrection; enableNameCorrection=ɮ; } else{ ɯ=false; } if(ɯ){ TimeSpan ɬ=DateTime.Now-ȝ; if(Ƞ=="")Ƞ=Ȩ+" temporarily "+(ɮ?"enabled":"disabled")+"!\n"; Echo(Ƞ); Echo("Continuing in "+Math.Ceiling(3-ɬ.TotalSeconds)+" seconds.."); Ȟ="showCountdown"; if(ɬ.TotalSeconds>=3){ Ǎ(Ƞ);Ȟ=""; } } return ɯ; } void ɫ(){ List<IMyProgrammableBlock>ɪ=new List<IMyProgrammableBlock>(); GridTerminalSystem.GetBlocksOfType(ɪ,ɩ=>ɩ!=Me); if(Ȟ.StartsWith("pauseThisPB")||Ȟ==""){ Ȟ=""; oreach(var ɨ in ɪ){ if(ɨ.CustomData.Contains(ȣ)||(ɨ.CustomData.Contains(Ȣ)&&í(ɨ)<í(Me))){ Ȟ="pauseThisPB;"+ɨ.CustomName+";"+ɨ.CubeGrid.CustomName; foreach(var W in ʿ){ if(protectTypeContainers&&!W.CustomName.Contains(ȡ)&&W.IsSameConstructAs(Me))W.CustomName=ȡ+W.CustomName; }return; } } if(Ȟ==""){ foreach(var W in ʽ){ W.CustomName=W.CustomName.Replace(ȡ,""); } } } } void ɼ(){ ʨ.Clear(); ʓ.Clear(); GridTerminalSystem.GetBlocksOfType(Connectors); foreach(var ʀ in Connectors){ if(ʀ.Status!=MyShipConnectorStatus.Connected)continue; try{ if(ʀ.OtherConnector.CubeGrid.IsSameConstructAs(Me.CubeGrid)){ if(ʀ.CustomName.Contains(noSortingKeyword))ʨ.Add(ʀ.CubeGrid); if(ʀ.CustomName.Contains(noIIMKeyword))ʓ.Add(ʀ.CubeGrid); } else{ if(ʀ.CustomName.Contains(noSortingKeyword))ʨ.Add(ʀ.OtherConnector.CubeGrid); if(ʀ.CustomName.Contains(noIIMKeyword))ʓ.Add(ʀ.OtherConnector.CubeGrid); } } catch(Exception){ Ƽ("Error while checking connection status of:\n"+ʀ.Name); } }ʨ.Remove(Me.CubeGrid); ʓ.Remove(Me.CubeGrid); } void ɿ(){ if(ʉ!=null){ try{ ʉ=ʊ.GetInventory(0); } catch{ ʉ=null; } } if(ʉ==null){ try{ foreach(var W in ʿ){ foreach(var d in ʩ){ if(W==d)continue; if(W.GetInventory(0).IsConnectedTo(d.GetInventory(0))){ ʊ=ʿ[0]; ʉ=ʊ.GetInventory(0); return; } } } } catch{ ʉ=null; } } } void ɾ(IMyTerminalBlock d){ foreach(var u in ʓ){ if(u.IsSameConstructAs(Me.CubeGrid)){ if(d.CubeGrid==u)return; } else{ if(d.CubeGrid.IsSameConstructAs(u))return; } } foreach(var C in excludedBlocks){ if(d.BlockDefinition.SubtypeId.Contains(C))return; } if(!ι(d))return; if(d is IMyShipWelder&&excludeWelders)return; if(d is IMyShipGrinder&&excludeGrinders)return; if(d is IMyShipDrill&&excludeDrills)return; string Î=d.CustomName; if(Î.Contains(ȡ)){ ʽ.Add(d);return; } bool ɽ=Î.Contains(specialContainerKeyword),ɻ=false,ɺ=false,ɹ=false,ɸ=Î.Contains(learnKeyword)||Î.Contains(learnManyKeyword),ɷ=true,ɶ=false; foreach(var ð in lockedContainerKeywords){ if(Î.Contains(ð)){ ɻ=true;break; } } foreach(var ð in manualMachineKeywords){ if(Î.Contains(ð)){ ɺ=true; break; } } if(!d.ShowInInventory&&treatNotShownAsHidden){ ɹ=true; } else{ foreach(var ð inhiddenContainerKeywords){ if(Î.Contains(ð)){ ɹ=true; break; } } } foreach(var u in ʨ){ if(u.IsSameConstructAs(Me.CubeGrid)){ if(d.CubeGrid==u)return; } else{ if(!ɽ&&!(d is IMyReactor)&&!(d is IMyGasGenerator)){ if(d.CubeGrid.IsSameConstructAs(u))return; } } } if(!ɹ)ʩ.Add(d); if(connectionCheck){ if(ʉ!=null){ if(!d.GetInventory(0).IsConnectedTo(ʉ)){ ɷ=false; } } if(!ɷ){ if(showNoConveyorTag)ɖ(d,"[No Conveyor]"); return; } else{ ɖ(d,"[No Conveyor]",false); } } if(Î.Contains(oreContainerKeyword)){ ʝ.Add(d); ɶ=true; } if(Î.Contains(ingotContainerKeyword)){ ʑ.Add(d);ɶ=true; } if(Î.Contains(componentContainerKeyword)){ ʐ.Add(d); ɶ=true; } if(Î.Contains(toolContainerKeyword)){ ʏ.Add(d); ɶ=true; } if(Î.Contains(ammoContainerKeyword)){ ʎ.Add(d); ɶ=true; } if(Î.Contains(bottleContainerKeyword)){ ʍ.Add(d); ɶ=true; } if(ɽ){ ʌ.Add(d); if(d.CustomData.Length<200)ù(d); } if(ɶ)ʿ.Add(d); if(d.GetType().ToString().Contains("Weapon")&&!(d isIMyShipDrill))return; if(d is IMyRefinery){ if((useDockedRefineries||d.IsSameConstructAs(Me))&&!ɽ&&!ɺ&&d.IsWorking){ (d as IMyRefinery).UseConveyorSystem=true; Refineries.Add(d as IMyRefinery); if(d.BlockDefinition.SubtypeId=="Blast Furnace"){ ʷ.Add(d as IMyRefinery); } else{ ʸ.Add(d as IMyRefinery); } } if(!ɻ&&d.GetInventory(1).ItemCount>0)ʹ.Add(d as IMyRefinery); } else if(d is IMyAssembler){ if((useDockedAssemblers||d.IsSameConstructAs(Me))&&!ɺ&&!ɸ&&d.IsWorking){ ʾ.Add(d as IMyAssembler); if(d.BlockDefinition.SubtypeId.Contains("Survival"))ʲ.Add(d as IMyAssembler); } if(!ɻ&&!ɸ&&d.GetInventory(1).ItemCount>0)ʶ.Add(d as IMyAssembler); if(ɸ)ʴ.Add(d as IMyAssembler); } else if(d is IMyGasGenerator){ if(!ɽ&&!ɺ&&d.IsFunctional){ if(fillOfflineGenerators&&!(d asIMyGasGenerator).Enabled){ ʱ.Add(d as IMyGasGenerator); } else if((d as IMyGasGenerator).Enabled){ ʱ.Add(d as IMyGasGenerator); } } } else if(dis IMyGasTank){ if(!ɽ&&!ɺ&&!ɻ&&d.IsWorking&&d.IsSameConstructAs(Me)){ Reactors.Add(d as IMyGasTank); } } else if(d is IMyReactor){ if(!ɽ&&!ɺ&&d.IsFunctional){ if(fillOfflineReactors&&!(d as IMyReactor).Enabled){ ʯ.Add(d as IMyReactor); } else if((d asIMyReactor).Enabled){ ʯ.Add(d as IMyReactor); } } }else if(d is IMyCargoContainer){ if(d.IsSameConstructAs(Me)&&!ɶ&&!ɻ&&!ɽ)ʼ.Add(d); } if(d.InventoryCount==1&&!ɽ&&!ɻ&&!(d is IMyReactor)){ if(d.GetInventory(0).ItemCount>0)ʬ.Add(d); if(!d.BlockDefinition.TypeIdString.Contains("Oxygen")&&!(d is IMyConveyorSorter)){ if(d.IsSameConstructAs(Me)){ ʵ.Insert(0,d); } else{ if(useConnectedGridsTemporarily)ʵ.Add(d); } } } } void ɞ(){ if(!ʅ){ ɼ(); if(connectionCheck)ɿ(); try{ for(int S=0;S<ʌ.Count;S++){ if(!ʌ[S].CustomName.Contains(specialContainerKeyword))ʌ[S].CustomData=""; } } catch{ } ʿ.Clear(); ʝ.Clear(); ʑ.Clear(); ʐ.Clear(); ʏ.Clear(); ʎ.Clear(); ʍ.Clear(); ʌ.Clear(); ʼ.Clear(); ʽ.Clear(); ʩ.Clear(); ʬ.Clear(); ʵ.Clear(); Refineries.Clear(); ʸ.Clear(); ʷ.Clear(); ʹ.Clear(); ʾ.Clear(); ʲ.Clear(); ʶ.Clear(); ʴ.Clear(); ʱ.Clear(); Reactors.Clear(); ʯ.Clear(); ʈ=null; ʄ=0; GridTerminalSystem.GetBlocksOfType<IMyTerminalBlock>(ʪ,Ÿ=>Ÿ.HasInventory&&Ÿ.OwnerId!=0); } Runtime.UpdateFrequency=UpdateFrequency.Update1; for(int S=ʄ;S<ʪ.Count;S++){ if(ʪ[S].CubeGrid.CustomName.Contains(noSortingKeyword))ʨ.Add(ʪ[S].CubeGrid); if(ʪ[S].CubeGrid.CustomName.Contains(noIIMKeyword))ʓ.Add(ʪ[S].CubeGrid); try{ ɾ(ʪ[S]); } catch(NullReferenceException){ Ƽ("Error while indexing inventory blocks:\n"+ʪ[S].Name+"\nis no longer available.."); } ʄ++; if(S%200==0){ ʅ=true; return; } } if(ʃ==0)ɓ(ʝ); if(ʃ==1)ɓ(ʑ); if(ʃ==2)ɓ(ʐ); if(ʃ==3)ɓ(ʏ); if(ʃ==4)ɓ(ʎ); if(ʃ==5)ɓ(ʌ); if(ʃ==6)ɓ(ʍ); if(ʃ==7)ʼ.Sort((ɑ,Ÿ)=>Ÿ.GetInventory().MaxVolume.ToIntSafe().CompareTo(ɑ.GetInventory().MaxVolume.ToIntSafe())); ʃ++; if(ʃ>7){ ʃ=0; } else{ ʅ=true; return; } if(disableBasicAutocrafting&&ʾ.Count!=ʲ.Count)ʾ.RemoveAll(ʼn=>ʼn.BlockDefinition.SubtypeId.Contains("Survival")); if(fillBottles){ ʬ.Sort((ɑ,Ÿ)=>Ÿ.BlockDefinition.TypeIdString.Contains("Oxygen").CompareTo(ɑ.BlockDefinition.TypeIdString.Contains("Oxygen"))); } ʳ.Clear(); bool ɕ; foreach(var ǂ in ʾ){ if(ʳ.Count==0){ ʳ.Add(ǂ); continue; } ɕ=false; foreach(var ɔ in ʳ){ if(ɔ.BlockDefinition.ToString()==ǂ.BlockDefinition.ToString()){ ɕ=true; } } if(!ɕ){ ʳ.Add(ǂ); } } ʅ=false; Runtime.UpdateFrequency=UpdateFrequency.Update10; } void ɓ(List<IMyTerminalBlock>ɒ){ if(ɒ.Count>=2&&ɒ.Count<=500)ɒ.Sort((ɑ,Ÿ)=>í(ɑ).CompareTo(í(Ÿ))); if(!Ǥ())ʃ++; } void ɖ(IMyTerminalBlock d,string ɗ,boolɧ=true){ if(ɧ){ if(d.CustomName.Contains(ɗ))return; d.CustomName+=" "+ɗ; } else{ if(!d.CustomName.Contains(ɗ))return; d.CustomName=d.CustomName.Replace(" "+ɗ,"").Replace(ɗ,"").TrimEnd(' '); } } void ɥ(){ for(int S=0;S<ʩ.Count;S++){ ɖ(ʩ[S],"[No Conveyor]",false); } } void ɤ(){ bool ɣ=false; string ɢ=é("oreContainer"); string ɡ=é("ingotContainer"); string ɠ=é("componentContainer"); string ɦ=é("toolContainer"); string ɟ=é("ammoContainer"); string ɝ=é("bottleContainer"); string ɜ=é("specialContainer"); if(oreContainerKeyword!=ɢ){ ɣ=true; } else if(ingotContainerKeyword!=ɡ){ ɣ=true; } else if(componentContainerKeyword!=ɠ){ ɣ=true; } else if(toolContainerKeyword!=ɦ){ ɣ=true; } else if(ammoContainerKeyword!=ɟ){ ɣ=true; } else if(bottleContainerKeyword!=ɝ){ ɣ=true; } else if(specialContainerKeyword!=ɜ){ ɣ=true; } if(ɣ){ for(int S=0;S<ʩ.Count;S++){ if(ʩ[S].CustomName.Contains(ɢ)){ ʩ[S].CustomName=ʩ[S].CustomName.Replace(ɢ,oreContainerKeyword); } if(ʩ[S].CustomName.Contains(ɡ)){ ʩ[S].CustomName=ʩ[S].CustomName.Replace(ɡ,ingotContainerKeyword); } if(ʩ[S].CustomName.Contains(ɠ)){ ʩ[S].CustomName=ʩ[S].CustomName.Replace(ɠ,componentContainerKeyword); } if(ʩ[S].CustomName.Contains(ɦ)){ ʩ[S].CustomName=ʩ[S].CustomName.Replace(ɦ,toolContainerKeyword); } if(ʩ[S].CustomName.Contains(ɟ)){ ʩ[S].CustomName=ʩ[S].CustomName.Replace(ɟ,ammoContainerKeyword); } if(ʩ[S].CustomName.Contains(ɝ)){ ʩ[S].CustomName=ʩ[S].CustomName.Replace(ɝ,bottleContainerKeyword); } if(ʩ[S].CustomName.Contains(ɜ)){ ʩ[S].CustomName=ʩ[S].CustomName.Replace(ɜ,specialContainerKeyword); } } ç("oreContainer",oreContainerKeyword); ç("ingotContainer",ingotContainerKeyword); ç("componentContainer",componentContainerKeyword); ç("toolContainer",toolContainerKeyword); ç("ammoContainer",ammoContainerKeyword); ç("bottleContainer",bottleContainerKeyword); ç("specialContainer",specialContainerKeyword); } } void ɛ(){ string ɚ=""; foreach(var ə in ʋ){ if(assignOres&&ə==ɂ){ɚ=ɂ; } else if(assignIngots&&ə==Ɂ){ ɚ=Ɂ; } else if(assignComponents&&ə==ɀ){ ɚ=ɀ; }else if(assignTools&&(ə==Ȫ||ə==Ȗ||ə==ȟ||ə==Ȕ)){ ɚ=Ȫ; } else if(assignAmmo&&ə==ȿ){ ɚ=ȿ; } else if(assignBottles&&(ə==Ⱦ||ə==Ƚ)){ ɚ=Ⱦ; } if(ɚ!="")break; } for(int S=0;S<ʼ.Count;S++){ bool Ȼ=false; bool ɘ=false; string ˀ=ʼ[S].CustomName; string ϕ=""; string ϓ=" and "; bool ϒ=false; if(assignOres&&(ʝ.Count==0||ɚ==ɂ)){ if(oresIngotsInOne){ ɘ=true; } else{ ʼ[S].CustomName+=" "+oreContainerKeyword; ʝ.Add(ʼ[S]); ϕ="Ores"; } } else if(assignIngots&&(ʑ.Count==0||ɚ==Ɂ)){ if(oresIngotsInOne){ ɘ=true; } else{ ʼ[S].CustomName+=" "+ingotContainerKeyword; ʑ.Add(ʼ[S]); ϕ="Ingots"; } } else if(assignComponents&&(ʐ.Count==0||ɚ==ɀ)){ ʼ[S].CustomName+=" "+componentContainerKeyword; ʐ.Add(ʼ[S]); ϕ="Components"; } else if(assignTools&&(ʏ.Count==0||ɚ==Ȫ)){ if(toolsAmmoBottlesInOne){ Ȼ=true; } else{ ʼ[S].CustomName+=" "+toolContainerKeyword; ʏ.Add(ʼ[S]);ϕ="Tools"; } } else if(assignAmmo&&(ʎ.Count==0||ɚ==ȿ)){ if(toolsAmmoBottlesInOne){ Ȼ=true; } else{ʼ[S].CustomName+=" "+ammoContainerKeyword; ʎ.Add(ʼ[S]); ϕ="Ammo"; } } else if(assignBottles&&(ʍ.Count==0||ɚ==Ⱦ)){ if(toolsAmmoBottlesInOne){ Ȼ=true; } else{ ʼ[S].CustomName+=" "+bottleContainerKeyword; ʍ.Add(ʼ[S]);ϕ="Bottles"; } } if(ɘ){ if(assignOres){ ʼ[S].CustomName+=" "+oreContainerKeyword; ʝ.Add(ʼ[S]); ϕ="Ores"; ϒ=true; } if(assignIngots){ ʼ[S].CustomName+=" "+ingotContainerKeyword; ʑ.Add(ʼ[S]); ϕ+=(ϒ?ϓ:"")+"Ingots"; } } if(Ȼ){ if(assignTools){ ʼ[S].CustomName+=" "+toolContainerKeyword; ʏ.Add(ʼ[S]); ϕ="Tools"; ϒ=true; } if(assignAmmo){ ʼ[S].CustomName+=" "+ammoContainerKeyword; ʎ.Add(ʼ[S]); ϕ+=(ϒ?ϓ:"")+"Ammo"; ϒ=true; } if(assignBottles){ ʼ[S].CustomName+=" "+bottleContainerKeyword; ʍ.Add(ʼ[S]); ϕ+=(ϒ?ϓ:"")+"Bottles"; } } if(ϕ!=""){ ɚ=""; Ǎ("Assigned '"+ˀ+"' as a new container for type '"+ϕ+"'."); } } ʋ.Clear(); } void ϑ(){ if(unassignOres)ϐ(ʝ,oreContainerKeyword); if(unassignIngots)ϐ(ʑ,ingotContainerKeyword); if(unassignComponents)ϐ(ʐ,componentContainerKeyword); if(unassignTools)ϐ(ʏ,toolContainerKeyword); if(unassignAmmo)ϐ(ʎ,ammoContainerKeyword); if(unassignBottles)ϐ(ʍ,bottleContainerKeyword); } void ϐ(List<IMyTerminalBlock>ď,string Ϗ){ IMyTerminalBlock ώ=null; if(ȥ.TryGetValue(Ϗ,out ώ)){ ȥ.Remove(Ϗ); if(ώ==null)return; if(ώ.GetInventory(0).ItemCount==0){ string ϔ=System.Text.RegularExpressions.Regex.Replace(ώ.CustomName,@"("+Ϗ+@")",""); ϔ=System.Text.RegularExpressions.Regex.Replace(ϔ,@"\(\d+\.?\d*\%\)",""); ϔ=ϔ.Replace(" "," "); ώ.CustomName=ϔ.TrimEnd(' '); ʿ.Remove(ώ); Ǎ("Unassigned '"+ϔ+"' from being a container for type '"+Ϗ+"'."); } return; } if(ď.Count>1){ int ύ=0; foreach(var W in ď){ if(W.CustomName.Contains("[P"))continue; if(W.GetInventory(0).ItemCount==0){ ώ=W; ύ++; } } if(ύ>1){ ȥ[Ϗ]=ώ; } } } void ό(){ string Î,ϋ; List<string>ϊ=newList<string>(); for(int S=0;S<ʩ.Count;S++){ Î=ʩ[S].CustomName; ϋ=Î.ToLower(); ϊ.Clear(); if(ϋ.Contains(oreContainerKeyword.ToLower())&&!Î.Contains(oreContainerKeyword))ϊ.Add(oreContainerKeyword); if(ϋ.Contains(ingotContainerKeyword.ToLower())&&!Î.Contains(ingotContainerKeyword))ϊ.Add(ingotContainerKeyword); if(ϋ.Contains(componentContainerKeyword.ToLower())&&!Î.Contains(componentContainerKeyword))ϊ.Add(componentContainerKeyword); if(ϋ.Contains(toolContainerKeyword.ToLower())&&!Î.Contains(toolContainerKeyword))ϊ.Add(toolContainerKeyword); if(ϋ.Contains(ammoContainerKeyword.ToLower())&&!Î.Contains(ammoContainerKeyword))ϊ.Add(ammoContainerKeyword); if(ϋ.Contains(bottleContainerKeyword.ToLower())&&!Î.Contains(bottleContainerKeyword))ϊ.Add(bottleContainerKeyword); foreach(var ð in lockedContainerKeywords){ if(ϋ.Contains(ð.ToLower())&&!Î.Contains(ð)){ ϊ.Add(ð);break; } } foreach(var ð inhiddenContainerKeywords){ if(ϋ.Contains(ð.ToLower())&&!Î.Contains(ð)){ ϊ.Add(ð);break; } } foreach(var ð in manualMachineKeywords){ if(ϋ.Contains(ð.ToLower())&&!Î.Contains(ð)){ ϊ.Add(ð); break; } } if(ϋ.Contains(specialContainerKeyword.ToLower())&&!Î.Contains(specialContainerKeyword))ϊ.Add(specialContainerKeyword); if(ϋ.Contains(noSortingKeyword.ToLower())&&!Î.Contains(noSortingKeyword))ϊ.Add(noSortingKeyword); if(ϋ.Contains(noIIMKeyword.ToLower())&&!Î.Contains(noIIMKeyword))ϊ.Add(noIIMKeyword); if(ϋ.Contains(autocraftingKeyword.ToLower())&&!Î.Contains(autocraftingKeyword))ϊ.Add(autocraftingKeyword); if(ϋ.Contains(assembleKeyword.ToLower())&&!Î.Contains(assembleKeyword))ϊ.Add(assembleKeyword); if(ϋ.Contains(disassembleKeyword.ToLower())&&!Î.Contains(disassembleKeyword))ϊ.Add(disassembleKeyword); if(ϋ.Contains(learnKeyword.ToLower())&&!Î.Contains(learnKeyword))ϊ.Add(learnKeyword); if(ϋ.Contains(learnManyKeyword.ToLower())&&!Î.Contains(learnManyKeyword))ϊ.Add(learnManyKeyword); if(ϋ.Contains("[p")&&!Î.Contains("[P"))ϊ.Add("[P"); if(ϋ.Contains("[pmax]")&&!Î.Contains("[PMax]"))ϊ.Add("[PMax]"); if(ϋ.Contains("[pmin]")&&!Î.Contains("[PMin]"))ϊ.Add("[PMin]"); foreach(var Ð in ϊ){ ʩ[S].CustomName=ʩ[S].CustomName.ƍ(Ð,Ð); Ǎ("Corrected name\nof: '"+Î+"'\nto: '"+ʩ[S].CustomName+"'"); } } var ź=new List<IMyTerminalBlock>(); GridTerminalSystem.GetBlocksOfType<IMyTextSurfaceProvider>(ź,Ÿ=>Ÿ.IsSameConstructAs(Me)); for(int S=0;S<ź.Count;S++){ Î=ź[S].CustomName;ϋ=Î.ToLower(); ϊ.Clear(); if(ϋ.Contains(mainLCDKeyword.ToLower())&&!Î.Contains(mainLCDKeyword))ϊ.Add(mainLCDKeyword); if(ϋ.Contains(warningsLCDKeyword.ToLower())&&!Î.Contains(warningsLCDKeyword))ϊ.Add(warningsLCDKeyword); if(ϋ.Contains(actionsLCDKeyword.ToLower())&&!Î.Contains(actionsLCDKeyword))ϊ.Add(actionsLCDKeyword); if(ϋ.Contains(performanceLCDKeyword.ToLower())&&!Î.Contains(performanceLCDKeyword))ϊ.Add(performanceLCDKeyword); if(ϋ.Contains(inventoryLCDKeyword.ToLower())&&!Î.Contains(inventoryLCDKeyword))ϊ.Add(inventoryLCDKeyword); foreach(var Ð in ϊ){ ź[S].CustomName=ź[S].CustomName.ƍ(Ð,Ð); Ǎ("Corrected name\nof: '"+Î+"'\nto: '"+ź[S].CustomName+"'"); } } } bool Ϛ(){ ț=Ț[6]+" stage "+(ʒ+1)+"/10"; if(ʒ==0)ϙ(ɂ,ʝ,oreContainerKeyword); if(ʒ==1)ϙ(Ɂ,ʑ,ingotContainerKeyword); if(ʒ==2)ϙ(ɀ,ʐ,componentContainerKeyword); if(ʒ==3)ϙ(Ȫ,ʏ,toolContainerKeyword); if(ʒ==4)ϙ(ȿ,ʎ,ammoContainerKeyword); if(ʒ==5)ϙ(Ⱦ,ʍ,bottleContainerKeyword); if(ʒ==6)ϙ(Ƚ,ʍ,bottleContainerKeyword); if(ʒ==7)ϙ(Ȗ,ʏ,toolContainerKeyword); if(ʒ==8)ϙ(ȟ,ʏ,toolContainerKeyword); if(ʒ==9)ϙ(Ȕ,ʏ,toolContainerKeyword); ʒ++;if(ʒ>9){ ʒ=0; return true; } else{ return false; } } void ϙ(string κ,List<IMyTerminalBlock>Ϙ,string ϛ){ if(Ϙ.Count==0){ Ƽ("There are no containers for type '"+ϛ+"'!\nBuild new ones or add the tag to existing ones!"); ʋ.Add(κ);return; } IMyTerminalBlock N=null; int ϗ=int.MaxValue; for(int S=0;S<Ϙ.Count;S++){ if(κ==Ⱦ&&Ϙ[S].BlockDefinition.TypeIdString.Contains("OxygenTank")&&Ϙ[S].BlockDefinition.SubtypeId.Contains("Hydrogen")){ continue; } else if(κ==Ƚ&&Ϙ[S].BlockDefinition.TypeIdString.Contains("OxygenTank")&&!Ϙ[S].BlockDefinition.SubtypeId.Contains("Hydrogen")){ continue; } var Ø=Ϙ[S].GetInventory(0); if(Ø.ư(inventoryFullBuffer)){ N=Ϙ[S]; ϗ=í(Ϙ[S]); break; } } if(N==null){ Ƽ("All containers for type '"+ϛ+"' are full!\nYou should build or tag new cargo containers!"); ʋ.Add(κ); return; } IMyTerminalBlock σ=null; if(fillBottles&&(κ==Ⱦ||κ==Ƚ)){ σ=ϖ(κ); } for(int S=0;S<ʬ.Count;S++){ if(ʬ[S]==N||(ʬ[S].CustomName.Contains(ϛ)&&í(ʬ[S])<=ϗ)||(κ=="Ore"&&ʬ[S].GetType().ToString().Contains("MyGasGenerator"))){ continue; } if(ʬ[S].CustomName.Contains(ϛ)&&balanceTypeContainers&&!ʬ[S].BlockDefinition.TypeIdString.Contains("OxygenGenerator")&&!ʬ[S].BlockDefinition.TypeIdString.Contains("OxygenTank"))continue; if(σ!=null){ if(ʬ[S]!=σ){ R(κ,ʬ[S],0,σ,0); continue; } } R(κ,ʬ[S],0,N,0); } for(int S=0;S<ʹ.Count;S++){ if(ʹ[S]==N||(ʹ[S].CustomName.Contains(ϛ)&&í(ʹ[S])<=ϗ)){ continue; } R(κ,ʹ[S],1,N,0); } for(int S=0;S<ʶ.Count;S++){ if((ʶ[S].Mode==MyAssemblerMode.Disassembly&&ʶ[S].IsProducing)||ʶ[S]==N||(ʶ[S].CustomName.Contains(ϛ)&&í(ʶ[S])<=ϗ)){ continue; } if(σ!=null){ R(κ,ʶ[S],1,σ,0); continue; } R(κ,ʶ[S],1,N,0); } } IMyTerminalBlock ϖ(string κ){ IMyTerminalBlock σ; if(ʇ!=null&&κ==Ⱦ){ σ=ʇ;ʇ=null; return σ; } if(ʆ!=null&&κ==Ƚ){ σ=ʆ; ʆ=null; return σ; } List<IMyGasTank>υ=new List<IMyGasTank>(Reactors); if(κ==Ⱦ)υ.RemoveAll(ρ=>ρ.BlockDefinition.SubtypeId.Contains("Hydrogen")); if(κ==Ƚ)υ.RemoveAll(ρ=>!ρ.BlockDefinition.SubtypeId.Contains("Hydrogen")); foreach(var π in υ){ if(π.FilledRatio>0){ var ο=π.GetInventory(); if((float)(ο.MaxVolume-ο.CurrentVolume)<0.120)continue; π.AutoRefillBottles=true; λ(π,κ); return π; } } List<IMyGasGenerator>ξ=ʱ.Where(ν=>ν.IsSameConstructAs(Me)&&ν.Enabled==true).ToList(); MyDefinitionId Ġ=MyItemType.MakeOre("Ice"); foreach(var μ in ξ){ if(f(Ġ,μ)>100){ μ.AutoRefill=true; λ(μ,κ); return μ; } } return null; } void λ(IMyTerminalBlock W,string κ){ if(κ==Ⱦ){ ʇ=W; } else{ ʆ=W; } } bool ι(IMyTerminalBlock d){ if(d.GetOwnerFactionTag()!=Me.GetOwnerFactionTag()){if(showOwnerWarnings)Ƽ("'"+d.CustomName+"'\nhas a different owner/faction!\nIt won't be managed by the script!"); return false; } return true; } void θ(){ char η='0'; char ς='0'; char[]ζ={'A','N','T','X'}; char[]τ={'a','d'}; if(sortingPattern.Length==2){ η=sortingPattern[0]; ς=sortingPattern[1]; } ʫ=new List<IMyTerminalBlock>(ʬ) ʫ.AddRange(ʌ); if(enableInternalSorting){ if(η.ToString().IndexOfAny(ζ)<0||ς.ToString().IndexOfAny(τ)<0){ Ƽ("You provided the invalid sorting pattern '"+sortingPattern+"'!\nCan't sort the inventories!"); return; } } else{ ʫ=ʫ.FindAll(S=>S.CustomName.ToLower().Contains("(sort:")); } for(var ƭ=ʂ;ƭ<ʫ.Count;ƭ++){ if(Ǥ())return; if(ʂ>=ʫ.Count-1){ ʂ=0; } else{ ʂ++; } var Ø=ʫ[ƭ].GetInventory(0); var H=new List<MyInventoryItem>(); Ø.GetItems(H); if(H.Count>200)continue; char ω=η; char ψ=ς; string χ=System.Text.RegularExpressions.Regex.Match(ʫ[ƭ].CustomName,@"(\(sort:)(.{2})",System.Text.RegularExpressions.RegexOptions.IgnoreCase).Groups[2].Value;if(χ.Length==2){ η=χ[0];ς=χ[1]; if(η.ToString().IndexOfAny(ζ)<0||ς.ToString().IndexOfAny(τ)<0){ Ƽ("You provided an invalid sorting pattern in\n'"+ʫ[ƭ].CustomName+"'!\nUsing global pattern!"); η=ω; ς=ψ; } } var φ=new List<MyInventoryItem>(); Ø.GetItems(φ); if(η=='A'){ if(ς=='d'){ φ.Sort((ɑ,Ÿ)=>Ÿ.Amount.ToIntSafe().CompareTo(ɑ.Amount.ToIntSafe())); } else{ φ.Sort((ɑ,Ÿ)=>ɑ.Amount.ToIntSafe().CompareTo(Ÿ.Amount.ToIntSafe())); } } else if(η=='N'){ if(ς=='d'){ φ.Sort((ɑ,Ÿ)=>Ÿ.Type.SubtypeId.ToString().CompareTo(ɑ.Type.SubtypeId.ToString())); } else{ φ.Sort((ɑ,Ÿ)=>ɑ.Type.SubtypeId.ToString().CompareTo(Ÿ.Type.SubtypeId.ToString())); } } else if(η=='T'){ if(ς=='d'){ φ.Sort((ɑ,Ÿ)=>Ÿ.Type.ToString().CompareTo(ɑ.Type.ToString())); } else{ φ.Sort((ɑ,Ÿ)=>ɑ.Type.ToString().CompareTo(Ÿ.Type.ToString())); } } else if(η=='X'){ if(ς=='d'){ φ.Sort((ɑ,Ÿ)=>(Ÿ.Type.TypeId.ToString()+Ÿ.Amount.ToIntSafe().ToString(@"000000000")).CompareTo((ɑ.Type.TypeId.ToString()+ɑ.Amount.ToIntSafe().ToString(@"000000000")))); } else{ φ.Sort((ɑ,Ÿ)=>(ɑ.Type.TypeId.ToString()+ɑ.Amount.ToIntSafe().ToString(@"000000000")).CompareTo((Ÿ.Type.TypeId.ToString()+Ÿ.Amount.ToIntSafe().ToString(@"000000000")))); } } if(φ.SequenceEqual(H,new Ŷ()))continue; foreach(var Ð in φ){ string ϯ=Ð.ToString(); for(int S=0;S<H.Count;S++){ if(H[S].ToString()==ϯ){ Ø.TransferItemTo(Ø,S,H.Count,false); H.Clear(); Ø.GetItems(H); break; } } } η=ω; ς=ψ; } } void Ϯ(){ for(int ƭ=ʔ;ƭ<ʌ.Count;ƭ++){ if(Ǥ())return; ʔ++; ù(ʌ[ƭ]); int q=0; if(ʌ[ƭ].BlockDefinition.SubtypeId.Contains("Assembler")){ IMyAssembler ǂ=ʌ[ƭ]as IMyAssembler; if(ǂ.Mode==MyAssemblerMode.Disassembly)q=1; } List<string>Ϭ=new List<string>(); double ϫ,Ϫ,ˇ,ϩ; MyDefinitionId F; string ϭ="",A=""; foreach(var Ð in Ȧ){ if(!MyDefinitionId.TryParse(Ƀ+Ð.Key,out F))continue; Ϫ=f(F,ʌ[ƭ],q);ϭ=Ð.Value.ToLower(); double.TryParse(System.Text.RegularExpressions.Regex.Match(ϭ,@"\d+").Value,out ϫ); ˇ=0; ϩ=0; if(ϭ.Contains("all")){ A="all"; ϫ=int.MaxValue; } else if(ϭ.Contains("m")){ A="m"; } else if(ϭ.Contains("l")||ϭ.Contains("-")){ A="l"; } ˇ=ϫ-Ϫ; if(ˇ>=1&&A!="l"){ var Ø=ʌ[ƭ].GetInventory(q); if(!Ø.ư(inventoryFullBuffer))break; IMyTerminalBlock P=null; if(allowSpecialSteal){ P=Z(F,true,ʌ[ƭ]); } else{ P=Z(F); } if(P!=null){ ϩ=R(F.ToString(),P,0,ʌ[ƭ],q,ˇ,true); } if(ˇ>ϩ&&A!="all"){ Ϭ.Add(ˇ-ϩ+" "+F.SubtypeName); } } elseif(ˇ<0&&A!="m"){ IMyTerminalBlock N=V(ʌ[ƭ],ʼ); if(N!=null)R(F.ToString(),ʌ[ƭ],q,N,0,Math.Abs(ˇ),true); } } if(Ϭ.Count>0){ Ƽ(ʌ[ƭ].CustomName+"\nis missing the following items to match its quota:\n"+String.Join(", ",Ϭ)); } } ʔ=0; } void ϴ(List<IMyTerminalBlock>ď){ foreach(var W in ď){ string ϳ=W.CustomName; string ϔ;var ϵ=System.Text.RegularExpressions.Regex.Match(ϳ,@"\(\d+\.?\d*\%\)").Value;if(ϵ!=""){ ϔ=ϳ.Replace(ϵ,"").TrimEnd(' '); } else{ ϔ=ϳ; } var Ø=W.GetInventory(0); string dz=((float)Ø.CurrentVolume).ƙ((float)Ø.MaxVolume); if(showFillLevel){ ϔ+=" ("+dz+")"; ϔ=ϔ.Replace(" "," "); } if(ϔ!=ϳ)W.CustomName=ϔ; } } StringBuilder ϲ(){ if(ʮ.Count>1){ string ϱ=@"("+autocraftingKeyword+@" *)(\d*)"; ʮ.Sort((ɑ,Ÿ)=>System.Text.RegularExpressions.Regex.Match(ɑ.CustomName,ϱ).Groups[2].Value.CompareTo(System.Text.RegularExpressions.Regex.Match(Ÿ.CustomName,ϱ).Groups[2].Value)); } StringBuilder Ő=new StringBuilder(); if(!ʮ[0].GetText().Contains(ɏ)){ ʮ[0].Font=defaultFont;ʮ[0].FontSize=defaultFontSize; ʮ[0].TextPadding=defaultPadding; } foreach(var È in ʮ){ Ő.Append(È.GetText()+"\n"); È.WritePublicTitle("Craft item manually once to show up here"); È.Font=ʮ[0].Font; È.FontSize=ʮ[0].FontSize; È.TextPadding=ʮ[0].TextPadding; È.Alignment=TextAlignment.LEFT; È.ContentType=ContentType.TEXT_AND_IMAGE; } var ϰ=new List<string>(Ő.ToString().Split('\n')); var Ά=new List<string>();var Ϩ=new HashSet<string>(); string Ϝ; foreach(var Ê in ϰ){ if(Ê.IndexOfAny(Ɍ)<=0)continue; Ϝ=Ê.Remove(Ê.IndexOf(" ")); if(!Ϩ.Contains(Ϝ)){ Ά.Add(Ê);Ϩ.Add(Ϝ); } } List<string>Ü=ʮ[0].CustomData.Split('\n').ToList(); foreach(var C in ʭ){ bool ϡ=false; if(Ϩ.Contains(C)){ continue; } foreach(varÊ in Ü){ if(!Ê.StartsWith("-"))continue; string Ϡ=""; try{ if(Ê.Contains("=")){ Ϡ=Ê.Substring(1,Ê.IndexOf("=")-1); } else{ Ϡ=Ê.Substring(1); } } catch{ continue; } if(Ϡ==C){ ϡ=true; break; } } if(!ϡ){ MyDefinitionId F=Ƕ(C); bool ͼ; MyDefinitionId á=Ǹ(F,out ͼ); if(!ͼ&&!showUnlearnedItems)continue; double Ȅ=Math.Ceiling(f(F)); Ά.Add(C+" "+Ȅ+" = "+Ȅ+defaultModifier); } } foreach(var Ê in Ü){ if(!Ê.StartsWith("-"))continue; if(Ê.Contains("=")){ Ά.Add(Ê); } } StringBuilder Ƨ=new StringBuilder(); try{ IOrderedEnumerable<string>ϟ; ϟ=Ά.OrderBy(ɑ=>ɑ); bool Ϟ; string ϝ,C,Ϣ; foreach(var Ê in ϟ){ Ϟ=false; if(Ê.StartsWith("-")){ C=Ê.Remove(Ê.IndexOf("=")).TrimStart('-'); ϝ="-"; } else{ C=Ê.Remove(Ê.IndexOf(" ")); ϝ=""; } Ϣ=Ê.Replace(ϝ+C,""); foreach(var Ð in ʭ){ if(Ð==C){ Ϟ=true; break; } } if(Ϟ)Ƨ.Append(ϝ+C+Ϣ+"\n"); } } catch{ } return Ƨ; } void ϧ(StringBuilder Ő){ if(Ő.Length==0){ Ő.Append("Autocrafting error!\n\nNo items for crafting available!\n\nIf you hid all items, check the custom data of the first autocrafting panel and reenable some of them.\n\nOtherwise, store or build new items manually!"); Ő=ʮ[0].Ū(Ő,2,false); ʮ[0].WriteText(Ő); return; } var ņ=Ő.ToString().TrimEnd('\n').Split('\n'); int Ņ=ņ.Length; int ń=0; floatϦ=0; foreach(var È in ʮ){ float Ɖ=È.Ś(); int Ń=È.Ş(); int ł=0; List<string>Ƨ=new List<string>(); if(È==ʮ[0]||headerOnEveryScreen){ string ϥ=ɏ; if(headerOnEveryScreen&&ʮ.Count>1){ ϥ+=" "+(ʮ.IndexOf(È)+1)+"/"+ʮ.Count; try{ ϥ+=" ["+ņ[ń][0]+"-#]"; } catch{ ϥ+=" [Empty]"; } } Ƨ.Add(ϥ); Ƨ.Add(È.Ř('=',È.Ţ(ϥ)).ToString()+"\n"); string Ϥ="Component "; string ϣ="Current | Wanted "; Ϧ=È.Ţ("Wanted "); string ǟ=È.Ř(' ',Ɖ-È.Ţ(Ϥ)-È.Ţ(ϣ)).ToString(); Ƨ.Add(Ϥ+ǟ+ϣ+"\n"); ł=5; } while((ń<Ņ&&ł<Ń)||(È==ʮ[ʮ.Count-1]&&ń<Ņ)){ var Ê=ņ[ń].Split(' '); Ê[0]+=" "; Ê[1]=Ê[1].Replace('$',' '); string ǟ=È.Ř(' ',Ɖ-È.Ţ(Ê[0])-È.Ţ(Ê[1])-Ϧ).ToString(); string ε=Ê[0]+ǟ+Ê[1]+Ê[2]; Ƨ.Add(ε); ń++; ł++; } if(headerOnEveryScreen&&ʮ.Count>1){ Ƨ[0]=Ƨ[0].Replace('#',ņ[ń-1][0]); } È.WriteText(String.Join("\n",Ƨ)); } if(showAutocraftingModifiers){ string Ή="\n\n---\n\nModifiers (append after wanted amount):\n"+"'A' - Assemble only\n"+"'D' - Disassemble only\n"+"'P' - Priority (always craft first)\n"+"'H' - Hide (manage in custom data)\n"+"'I' - Ignore (don't manage and hide)\n"+"'Y#' - Yield modifier. Set # to the itemamount, one craft yields"; ʮ[ʮ.Count-1].WriteText(Ή,true); } } void ː(){ ʮ.Clear(); GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(ʮ,È=>È.IsSameConstructAs(Me)&&È.CustomName.Contains(autocraftingKeyword)); if(ʮ.Count==0)return; if(ʾ.Count==0){ Ƽ("No usable assemblers found!\nBuild or enable assemblers to enable autocrafting!"); return; } if(!enableAutocrafting&&!enableAutodisassembling)return; Π(); List<MyDefinitionId>Έ=new List<MyDefinitionId>(); var Ά=ϲ().ToString().TrimEnd('\n').Split('\n');StringBuilder Ƨ=new StringBuilder(); foreach(var Ê in Ά){ string C=""; bool ͽ=true; if(Ê.StartsWith("-")){ ͽ=false; try{ C=Ê.Substring(1,Ê.IndexOf("=")-1); } catch{ continue; } } else{ try{ C=Ê.Substring(0,Ê.IndexOf(" ")); } catch{ continue; } } MyDefinitionId F=Ƕ(C); if(F==null)continue; bool ͼ; MyDefinitionId á=Ǹ(F,out ͼ); if(!ͼ&&!showUnlearnedItems)continue; double ͺ=Math.Ceiling(f(F)); string ͷ=Ê.Substring(Ê.IndexOfAny(Ɍ)+1).ToLower().Replace(" ",""); double Ͷ=0; int ʹ=1; double.TryParse(System.Text.RegularExpressions.Regex.Match(ͷ,@"\d+").Value,out Ͷ); string ͳ=ͺ.ToString(); string Ͳ=Ͷ.ToString(); string ͻ=""; bool ï=false; if(ͷ.Contains("h")&&ͽ){ if(!ʮ[0].CustomData.StartsWith(ɍ))ʮ[0].CustomData=ɍ; ʮ[0].CustomData+="\n-"+C+"="+ͷ.Replace("h","").Replace(" ","").ToUpper(); continue; } else if(ͷ.Contains("i")&&ͽ){ if(!ʮ[0].CustomData.StartsWith(ɍ))ʮ[0].CustomData=ɍ; ʮ[0].CustomData+="\n-"+C; continue; } if(ͷ.Contains("a")){ if(ͺ>Ͷ)Ͷ=ͺ; ͻ+="A"; } if(ͷ.Contains("d")){ if(ͺ<Ͷ)Ͷ=ͺ; ͻ+="D"; } if(ͷ.Contains("p")){ ï=true; ͻ+="P"; } if(ͷ.Contains("y")){ int.TryParse(System.Text.RegularExpressions.Regex.Match(ͷ,@"y\d+").Value.Replace("y",""),out ʹ); if(ʹ==0)ʹ=1; ͻ+="Y"+ʹ; } ǀ(F,Ͷ); double Α=Math.Abs((Ͷ-ͺ)/ʹ); if(ʹ!=1)Α=Math.Floor(Α); double Θ=ǁ(á); if(ͺ>=Ͷ+Ͷ*assembleMargin&&Θ>0&&ƿ(á)>0){ Σ(á); ƾ(á,0); Θ=0; Ǎ("Removed '"+F.SubtypeId.ToString()+"' from the assembling queue."); } if(ͺ<=Ͷ-Ͷ*disassembleMargin&&Θ>0&&ƿ(á)<0){ Σ(á); ƾ(á,0); Θ=0; Ǎ("Removed '"+F.SubtypeId.ToString()+"' from the disassembling queue."); } string ĥ="";if(Θ>0||Α>0){ if((enableAutodisassembling||ͷ.Contains("d"))&&ͺ>Ͷ+Ͷ*disassembleMargin){ ƾ(á,-1); ĥ="$[D:"; } else if(enableAutocrafting&&ͺ<Ͷ-Ͷ*assembleMargin){ ƾ(á,1); ĥ="$[A:"; } if(ĥ!=""){ if(Θ==0){ ĥ+="Wait]"; } else{ ĥ+=Math.Round(Θ)+"]"; } } } else{ ƾ(á,0); } if(showUnlearnedItems&&!ͼ)ĥ="$[NoBP]"; if(ï){ Έ.Add(á); } string Ζ="$=$ "; if(ͺ>Ͷ)Ζ="$>$ "; if(ͺ<Ͷ)Ζ="$<$ "; if(ͽ)Ƨ.Append(C+" "+ͳ+ĥ+Ζ+Ͳ+ͻ+"\n"); if(ĥ.Contains("[D:Wait]")){ Ι(á,Α); } else if(ĥ.Contains("[A:Wait]")){ Λ(á,Α,ï); Ǎ("Queued "+Α+" '"+F.SubtypeId.ToString()+"' in the assemblers."); } } Ρ(Έ); ϧ(Ƨ); } void Ε(){ if(Refineries.Count>0)return; MyDefinitionId ˠ=MyItemType.MakeOre("Stone"); MyDefinitionId á=MyDefinitionId.Parse(ȓ+"Position0010_StoneOreToIngotBasic"); double Δ=f(ˠ); if(Δ>0){ double Γ=Math.Floor(Δ/100/ʲ.Count); if(Γ<1)return; foreach(var Η in ʲ){ if(Η.CanUseBlueprint(á)&&Η.IsQueueEmpty){ Η.AddQueueItem(á,Γ); Ǎ("Queued "+Γ+" ingot crafts in "+Η.CustomName+"."); } } } } void Β(){ if(ʧ==0)ʧ+=ΐ(ʝ,ɂ,true,true); if(ʧ==1)ʧ+=ΐ(ʑ,Ɂ,true,true); if(ʧ==2)ʧ+=ΐ(ʐ,ɀ,true,true); if(ʧ==3)ʧ+=ΐ(ʏ,Ȫ,true,true); if(ʧ==4)ʧ+=ΐ(ʎ,ȿ,true,true); if(ʧ==5)ʧ+=ΐ(ʍ,"ContainerObject",true,true); ʧ++; if(ʧ>5)ʧ=0; }
623ed5415a6898af217312782bcd6338
{ "intermediate": 0.31845811009407043, "beginner": 0.3622826039791107, "expert": 0.31925928592681885 }
45,846
"ладно, можете не читать то что я написал выше" исправь ошибки
0e786333a3da45d710896da3bc366648
{ "intermediate": 0.2769802212715149, "beginner": 0.3319375216960907, "expert": 0.3910822868347168 }
45,847
how to loggin in poython. write example
63a3526b3b40e3f4e98fdbb0e64abb3e
{ "intermediate": 0.3178587257862091, "beginner": 0.26528504490852356, "expert": 0.41685622930526733 }
45,848
I want to make a ping pong 2 players game on godot for my phone
bd6911345c1a148c522537b501ab51bc
{ "intermediate": 0.32938215136528015, "beginner": 0.3069530129432678, "expert": 0.36366477608680725 }
45,849
Hi, are you familiar with Space Engineers mods and scripts?
27daba58c61642069d847e6452c253b6
{ "intermediate": 0.2554776966571808, "beginner": 0.542011559009552, "expert": 0.2025107443332672 }
45,850
as we startet earlier, please translate this code snippet for me of a C# code of a space engineers script to a ASCII-friendly translation and consistency
fbc3ba6e64a0f6038fc182920915f7ff
{ "intermediate": 0.32285526394844055, "beginner": 0.4022616147994995, "expert": 0.2748831510543823 }
45,851
please translate this code snippet of C# of a space engineers script to hold ASCII-friendly variables and be consinstent to the rest of this script. Basis if this script is Isy's Inventory management script. void ː(){ ʮ.Clear(); GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(ʮ,È=>È.IsSameConstructAs(Me)&&È.CustomName.Contains(autocraftingKeyword)); if(ʮ.Count==0)return; if(ʾ.Count==0){ Ƽ("No usable assemblers found!\nBuild or enable assemblers to enable autocrafting!"); return; } if(!enableAutocrafting&&!enableAutodisassembling)return; Π(); List<MyDefinitionId>Έ=new List<MyDefinitionId>(); var Ά=ϲ().ToString().TrimEnd('\n').Split('\n');StringBuilder Ƨ=new StringBuilder(); foreach(var Ê in Ά){ string C=""; bool ͽ=true; if(Ê.StartsWith("-")){ ͽ=false; try{ C=Ê.Substring(1,Ê.IndexOf("=")-1); } catch{ continue; } } else{ try{ C=Ê.Substring(0,Ê.IndexOf(" ")); } catch{ continue; } } MyDefinitionId F=Ƕ(C); if(F==null)continue; bool ͼ; MyDefinitionId á=Ǹ(F,out ͼ); if(!ͼ&&!showUnlearnedItems)continue; double ͺ=Math.Ceiling(f(F)); string ͷ=Ê.Substring(Ê.IndexOfAny(Ɍ)+1).ToLower().Replace(" ",""); double Ͷ=0; int ʹ=1; double.TryParse(System.Text.RegularExpressions.Regex.Match(ͷ,@"\d+").Value,out Ͷ); string ͳ=ͺ.ToString(); string Ͳ=Ͷ.ToString(); string ͻ=""; bool ï=false; if(ͷ.Contains("h")&&ͽ){ if(!ʮ[0].CustomData.StartsWith(ɍ))ʮ[0].CustomData=ɍ; ʮ[0].CustomData+="\n-"+C+"="+ͷ.Replace("h","").Replace(" ","").ToUpper(); continue; } else if(ͷ.Contains("i")&&ͽ){ if(!ʮ[0].CustomData.StartsWith(ɍ))ʮ[0].CustomData=ɍ; ʮ[0].CustomData+="\n-"+C; continue; } if(ͷ.Contains("a")){ if(ͺ>Ͷ)Ͷ=ͺ; ͻ+="A"; } if(ͷ.Contains("d")){ if(ͺ<Ͷ)Ͷ=ͺ; ͻ+="D"; } if(ͷ.Contains("p")){ ï=true; ͻ+="P"; } if(ͷ.Contains("y")){ int.TryParse(System.Text.RegularExpressions.Regex.Match(ͷ,@"y\d+").Value.Replace("y",""),out ʹ); if(ʹ==0)ʹ=1; ͻ+="Y"+ʹ; } ǀ(F,Ͷ); double Α=Math.Abs((Ͷ-ͺ)/ʹ); if(ʹ!=1)Α=Math.Floor(Α); double Θ=ǁ(á); if(ͺ>=Ͷ+Ͷ*assembleMargin&&Θ>0&&ƿ(á)>0){ Σ(á); ƾ(á,0); Θ=0; Ǎ("Removed '"+F.SubtypeId.ToString()+"' from the assembling queue."); } if(ͺ<=Ͷ-Ͷ*disassembleMargin&&Θ>0&&ƿ(á)<0){ Σ(á); ƾ(á,0); Θ=0; Ǎ("Removed '"+F.SubtypeId.ToString()+"' from the disassembling queue."); } string ĥ="";if(Θ>0||Α>0){ if((enableAutodisassembling||ͷ.Contains("d"))&&ͺ>Ͷ+Ͷ*disassembleMargin){ ƾ(á,-1); ĥ="$[D:"; } else if(enableAutocrafting&&ͺ<Ͷ-Ͷ*assembleMargin){ ƾ(á,1); ĥ="$[A:"; } if(ĥ!=""){ if(Θ==0){ ĥ+="Wait]"; } else{ ĥ+=Math.Round(Θ)+"]"; } } } else{ ƾ(á,0); } if(showUnlearnedItems&&!ͼ)ĥ="$[NoBP]"; if(ï){ Έ.Add(á); } string Ζ="$=$ "; if(ͺ>Ͷ)Ζ="$>$ "; if(ͺ<Ͷ)Ζ="$<$ "; if(ͽ)Ƨ.Append(C+" "+ͳ+ĥ+Ζ+Ͳ+ͻ+"\n"); if(ĥ.Contains("[D:Wait]")){ Ι(á,Α); } else if(ĥ.Contains("[A:Wait]")){ Λ(á,Α,ï); Ǎ("Queued "+Α+" '"+F.SubtypeId.ToString()+"' in the assemblers."); } } Ρ(Έ); ϧ(Ƨ); } void Ε(){ if(Refineries.Count>0)return; MyDefinitionId ˠ=MyItemType.MakeOre("Stone"); MyDefinitionId á=MyDefinitionId.Parse(ȓ+"Position0010_StoneOreToIngotBasic"); double Δ=f(ˠ); if(Δ>0){ double Γ=Math.Floor(Δ/100/ʲ.Count); if(Γ<1)return; foreach(var Η in ʲ){ if(Η.CanUseBlueprint(á)&&Η.IsQueueEmpty){ Η.AddQueueItem(á,Γ); Ǎ("Queued "+Γ+" ingot crafts in "+Η.CustomName+"."); } } } } void Β(){ if(ʧ==0)ʧ+=ΐ(ʝ,ɂ,true,true); if(ʧ==1)ʧ+=ΐ(ʑ,Ɂ,true,true); if(ʧ==2)ʧ+=ΐ(ʐ,ɀ,true,true); if(ʧ==3)ʧ+=ΐ(ʏ,Ȫ,true,true); if(ʧ==4)ʧ+=ΐ(ʎ,ȿ,true,true); if(ʧ==5)ʧ+=ΐ(ʍ,"ContainerObject",true,true); ʧ++; if(ʧ>5)ʧ=0; } int ΐ(List<IMyTerminalBlock>ɒ,string Ώ="",bool Ύ=false,bool Ό=false){ if(Ύ)ɒ.RemoveAll(ſ=>ſ.InventoryCount==2||ſ.BlockDefinition.TypeIdString.Contains("OxygenGenerator")||ſ.BlockDefinition.TypeIdString.Contains("OxygenTank")); if(Ό)ɒ.RemoveAll(S=>!S.CubeGrid.IsSameConstructAs(Me.CubeGrid)); if(ɒ.Count<2){ return 1; } Dictionary<MyItemType,double>Ί=new Dictionary<MyItemType,double>(); for(int S=0;S<ɒ.Count;S++){ var H=new List<MyInventoryItem>(); ɒ[S].GetInventory(0).GetItems(H); foreach(var Ð in H){ if(!Ð.Type.TypeId.ToString().Contains(Ώ))continue; MyItemType F=Ð.Type; if(Ί.ContainsKey(F)){ Ί[F]+=(double)Ð.Amount; } else{ Ί[F]=(double)Ð.Amount; } } } Dictionary<MyItemType,double>ˍ=new Dictionary<MyItemType,double>(); foreach(var Ð in Ί){ ˍ[Ð.Key]=(int)(Ð.Value/ɒ.Count); } for(int ˌ=0;ˌ<ɒ.Count;ˌ++){ if(Ǥ())return 0; var ˋ=new List<MyInventoryItem>(); ɒ[ˌ].GetInventory(0).GetItems(ˋ); Dictionary<MyItemType,double>ˊ=new Dictionary<MyItemType,double>(); foreach(var Ð in ˋ){ MyItemType F=Ð.Type; if(ˊ.ContainsKey(F)){ ˊ[F]+=(double)Ð.Amount; } else{ ˊ[F]=(double)Ð.Amount; } } double ı=0; foreach(var Ð in Ί){ ˊ.TryGetValue(Ð.Key,out ı); double ˉ=ˍ[Ð.Key]; if(ı<=ˉ+1)continue; for(int ˈ=0;ˈ<ɒ.Count;ˈ++){ if(ɒ[ˌ]==ɒ[ˈ])continue; double ĭ=f(Ð.Key,ɒ[ˈ]); if(ĭ>=ˉ-1)continue; double ˇ=ˉ-ĭ; if(ˇ>ı-ˉ)ˇ=ı-ˉ; if(ˇ>0){ ı-=R(Ð.Key.ToString(),ɒ[ˌ],0,ɒ[ˈ],0,ˇ,true); if(ı.ƚ(ˉ-1,ˉ+1))break; } } } } return Ǥ()?0:1; }
7b2ddbc111ff62c22936ea9d162cf898
{ "intermediate": 0.29485687613487244, "beginner": 0.3894349932670593, "expert": 0.3157081604003906 }
45,852
please translate this C# space engineers script snippet to have ASCII-friendly variables and to be consinstent with the rest of the script: void ː(){ ʮ.Clear(); GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(ʮ,È=>È.IsSameConstructAs(Me)&&È.CustomName.Contains(autocraftingKeyword)); if(ʮ.Count==0)return; if(ʾ.Count==0){ Ƽ("No usable assemblers found!\nBuild or enable assemblers to enable autocrafting!"); return; } if(!enableAutocrafting&&!enableAutodisassembling)return; Π(); List<MyDefinitionId>Έ=new List<MyDefinitionId>(); var Ά=ϲ().ToString().TrimEnd('\n').Split('\n');StringBuilder Ƨ=new StringBuilder(); foreach(var Ê in Ά){ string C=""; bool ͽ=true; if(Ê.StartsWith("-")){ ͽ=false; try{ C=Ê.Substring(1,Ê.IndexOf("=")-1); } catch{ continue; } } else{ try{ C=Ê.Substring(0,Ê.IndexOf(" ")); } catch{ continue; } } MyDefinitionId F=Ƕ(C); if(F==null)continue; bool ͼ; MyDefinitionId á=Ǹ(F,out ͼ); if(!ͼ&&!showUnlearnedItems)continue; double ͺ=Math.Ceiling(f(F)); string ͷ=Ê.Substring(Ê.IndexOfAny(Ɍ)+1).ToLower().Replace(" ",""); double Ͷ=0; int ʹ=1; double.TryParse(System.Text.RegularExpressions.Regex.Match(ͷ,@"\d+").Value,out Ͷ); string ͳ=ͺ.ToString(); string Ͳ=Ͷ.ToString(); string ͻ=""; bool ï=false; if(ͷ.Contains("h")&&ͽ){ if(!ʮ[0].CustomData.StartsWith(ɍ))ʮ[0].CustomData=ɍ; ʮ[0].CustomData+="\n-"+C+"="+ͷ.Replace("h","").Replace(" ","").ToUpper(); continue; } else if(ͷ.Contains("i")&&ͽ){ if(!ʮ[0].CustomData.StartsWith(ɍ))ʮ[0].CustomData=ɍ; ʮ[0].CustomData+="\n-"+C; continue; } if(ͷ.Contains("a")){ if(ͺ>Ͷ)Ͷ=ͺ; ͻ+="A"; } if(ͷ.Contains("d")){ if(ͺ<Ͷ)Ͷ=ͺ; ͻ+="D"; } if(ͷ.Contains("p")){ ï=true; ͻ+="P"; } if(ͷ.Contains("y")){ int.TryParse(System.Text.RegularExpressions.Regex.Match(ͷ,@"y\d+").Value.Replace("y",""),out ʹ); if(ʹ==0)ʹ=1; ͻ+="Y"+ʹ; } ǀ(F,Ͷ); double Α=Math.Abs((Ͷ-ͺ)/ʹ); if(ʹ!=1)Α=Math.Floor(Α); double Θ=ǁ(á); if(ͺ>=Ͷ+Ͷ*assembleMargin&&Θ>0&&ƿ(á)>0){ Σ(á); ƾ(á,0); Θ=0; Ǎ("Removed '"+F.SubtypeId.ToString()+"' from the assembling queue."); } if(ͺ<=Ͷ-Ͷ*disassembleMargin&&Θ>0&&ƿ(á)<0){ Σ(á); ƾ(á,0); Θ=0; Ǎ("Removed '"+F.SubtypeId.ToString()+"' from the disassembling queue."); } string ĥ="";if(Θ>0||Α>0){ if((enableAutodisassembling||ͷ.Contains("d"))&&ͺ>Ͷ+Ͷ*disassembleMargin){ ƾ(á,-1); ĥ="$[D:"; } else if(enableAutocrafting&&ͺ<Ͷ-Ͷ*assembleMargin){ ƾ(á,1); ĥ="$[A:"; } if(ĥ!=""){ if(Θ==0){ ĥ+="Wait]"; } else{ ĥ+=Math.Round(Θ)+"]"; } } } else{ ƾ(á,0); } if(showUnlearnedItems&&!ͼ)ĥ="$[NoBP]"; if(ï){ Έ.Add(á); } string Ζ="$=$ "; if(ͺ>Ͷ)Ζ="$>$ "; if(ͺ<Ͷ)Ζ="$<$ "; if(ͽ)Ƨ.Append(C+" "+ͳ+ĥ+Ζ+Ͳ+ͻ+"\n"); if(ĥ.Contains("[D:Wait]")){ Ι(á,Α); } else if(ĥ.Contains("[A:Wait]")){ Λ(á,Α,ï); Ǎ("Queued "+Α+" '"+F.SubtypeId.ToString()+"' in the assemblers."); } } Ρ(Έ); ϧ(Ƨ); } void Ε(){ if(Refineries.Count>0)return; MyDefinitionId ˠ=MyItemType.MakeOre("Stone"); MyDefinitionId á=MyDefinitionId.Parse(ȓ+"Position0010_StoneOreToIngotBasic"); double Δ=f(ˠ); if(Δ>0){ double Γ=Math.Floor(Δ/100/ʲ.Count); if(Γ<1)return; foreach(var Η in ʲ){ if(Η.CanUseBlueprint(á)&&Η.IsQueueEmpty){ Η.AddQueueItem(á,Γ); Ǎ("Queued "+Γ+" ingot crafts in "+Η.CustomName+"."); } } } } void Β(){ if(ʧ==0)ʧ+=ΐ(ʝ,ɂ,true,true); if(ʧ==1)ʧ+=ΐ(ʑ,Ɂ,true,true); if(ʧ==2)ʧ+=ΐ(ʐ,ɀ,true,true); if(ʧ==3)ʧ+=ΐ(ʏ,Ȫ,true,true); if(ʧ==4)ʧ+=ΐ(ʎ,ȿ,true,true); if(ʧ==5)ʧ+=ΐ(ʍ,"ContainerObject",true,true); ʧ++; if(ʧ>5)ʧ=0; }
c84888ccc46ca8b1233e7867007b1af1
{ "intermediate": 0.3767688274383545, "beginner": 0.47712603211402893, "expert": 0.1461051106452942 }
45,853
void Β(){ if(ʧ==0)ʧ+=ΐ(ʝ,ɂ,true,true); if(ʧ==1)ʧ+=ΐ(ʑ,Ɂ,true,true); if(ʧ==2)ʧ+=ΐ(ʐ,ɀ,true,true); if(ʧ==3)ʧ+=ΐ(ʏ,Ȫ,true,true); if(ʧ==4)ʧ+=ΐ(ʎ,ȿ,true,true); if(ʧ==5)ʧ+=ΐ(ʍ,"ContainerObject",true,true); ʧ++; if(ʧ>5)ʧ=0; }
4b0a597ec8b3c9b4345b8327873897fc
{ "intermediate": 0.35011014342308044, "beginner": 0.4488348066806793, "expert": 0.20105507969856262 }
45,854
An ad agency is interested in keeping track of their clients a little more easily. Help them out by creating two ArrayLists: Create an ArrayList called companyName that stores an ArrayList of all the company names. Create an Integer ArrayList called contractValue that stores the value of the contract that the ad agency has with its clients. import java.util.ArrayList; public class Agency { public static void main(String[] args) { //Initialize your ArrayLists here! } }
21011e8be8fa84ee27011262a6473f61
{ "intermediate": 0.40268033742904663, "beginner": 0.34226593375205994, "expert": 0.25505372881889343 }
45,855
you have this pandas dataframe: t_gene helper transcripts relation class pred q_gene 0 ENSG00000048740 ENST00000632728 ENST00000632728.32 o2o I 0.996369 reg_14654 1 ENSG00000048740 ENST00000631816 ENST00000631816.32 o2o I 0.996369 reg_14654 2 ENSG00000048740 ENST00000416382 ENST00000416382.32 o2o I 0.996369 reg_14654 3 ENSG00000048740 ENST00000609692 ENST00000609692.32 o2o I 0.996369 reg_14654 4 ENSG00000048740 ENST00000608830 ENST00000608830.32 o2o I 0.996369 reg_14654 ... ... ... ... ... ... ... ... 104286 ENSG00000233087 ENST00000623617 ENST00000623617.1590 NaN M -1.000000 NaN 104287 ENSG00000178201 ENST00000321039 ENST00000321039.5698 NaN M -1.000000 NaN 104288 ENSG00000196268 ENST00000599461 ENST00000599461.52021 NaN M -1.000000 NaN 104289 ENSG00000196268 ENST00000599461 ENST00000599461.78626 NaN M -1.000000 NaN 104290 ENSG00000169246 ENST00000542817 ENST00000542817.7870 NaN M -1.000000 NaN I want to group by "helper" and check if ANY value in the "pred" column surpasses a given threshold (namely THRESHOLD). If any number in "pred" for any name in "helper" surpasses that threshold, I want to drop all the rows that contain that "name" in "helper".
a7ca16e57547a938e73a5b598783559a
{ "intermediate": 0.2663925290107727, "beginner": 0.43914932012557983, "expert": 0.2944580912590027 }
45,856
A car company wants to keep a list of all the cars that they have in stock. The company has created a ClassicCar class that stores important information about each of their cars. Initialize an ArrayList called garage that stores each ClassicCar that the company has in stock. import java.util.ArrayList; public class CarTracker { public static void main(String[] args) { //Initialize your ArrayList here: } }
2d0084df365f91adf9b8c2b7e8989095
{ "intermediate": 0.42779016494750977, "beginner": 0.34162992238998413, "expert": 0.2305799126625061 }
45,857
A car company wants to keep a list of all the cars that they have in stock. The company has created a ClassicCar class that stores important information about each of their cars. Initialize an ArrayList called garage that stores each ClassicCar that the company has in stock. import java.util.ArrayList; public class CarTracker { public static void main(String[] args) { //Initialize your ArrayList here: ArrayList<> garage = new ArrayList<>(); } }public class ClassicCar { String name; String model; int cost; public ClassicCar(String name, String model, int cost) { this.name = name; this.model = model; this.cost = cost; } }
55298c8d8796b86b287905dd0a4fc314
{ "intermediate": 0.4051768481731415, "beginner": 0.3765150010585785, "expert": 0.21830813586711884 }
45,858
Write a program that adds the numbers 10, 15, 20, 25, 30 into the numbers ArrayList and then prints out the first element in the list.import java.util.ArrayList; public class Numbers { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<Integer>(); // Add 5 numbers to `numbers` // Print out the first element in `numbers` } }
d4364e914d24094cbb42b28df2157451
{ "intermediate": 0.3734080195426941, "beginner": 0.5180908441543579, "expert": 0.10850120335817337 }
45,859
write a python application that has a ui interface. the program should be able to take in a excel file and show the data in a dataframe to edit. All edits are saved back to the excel file upon clicking a save button.
f2fe254ee90f34af68170a519789c96a
{ "intermediate": 0.5466594099998474, "beginner": 0.1447082757949829, "expert": 0.3086322546005249 }
45,860
write a program in python that calcultaes the fibonacci rect for a stock price
0e6cf6c83232714b621e53653c1de47e
{ "intermediate": 0.24416379630565643, "beginner": 0.12678676843643188, "expert": 0.6290494203567505 }
45,861
can i use function defined inside a class as a decorator?
05b658370d32079d74bf43b2cd41ff3e
{ "intermediate": 0.25635600090026855, "beginner": 0.6373239755630493, "expert": 0.10632003098726273 }
45,862
hola tengo este objeto class ConfigurationUser(Audit): DAYS = ( (0, '12 Horas'), (1, '1 Día'), (2, '2 Días'), (3, '3 Días'), (4, '4 Días'), (5, '5 Días'), ) buyer = models.OneToOneField( Buyer, on_delete=models.CASCADE, verbose_name=_('buyer') ) bidding_time_days = models.IntegerField( _('bidding time days'), choices=DAYS, default=1 ) shipping_companies = models.ManyToManyField(Transporter, verbose_name=_('shipping companies')) class Meta: verbose_name = _('Configuration User') verbose_name_plural = _('Configuration Users') def __str__(self): return f'Configuration User #{self.id}' y quiero traer los datos de days aca configuration_user = ConfigurationUser.objects.filter(buyer=self.request.user.buyer).first() context['configuration_user'] = configuration_user print(f'configuration_user.bidding_time_days: {configuration_user.bidding_time_days.value}') como hago para que lo muestre?
0c2fc9fda7fe238c5a3e3d5871124a23
{ "intermediate": 0.28623807430267334, "beginner": 0.5064817667007446, "expert": 0.20728012919425964 }
45,863
How do I chroot into asahi linux fedora on an apple silicon macbook running macos?
eead47449d4a2f0fc629679dabd40ca1
{ "intermediate": 0.4755813181400299, "beginner": 0.21405693888664246, "expert": 0.3103618025779724 }
45,864
How can I chroot into a linux install in macos?
47ce21f6a63e7dfdbd6e9cceea941295
{ "intermediate": 0.4193478524684906, "beginner": 0.2614228427410126, "expert": 0.3192293047904968 }
45,865
Can't bind to 'routerLink' since it isn't a known property of 'img'.ngtsc(-998002)
a87e2805b06e1bd9356c9fa3167bdc3e
{ "intermediate": 0.4604761600494385, "beginner": 0.32390812039375305, "expert": 0.21561573445796967 }
45,866
class Bot_Logger: def __init__(self, bot_number, board): self.bot_number = bot_number self.board = board self.log_file_path = f'{paths.main_folder}logs//{board}//bot{bot_number}.log' @Bot_Logger.add_to_logs def print(self, text): print(text) def add_to_logs(self, Print_func): def wrapper(*args): text = args[1].replace('\n','') now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') with open(self.log_file_path, "a", encoding='utf-8') as log_file: log_file.write(f'{now} - {text}\n') Print_func(*args) return wrapper why i cant use add_to_logs as a decorator?
ac284d84fdbb9109a6d62baa90abddae
{ "intermediate": 0.338556170463562, "beginner": 0.5493934750556946, "expert": 0.11205045878887177 }
45,867
Write a JavaScript ai prompt generator with a "function getRandomItem(list)" and a "function assembleString()". The "const assembledString" will be the prompt itself and return "assembledsString". It will contain configuration settings "const configuration = pipeline.configuration;" "const randomArtworkDescription = assembleString();" and "const negPrompt = """. It will then run the pipeline: for (i = 0; i < batchCount; i++) { const randomArtworkDescription = assembleString(); configuration.seed = -1; let batchCountLog = `{render ${i+1} of ${batchCount}}`; console.log(__dtPrettyPrint(batchCountLog)); pipeline.run({ configuration: configuration, prompt: randomArtworkDescription, negativePrompt: negPrompt }); } It needs to include variables for pinup artists, pinup costumes, pinup poses and exotic locales.
cf6a1a2cccb4c9acb34cf4c6006249e6
{ "intermediate": 0.30331021547317505, "beginner": 0.5359957218170166, "expert": 0.16069407761096954 }
45,868
i do except BaseException as ex: Print(str(ex)) but it only prints the error itself. how to print the line and path to that line when error occurs?
7f2238e7acef080e06a591dd18685a3b
{ "intermediate": 0.5888380408287048, "beginner": 0.14895164966583252, "expert": 0.26221030950546265 }
45,869
add this whole code here "from binance.client import Client import pandas as pd import numpy as np import ta # Initialize Binance client with your API keys api_key = 'YOUR_API_KEY' api_secret = 'YOUR_API_SECRET' client = Client(api_key, api_secret) # Define the trading pair and timeframe symbol = 'BTCUSDT' interval = Client.KLINE_INTERVAL_1HOUR # Fetch historical candlestick data klines = client.get_klines(symbol=symbol, interval=interval) # Format the data into a pandas DataFrame data = pd.DataFrame(klines, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore']) data['open'] = pd.to_numeric(data['open']) data['high'] = pd.to_numeric(data['high']) data['low'] = pd.to_numeric(data['low']) data['close'] = pd.to_numeric(data['close']) data['volume'] = pd.to_numeric(data['volume']) # Function to calculate Moving Averages (MA) def calculate_moving_averages(data, window_sizes=[20, 50, 200]): for window_size in window_sizes: data[f'MA_{window_size}'] = data['close'].rolling(window=window_size).mean() # Function to calculate Relative Strength Index (RSI) def calculate_rsi(data, window_size=14): data['RSI'] = ta.momentum.rsi(close=data['close'], window=window_size) # Function to calculate MACD (Moving Average Convergence Divergence) def calculate_macd(data): macd = ta.trend.macd(close=data['close']) data['MACD'] = macd.macd() data['MACD_Signal'] = macd.macd_signal() data['MACD_Histogram'] = macd.macd_diff() # Function to calculate Bollinger Bands def calculate_bollinger_bands(data, window_size=20, window_dev=2): indicator_bb = ta.volatility.BollingerBands(close=data['close'], window=window_size, window_dev=window_dev) data['BB_Middle'] = indicator_bb.bollinger_mavg() data['BB_Upper'] = indicator_bb.bollinger_hband() data['BB_Lower'] = indicator_bb.bollinger_lband() # Function to calculate Volume Analysis def calculate_volume_analysis(data): data['Volume_Moving_Average'] = data['volume'].rolling(window=20).mean() # Function to calculate Average True Range (ATR) def calculate_atr(data, window_size=14): data['ATR'] = ta.volatility.average_true_range(high=data['high'], low=data['low'], close=data['close'], window=window_size) # Function to calculate Fibonacci Extensions def calculate_fibonacci_extensions(data): highest_price = data['close'].max() lowest_price = data['close'].min() range_high_low = highest_price - lowest_price fibonacci_levels = [0.382, 0.5, 0.618] # Fibonacci retracement levels fibonacci_prices = [highest_price + level * range_high_low for level in fibonacci_levels] data['Fib_38.2%'] = fibonacci_prices[0] data['Fib_50%'] = fibonacci_prices[1] data['Fib_61.8%'] = fibonacci_prices[2] # Function to calculate Parabolic SAR (Stop and Reverse) def calculate_parabolic_sar(data, acceleration=0.02, maximum=0.2): data['SAR'] = ta.trend.PSARIndicator(high=data['high'], low=data['low'], acceleration=acceleration, maximum=maximum).psar() # Calculate technical indicators calculate_moving_averages(data) calculate_rsi(data) calculate_macd(data) calculate_bollinger_bands(data) calculate_volume_analysis(data) calculate_atr(data) calculate_fibonacci_extensions(data) calculate_parabolic_sar(data) # Print the DataFrame with calculated technical indicators print(data.head())" with this code here from binance.client import Client import pandas as pd import numpy as np import ta class CryptoTradingBot: def __init__(self, api_key, api_secret): self.client = Client(api_key, api_secret) def fetch_candlestick_data(self, symbol, interval): try: klines = self.client.get_klines(symbol=symbol, interval=interval) return pd.DataFrame(klines, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore']) except Exception as e: print(f"Error fetching candlestick data: {e}") return None def preprocess_data(self, data): try: data['open'] = pd.to_numeric(data['open']) data['high'] = pd.to_numeric(data['high']) data['low'] = pd.to_numeric(data['low']) data['close'] = pd.to_numeric(data['close']) data['volume'] = pd.to_numeric(data['volume']) return data.dropna() # Handle missing values except Exception as e: print(f"Error preprocessing data: {e}") return None def calculate_technical_indicators(self, data): try: calculate_moving_averages(data) calculate_rsi(data) calculate_macd(data) calculate_bollinger_bands(data) calculate_volume_analysis(data) calculate_atr(data) calculate_fibonacci_extensions(data) calculate_parabolic_sar(data) return data except Exception as e: print(f"Error calculating technical indicators: {e}") return None def visualize_data(self, data): # Add visualization code here pass def backtest_strategy(self, data): # Add backtesting code here pass def execute_trades(self, data): # Add trading execution code here pass def calculate_moving_averages(data, window_sizes=[20, 50, 200]): for window_size in window_sizes: data[f'MA_{window_size}'] = data['close'].rolling(window=window_size).mean() def calculate_rsi(data, window_size=14): data['RSI'] = ta.momentum.rsi(close=data['close'], window=window_size) def calculate_macd(data): macd = ta.trend.macd(close=data['close']) data['MACD'] = macd.macd() data['MACD_Signal'] = macd.macd_signal() data['MACD_Histogram'] = macd.macd_diff() def calculate_bollinger_bands(data, window_size=20, window_dev=2): indicator_bb = ta.volatility.BollingerBands(close=data['close'], window=window_size, window_dev=window_dev) data['BB_Middle'] = indicator_bb.bollinger_mavg() data['BB_Upper'] = indicator_bb.bollinger_hband() data['BB_Lower'] = indicator_bb.bollinger_lband() def calculate_volume_analysis(data): data['Volume_Moving_Average'] = data['volume'].rolling(window=20).mean() def calculate_atr(data, window_size=14): data['ATR'] = ta.volatility.average_true_range(high=data['high'], low=data['low'], close=data['close'], window=window_size) def calculate_fibonacci_extensions(data): highest_price = data['close'].max() lowest_price = data['close'].min() range_high_low = highest_price - lowest_price fibonacci_levels = [0.382, 0.5, 0.618] # Fibonacci retracement levels fibonacci_prices = [highest_price + level * range_high_low for level in fibonacci_levels] data['Fib_38.2%'] = fibonacci_prices[0] data['Fib_50%'] = fibonacci_prices[1] data['Fib_61.8%'] = fibonacci_prices[2] def calculate_parabolic_sar(data, acceleration=0.02, maximum=0.2): data['SAR'] = ta.trend.PSARIndicator(high=data['high'], low=data['low'], acceleration=acceleration, maximum=maximum).psar() # Example usage: if __name__ == "__main__": api_key = 'YOUR_API_KEY' api_secret = 'YOUR_API_SECRET' bot = CryptoTradingBot(api_key, api_secret) symbol = 'BTCUSDT' interval = Client.KLINE_INTERVAL_1HOUR candlestick_data = bot.fetch_candlestick_data(symbol, interval) if candlestick_data is not None: preprocessed_data = bot.preprocess_data(candlestick_data) if preprocessed_data is not None: technical_indicators_data = bot.calculate_technical_indicators(preprocessed_data) if technical_indicators_data is not None: bot.visualize_data(technical_indicators_data) bot.backtest_strategy(technical_indicators_data) bot.execute_trades(technical_indicators_data) and give me the whole code togather perfectly. not missing anything
54e1b23b263cc3e3094e114ba6eeb9f0
{ "intermediate": 0.377906858921051, "beginner": 0.3592938482761383, "expert": 0.2627992331981659 }
45,870
covert following code to full python code: result[rollup_category][day] = int(any(details[device][day] for device in devices if device in details))
8d9a2e5c13422af0bc78698c0d8d5c1e
{ "intermediate": 0.36461809277534485, "beginner": 0.31443846225738525, "expert": 0.3209434747695923 }
45,871
import java.util.Scanner; public class lcs { public static void main(String[] args) { if(args.length != 2) { System.out.println(“error”); return; } String s1 = args[0]; String s2 = args[1]; if(s1.length() > 100 || s2.length() > 100) { System.out.println(“the string length too long”); return; } String result = findLCS(s1, s2); System.out.println("Length of LCS: " + result.length()); System.out.println("LCS: " + result); } public static String findLCS(String s1, String s2) { int[][] dp = new int[s1.length() + 1][s2.length() + 1]; // Fill the dp table for(int i = 1; i <= s1.length(); i++) { for(int j = 1; j <= s2.length(); j++) { if(s1.charAt(i - 1) == s2.charAt(j - 1)) { dp[i][j] = 1 + dp[i - 1][j - 1]; } else { dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); } } } // Trace back from dp[s1.length()][s2.length()] to find the LCS StringBuilder lcs = new StringBuilder(); int i = s1.length(), j = s2.length(); while(i > 0 && j > 0) { if(s1.charAt(i - 1) == s2.charAt(j - 1)) { lcs.insert(0, s1.charAt(i - 1)); // append current character i–; j–; } else if(dp[i - 1][j] > dp[i][j - 1]) { i–; } else { j–; } } return lcs.toString(); } } Syntax error on token "Invalid Character", ++ expected. This error is occuring for i- and j- in i–; j–; } else if(dp[i - 1][j] > dp[i][j - 1]) { i–; } else { j–;
1e69f4eb482d69799f67df96136ebd58
{ "intermediate": 0.3422851860523224, "beginner": 0.46758559346199036, "expert": 0.19012919068336487 }
45,872
Write a program floyd.java to find all pairs shortest paths using Floyd’s algorithm for several undirected complete graphs, which are saved in a file called output.txt. Print all pairs shortest paths and their lengths. Program Usage Your program should be invoked as follows $> floyd <graph-file> Graph File: <graph-file> is the name of a file that includes more than one problem. The lines that correspond to problem j will contains an integer n (between 5 and 10) that indicates how many cities and n x n adjacency matrix A (that is, the distance between n cities, between 1 to 10), in the next n rows. Note that no infinity will appear in the matrix A. A sample graph file appears below. Problem 1: n = 7 0 6 5 4 6 3 6 6 0 6 4 5 5 3 5 6 0 3 1 4 6 4 4 3 0 4 1 4 6 5 1 4 0 5 5 3 5 4 1 5 0 3 6 3 6 4 5 3 0 Problem 2: n = 6 0 1 2 1 3 4 1 0 3 2 2 3 2 3 0 3 3 6 1 2 3 0 3 5 3 2 3 3 0 5 4 3 6 5 5 0 Output File Output the solution of problem 1 first, then problem 2, and etc. The solution of problem j should start with an integer n (the number cities) and the n x n Pointer Array P (in the next n rows). The shortest paths should then follow, one per line. Output the shortest paths from C1 to all other cities, then C2 to all other cities, and Cn to all other cities. A sample output file: Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: 0
33794ed6aa736b3bc2a7879d0bf78685
{ "intermediate": 0.32664430141448975, "beginner": 0.36390671133995056, "expert": 0.3094489574432373 }
45,873
How to install vera++ in linux, using checkinstall? I tried with ./configure and make and both gives me error, the folder structure has a cemake folder and other related cmake files ~/Downloads/vera++-1.3.0> ./configure bash: ./configure: No such file or directory ~/Downloads/vera++-1.3.0> make make: *** No targets specified and no makefile found. Stop.
d60941c34c89548c6681f55c69541b3b
{ "intermediate": 0.48434504866600037, "beginner": 0.23028464615345, "expert": 0.2853703200817108 }
45,874
Teach me how to use Whisper from openai.AsyncOpenAI library (Python)
822f007d43eb6c037cc27dd7875e0785
{ "intermediate": 0.5666233897209167, "beginner": 0.07625958323478699, "expert": 0.3571169972419739 }
45,875
import java.io.*; import java.util.Scanner; public class floyd { public static void main(String[] args) throws FileNotFoundException { if(args.length != 1) { System.err.println("Usage: floyd <graph-file>"); return; } String inputFile = args[0]; Scanner scanner = new Scanner(new File(inputFile)); PrintWriter writer = new PrintWriter("output.txt"); // Process each problem in the file while (scanner.hasNextInt()) { int n = scanner.nextInt(); // Read the number of vertices/cities int[][] dist = new int[n][n]; // Distance matrix int[][] next = new int[n][n]; // Next matrix to reconstruct paths // Initialize matrices for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dist[i][j] = scanner.nextInt(); if(dist[i][j] != 0) { next[i][j] = j; } } } // Floyd’s Algorithm for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; next[i][j] = next[i][k]; } } } } writer.println("Problem" + ": n = " + n); writer.println("Pmatrix:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { writer.print(next[i][j] + " "); } writer.println(); } // Reconstructing paths for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { int u = i; String path = "V" + (i+1); while(u != j){ u = next[u][j]; path += " V" + (u+1); } writer.println("V" + (i+1) + "-V" + (j+1) + ": shortest path and length"); writer.println(path + ": " + dist[i][j]); } } } } scanner.close(); writer.close(); } } When I'm giving ./floyd graphfile.txt this command in the terminal it is only showing an output.txt file but there is nothing in the output.txt file
03e39534c517f72a87c9257783cc572c
{ "intermediate": 0.36332306265830994, "beginner": 0.44231951236724854, "expert": 0.19435742497444153 }
45,876
import java.io.*; import java.util.Scanner; public class floyd { public static void main(String[] args) throws FileNotFoundException { if(args.length != 1) { System.err.println("Usage: floyd <graph-file>"); return; } String inputFile = args[0]; Scanner scanner = new Scanner(new File(inputFile)); PrintWriter writer = new PrintWriter("output.txt"); // To skip non-integer lines such as "Problem1 Amatrix: n = 7" while(scanner.hasNextLine()) { String line = scanner.nextLine().trim(); // Try to extract ‘n’ from lines like "Problem1 Amatrix: n = 7" if(line.startsWith("Problem") && line.contains("n =")) { int n = Integer.parseInt(line.split("n =")[1].trim()); // Now we know ‘n’, we can proceed with the adjacency matrix int[][] dist = new int[n][n]; int[][] next = new int[n][n]; // Read the matrix for(int i = 0; i < n; i++) { if(scanner.hasNextLine()) { line = scanner.nextLine().trim(); String[] parts = line.split("\\s+"); for(int j = 0; j < n; j++) { dist[i][j] = Integer.parseInt(parts[j]); if(dist[i][j] != 0 && i != j) { next[i][j] = j; } } } } for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; next[i][j] = next[i][k]; } } } } writer.println("Problem" + ": n = " + n); writer.println("Pmatrix:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { writer.print(next[i][j] + " "); } writer.println(); } // Reconstructing paths for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { int u = i; String path = "V" + (i+1); while(u != j){ u = next[u][j]; path += " V" + (u+1); } writer.println("V" + (i+1) + "-V" + (j+1) + ": shortest path and length"); writer.println(path + ": " + dist[i][j]); } } } } scanner.close(); writer.close(); } } } The program is giving error as ./floyd graphfile.txt Exception in thread "main" java.lang.IllegalStateException: Scanner closed at java.base/java.util.Scanner.ensureOpen(Scanner.java:1154) at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1786) at java.base/java.util.Scanner.hasNextLine(Scanner.java:1615) at floyd.main(floyd.java:17) The input is Problem1 Amatrix: n = 7 0 6 5 4 6 3 6 6 0 6 4 5 5 3 5 6 0 3 1 4 6 4 4 3 0 4 1 4 6 5 1 4 0 5 5 3 5 4 1 5 0 3 6 3 6 4 5 3 0 Problem2 Amatrix: n = 6 0 1 2 1 3 4 1 0 3 2 2 3 2 3 0 3 3 6 1 2 3 0 3 5 3 2 3 3 0 5 4 3 6 5 5 0 and the expected output is Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: 0 but the program is giving output as Problem: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V1-V2: shortest path and length V1 V2: 6 V1-V3: shortest path and length V1 V3: 5 V1-V4: shortest path and length V1 V4: 4 V1-V5: shortest path and length V1 V5: 6 V1-V6: shortest path and length V1 V6: 3 V1-V7: shortest path and length V1 V7: 6 V2-V1: shortest path and length V2 V1: 6 V2-V3: shortest path and length V2 V3: 6 V2-V4: shortest path and length V2 V4: 4 V2-V5: shortest path and length V2 V5: 5 V2-V6: shortest path and length V2 V6: 5 V2-V7: shortest path and length V2 V7: 3 V3-V1: shortest path and length V3 V1: 5 V3-V2: shortest path and length V3 V2: 6 V3-V4: shortest path and length V3 V4: 3 V3-V5: shortest path and length V3 V5: 1 V3-V6: shortest path and length V3 V6: 4 V3-V7: shortest path and length V3 V7: 6 V4-V1: shortest path and length V4 V1: 4 V4-V2: shortest path and length V4 V2: 4 V4-V3: shortest path and length V4 V3: 3 V4-V5: shortest path and length V4 V5: 4 V4-V6: shortest path and length V4 V6: 1 V4-V7: shortest path and length V4 V7: 4 V5-V1: shortest path and length V5 V1: 6 V5-V2: shortest path and length V5 V2: 5 V5-V3: shortest path and length V5 V3: 1 V5-V4: shortest path and length V5 V4: 4 V5-V6: shortest path and length V5 V6: 5 V5-V7: shortest path and length V5 V7: 5 V6-V1: shortest path and length V6 V1: 3 V6-V2: shortest path and length V6 V2: 5 V6-V3: shortest path and length V6 V3: 4 V6-V4: shortest path and length V6 V4: 1 V6-V5: shortest path and length V6 V5: 5 V6-V7: shortest path and length V6 V7: 3 V7-V1: shortest path and length V7 V1: 6 V7-V2: shortest path and length V7 V2: 3 V7-V3: shortest path and length V7 V3: 6 V7-V4: shortest path and length V7 V4: 4 V7-V5: shortest path and length V7 V5: 5 V7-V6: shortest path and length V7 V6: 3
cc0b69ec0dfea16e24a0ff4edeaa38c3
{ "intermediate": 0.3913532495498657, "beginner": 0.39991486072540283, "expert": 0.20873188972473145 }
45,877
import java.io.*; import java.util.Scanner; public class floyd { public static void main(String[] args) throws FileNotFoundException { if(args.length != 1) { System.err.println("Usage: floyd <graph-file>"); return; } String inputFile = args[0]; Scanner scanner = new Scanner(new File(inputFile)); PrintWriter writer = new PrintWriter("output.txt"); // To skip non-integer lines such as "Problem1 Amatrix: n = 7" while(scanner.hasNextLine()) { String line = scanner.nextLine().trim(); // Try to extract ‘n’ from lines like "Problem1 Amatrix: n = 7" if(line.startsWith("Problem") && line.contains("n =")) { int n = Integer.parseInt(line.split("n =")[1].trim()); // Now we know ‘n’, we can proceed with the adjacency matrix int[][] dist = new int[n][n]; int[][] next = new int[n][n]; // Read the matrix for(int i = 0; i < n; i++) { if(scanner.hasNextLine()) { line = scanner.nextLine().trim(); String[] parts = line.split("\\s+"); for(int j = 0; j < n; j++) { dist[i][j] = Integer.parseInt(parts[j]); if(dist[i][j] != 0 && i != j) { next[i][j] = j; } } } } for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; next[i][j] = next[i][k]; } } } } writer.println("Problem" + ": n = " + n); writer.println("Pmatrix:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { writer.print(next[i][j] + " "); } writer.println(); } // Reconstructing paths for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { int u = i; String path = "V" + (i+1); while(u != j){ u = next[u][j]; path += " V" + (u+1); } writer.println("V" + (i+1) + "-V" + (j+1) + ": shortest path and length"); writer.println(path + ": " + dist[i][j]); } } } } } scanner.close(); writer.close(); } } ./floyd graphfile.txt Exception in thread "main" java.lang.IllegalStateException: Scanner closed at java.base/java.util.Scanner.ensureOpen(Scanner.java:1154) at java.base/java.util.Scanner.findWithinHorizon(Scanner.java:1786) at java.base/java.util.Scanner.hasNextLine(Scanner.java:1615) at floyd.main(floyd.java:17) The input file graphfile.txt is Problem1 Amatrix: n = 7 0 6 5 4 6 3 6 6 0 6 4 5 5 3 5 6 0 3 1 4 6 4 4 3 0 4 1 4 6 5 1 4 0 5 5 3 5 4 1 5 0 3 6 3 6 4 5 3 0 Problem2 Amatrix: n = 6 0 1 2 1 3 4 1 0 3 2 2 3 2 3 0 3 3 6 1 2 3 0 3 5 3 2 3 3 0 5 4 3 6 5 5 0 and the output is Problem: n = 7 Pmatrix: 0 1 2 3 4 5 6 0 0 2 3 4 5 6 0 1 0 3 4 5 6 0 1 2 0 4 5 6 0 1 2 3 0 5 6 0 1 2 3 4 0 6 0 1 2 3 4 5 0 V1-V2: shortest path and length V1 V2: 6 V1-V3: shortest path and length V1 V3: 5 V1-V4: shortest path and length V1 V4: 4 V1-V5: shortest path and length V1 V5: 6 V1-V6: shortest path and length V1 V6: 3 V1-V7: shortest path and length V1 V7: 6 V2-V1: shortest path and length V2 V1: 6 V2-V3: shortest path and length V2 V3: 6 V2-V4: shortest path and length V2 V4: 4 V2-V5: shortest path and length V2 V5: 5 V2-V6: shortest path and length V2 V6: 5 V2-V7: shortest path and length V2 V7: 3 V3-V1: shortest path and length V3 V1: 5 V3-V2: shortest path and length V3 V2: 6 V3-V4: shortest path and length V3 V4: 3 V3-V5: shortest path and length V3 V5: 1 V3-V6: shortest path and length V3 V6: 4 V3-V7: shortest path and length V3 V7: 6 V4-V1: shortest path and length V4 V1: 4 V4-V2: shortest path and length V4 V2: 4 V4-V3: shortest path and length V4 V3: 3 V4-V5: shortest path and length V4 V5: 4 V4-V6: shortest path and length V4 V6: 1 V4-V7: shortest path and length V4 V7: 4 V5-V1: shortest path and length V5 V1: 6 V5-V2: shortest path and length V5 V2: 5 V5-V3: shortest path and length V5 V3: 1 V5-V4: shortest path and length V5 V4: 4 V5-V6: shortest path and length V5 V6: 5 V5-V7: shortest path and length V5 V7: 5 V6-V1: shortest path and length V6 V1: 3 V6-V2: shortest path and length V6 V2: 5 V6-V3: shortest path and length V6 V3: 4 V6-V4: shortest path and length V6 V4: 1 V6-V5: shortest path and length V6 V5: 5 V6-V7: shortest path and length V6 V7: 3 V7-V1: shortest path and length V7 V1: 6 V7-V2: shortest path and length V7 V2: 3 V7-V3: shortest path and length V7 V3: 6 V7-V4: shortest path and length V7 V4: 4 V7-V5: shortest path and length V7 V5: 5 V7-V6: shortest path and length V7 V6: 3 which is incorrect. The expected output is Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: 0
064ffad8ddb64e24b39b954fa4464d30
{ "intermediate": 0.3913532495498657, "beginner": 0.39991486072540283, "expert": 0.20873188972473145 }
45,878
import java.io.*; import java.util.Scanner; public class floyd { // Infinity parameter - you might need a large value that will not interfere with actual path costs public static final int INF = Integer.MAX_VALUE / 2; public static void main(String[] args) throws FileNotFoundException { if (args.length != 1) { System.err.println("Usage: Floyd <graph-file>"); return; } String inputFile = args[0]; Scanner scanner = new Scanner(new File(inputFile)); PrintWriter writer = new PrintWriter("output.txt"); while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); if (line.startsWith("Problem") && line.contains("n =")) { String problemId = line.split(" ")[0]; // to Storing the problem id, e.g., "Problem1" int n = Integer.parseInt(line.split("n =")[1].trim()); // Initialize the adjacency and next matrix int[][] dist = new int[n][n]; int[][] next = new int[n][n]; // Initially, no paths are known, so fill with INF and -1 respectively, except diagonal elements for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) dist[i][j] = 0; else dist[i][j] = INF; next[i][j] = -1; // Using -1 to indicate no path } } // Read the matrix for (int i = 0; i < n; i++) { if (scanner.hasNextLine()) { line = scanner.nextLine().trim(); String[] parts = line.split("\\s+"); for (int j = 0; j < n; j++) { int val = Integer.parseInt(parts[j]); // Only set distances for non-zero (assuming non-zero means path exists) and non-diagonal elements if (val != 0 && i != j) { dist[i][j] = val; next[i][j] = j; // Initially, the next vertex on the path is the target itself } } } } // Floyd-Warshall algorithm for (int k = 0; k < n; ++k) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { // We also need to check for potential integer overflow if (dist[i][k] < INF && dist[k][j] < INF && dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; next[i][j] = next[i][k]; } } } } writer.println(problemId + ": n = " + n); // Include the problem ID in the output // Print Pmatrix indicating direct path found from i to j writer.println("Pmatrix:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { writer.print(next[i][j] + " "); } writer.println(); } // Reconstructing paths for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j && dist[i][j] != INF) { // Ensure a path exists int u = i; writer.print(problemId + " V" + (i + 1) + "-V" + (j + 1) + ": shortest path and length\nV" + (i + 1)); while (u != j) { u = next[u][j]; writer.print(" V" + (u + 1)); } writer.println(": " + dist[i][j]); } } } } } scanner.close(); writer.close(); } } the program is giving the output as Problem1: n = 7 Pmatrix: -1 1 2 3 4 5 6 0 -1 2 3 4 5 6 0 1 -1 3 4 5 6 0 1 2 -1 4 5 6 0 1 2 3 -1 5 6 0 1 2 3 4 -1 6 0 1 2 3 4 5 -1 Problem1 V1-V2: shortest path and length V1 V2: 6 Problem1 V1-V3: shortest path and length V1 V3: 5 Problem1 V1-V4: shortest path and length V1 V4: 4 Problem1 V1-V5: shortest path and length V1 V5: 6 Problem1 V1-V6: shortest path and length V1 V6: 3 Problem1 V1-V7: shortest path and length V1 V7: 6 Problem1 V2-V1: shortest path and length V2 V1: 6 Problem1 V2-V3: shortest path and length V2 V3: 6 Problem1 V2-V4: shortest path and length V2 V4: 4 Problem1 V2-V5: shortest path and length V2 V5: 5 Problem1 V2-V6: shortest path and length V2 V6: 5 Problem1 V2-V7: shortest path and length V2 V7: 3 Problem1 V3-V1: shortest path and length V3 V1: 5 Problem1 V3-V2: shortest path and length V3 V2: 6 Problem1 V3-V4: shortest path and length V3 V4: 3 Problem1 V3-V5: shortest path and length V3 V5: 1 Problem1 V3-V6: shortest path and length V3 V6: 4 Problem1 V3-V7: shortest path and length V3 V7: 6 Problem1 V4-V1: shortest path and length V4 V1: 4 Problem1 V4-V2: shortest path and length V4 V2: 4 Problem1 V4-V3: shortest path and length V4 V3: 3 Problem1 V4-V5: shortest path and length V4 V5: 4 Problem1 V4-V6: shortest path and length V4 V6: 1 Problem1 V4-V7: shortest path and length V4 V7: 4 Problem1 V5-V1: shortest path and length V5 V1: 6 Problem1 V5-V2: shortest path and length V5 V2: 5 Problem1 V5-V3: shortest path and length V5 V3: 1 Problem1 V5-V4: shortest path and length V5 V4: 4 Problem1 V5-V6: shortest path and length V5 V6: 5 Problem1 V5-V7: shortest path and length V5 V7: 5 Problem1 V6-V1: shortest path and length V6 V1: 3 Problem1 V6-V2: shortest path and length V6 V2: 5 Problem1 V6-V3: shortest path and length V6 V3: 4 Problem1 V6-V4: shortest path and length V6 V4: 1 Problem1 V6-V5: shortest path and length V6 V5: 5 Problem1 V6-V7: shortest path and length V6 V7: 3 Problem1 V7-V1: shortest path and length V7 V1: 6 Problem1 V7-V2: shortest path and length V7 V2: 3 Problem1 V7-V3: shortest path and length V7 V3: 6 Problem1 V7-V4: shortest path and length V7 V4: 4 Problem1 V7-V5: shortest path and length V7 V5: 5 Problem1 V7-V6: shortest path and length V7 V6: 3 Problem2: n = 6 Pmatrix: -1 1 2 3 4 5 0 -1 2 3 4 5 0 1 -1 3 4 5 0 1 2 -1 4 5 0 1 2 3 -1 5 0 1 2 3 4 -1 Problem2 V1-V2: shortest path and length V1 V2: 1 Problem2 V1-V3: shortest path and length V1 V3: 2 Problem2 V1-V4: shortest path and length V1 V4: 1 Problem2 V1-V5: shortest path and length V1 V5: 3 Problem2 V1-V6: shortest path and length V1 V6: 4 Problem2 V2-V1: shortest path and length V2 V1: 1 Problem2 V2-V3: shortest path and length V2 V3: 3 Problem2 V2-V4: shortest path and length V2 V4: 2 Problem2 V2-V5: shortest path and length V2 V5: 2 Problem2 V2-V6: shortest path and length V2 V6: 3 Problem2 V3-V1: shortest path and length V3 V1: 2 Problem2 V3-V2: shortest path and length V3 V2: 3 Problem2 V3-V4: shortest path and length V3 V4: 3 Problem2 V3-V5: shortest path and length V3 V5: 3 Problem2 V3-V6: shortest path and length V3 V6: 6 Problem2 V4-V1: shortest path and length V4 V1: 1 Problem2 V4-V2: shortest path and length V4 V2: 2 Problem2 V4-V3: shortest path and length V4 V3: 3 Problem2 V4-V5: shortest path and length V4 V5: 3 Problem2 V4-V6: shortest path and length V4 V6: 5 Problem2 V5-V1: shortest path and length V5 V1: 3 Problem2 V5-V2: shortest path and length V5 V2: 2 Problem2 V5-V3: shortest path and length V5 V3: 3 Problem2 V5-V4: shortest path and length V5 V4: 3 Problem2 V5-V6: shortest path and length V5 V6: 5 Problem2 V6-V1: shortest path and length V6 V1: 4 Problem2 V6-V2: shortest path and length V6 V2: 3 Problem2 V6-V3: shortest path and length V6 V3: 6 Problem2 V6-V4: shortest path and length V6 V4: 5 Problem2 V6-V5: shortest path and length V6 V5: 5 which is wrong. The correct and expected output that the program should give is Problem1: n = 7 Pmatrix: 0 0 0 6 3 0 6 0 0 5 0 0 4 0 0 5 0 0 0 0 5 6 0 0 0 3 0 6 3 0 0 3 0 3 0 0 4 0 0 3 0 0 6 0 5 6 0 0 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 6 V1 V3: 5 V1 V6 V4: 4 V1 V3 V5: 6 V1 V6: 3 V1 V6 V7: 6 V2-Vj: shortest path and length V2 V1: 6 V2 V2: 0 V2 V5 V3: 6 V2 V4: 4 V2 V5: 5 V2 V4 V6: 5 V2 V7: 3 V3-Vj: shortest path and length V3 V1: 5 V3 V5 V2: 6 V3 V3: 0 V3 V4: 3 V3 V5: 1 V3 V6: 4 V3 V5 V7: 6 V4-Vj: shortest path and length V4 V6 V1: 4 V4 V2: 4 V4 V3: 3 V4 V4: 0 V4 V3 V5: 4 V4 V6: 1 V4 V6 V7: 4 V5-Vj: shortest path and length V5 V3 V1: 6 V5 V2: 5 V5 V3: 1 V5 V3 V4: 4 V5 V5: 0 V5 V3 V6: 5 V5 V7: 5 V6-Vj: shortest path and length V6 V1: 3 V6 V4 V2: 5 V6 V3: 4 V6 V4: 1 V6 V3 V5: 5 V6 V6: 0 V6 V7: 3 V7-Vj: shortest path and length V7 V6 V1: 6 V7 V2: 3 V7 V5 V3: 6 V7 V6 V4: 4 V7 V5: 5 V7 V6: 3 V7 V7: 0 Problem2: n = 6 Pmatrix: 0 0 0 0 2 2 0 0 1 1 0 0 0 1 0 1 0 2 0 1 1 0 0 2 2 0 0 0 0 2 2 0 2 2 2 0 V1-Vj: shortest path and length V1 V1: 0 V1 V2: 1 V1 V3: 2 V1 V4: 1 V1 V2 V5: 3 V1 V2 V6: 4 V2-Vj: shortest path and length V2 V1: 1 V2 V2: 0 V2 V1 V3: 3 V2 V1 V4: 2 V2 V5: 2 V2 V6: 3 V3-Vj: shortest path and length V3 V1: 2 V3 V1 V2: 3 V3 V3: 0 V3 V1 V4: 3 V3 V5: 3 V3 V1 V2 V6: 6 V4-Vj: shortest path and length V4 V1: 1 V4 V1 V2: 2 V4 V1 V3: 3 V4 V4: 0 V4 V5: 3 V4 V1 V2 V6: 5 V5-Vj: shortest path and length V5 V2 V1: 3 V5 V2: 2 V5 V3: 3 V5 V4: 3 V5 V5: 0 V5 V2 V6: 5 V6-Vj: shortest path and length V6 V2 V1: 4 V6 V2: 3 V6 V2 V1 V3: 6 V6 V2 V1 V4: 5 V6 V2 V5: 5 V6 V6: 0
9e1172ad49b70e72c6389136d5c3ab4f
{ "intermediate": 0.3619513511657715, "beginner": 0.5017861127853394, "expert": 0.13626253604888916 }
45,879
import gradio as gr import os import shutil import ffmpeg from datetime import datetime from pathlib import Path import numpy as np import cv2 import torch #import spaces from diffusers import AutoencoderKL, DDIMScheduler from einops import repeat from omegaconf import OmegaConf from PIL import Image from torchvision import transforms from transformers import CLIPVisionModelWithProjection from src.models.pose_guider import PoseGuider from src.models.unet_2d_condition import UNet2DConditionModel from src.models.unet_3d import UNet3DConditionModel from src.pipelines.pipeline_pose2vid_long import Pose2VideoPipeline from src.utils.util import get_fps, read_frames, save_videos_grid, save_pil_imgs from src.audio_models.model import Audio2MeshModel from src.utils.audio_util import prepare_audio_feature from src.utils.mp_utils import LMKExtractor from src.utils.draw_util import FaceMeshVisualizer from src.utils.pose_util import project_points, project_points_with_trans, matrix_to_euler_and_translation, euler_and_translation_to_matrix from src.utils.crop_face_single import crop_face from src.audio2vid import get_headpose_temp, smooth_pose_seq from src.utils.frame_interpolation import init_frame_interpolation_model, batch_images_interpolation_tool config = OmegaConf.load('./configs/prompts/animation_audio.yaml') if config.weight_dtype == "fp16": weight_dtype = torch.float16 else: weight_dtype = torch.float32 audio_infer_config = OmegaConf.load(config.audio_inference_config) # prepare model a2m_model = Audio2MeshModel(audio_infer_config['a2m_model']) a2m_model.load_state_dict(torch.load(audio_infer_config['pretrained_model']['a2m_ckpt'], map_location="cpu"), strict=False) a2m_model.cuda().eval() vae = AutoencoderKL.from_pretrained( config.pretrained_vae_path, ).to("cuda", dtype=weight_dtype) reference_unet = UNet2DConditionModel.from_pretrained( config.pretrained_base_model_path, subfolder="unet", ).to(dtype=weight_dtype, device="cuda") inference_config_path = config.inference_config infer_config = OmegaConf.load(inference_config_path) denoising_unet = UNet3DConditionModel.from_pretrained_2d( config.pretrained_base_model_path, config.motion_module_path, subfolder="unet", unet_additional_kwargs=infer_config.unet_additional_kwargs, ).to(dtype=weight_dtype, device="cuda") pose_guider = PoseGuider(noise_latent_channels=320, use_ca=True).to(device="cuda", dtype=weight_dtype) # not use cross attention image_enc = CLIPVisionModelWithProjection.from_pretrained( config.image_encoder_path ).to(dtype=weight_dtype, device="cuda") sched_kwargs = OmegaConf.to_container(infer_config.noise_scheduler_kwargs) scheduler = DDIMScheduler(**sched_kwargs) # load pretrained weights denoising_unet.load_state_dict( torch.load(config.denoising_unet_path, map_location="cpu"), strict=False, ) reference_unet.load_state_dict( torch.load(config.reference_unet_path, map_location="cpu"), ) pose_guider.load_state_dict( torch.load(config.pose_guider_path, map_location="cpu"), ) pipe = Pose2VideoPipeline( vae=vae, image_encoder=image_enc, reference_unet=reference_unet, denoising_unet=denoising_unet, pose_guider=pose_guider, scheduler=scheduler, ) pipe = pipe.to("cuda", dtype=weight_dtype) # lmk_extractor = LMKExtractor() # vis = FaceMeshVisualizer() frame_inter_model = init_frame_interpolation_model() #@spaces.GPU def audio2video(input_audio, ref_img, headpose_video=None, size=512, steps=25, length=60, seed=42): fps = 30 cfg = 3.5 fi_step = 3 generator = torch.manual_seed(seed) lmk_extractor = LMKExtractor() vis = FaceMeshVisualizer() width, height = size, size date_str = datetime.now().strftime("%Y%m%d") time_str = datetime.now().strftime("%H%M") save_dir_name = f"{time_str}--seed_{seed}-{size}x{size}" save_dir = Path(f"a2v_output/{date_str}/{save_dir_name}") while os.path.exists(save_dir): save_dir = Path(f"a2v_output/{date_str}/{save_dir_name}_{np.random.randint(10000):04d}") save_dir.mkdir(exist_ok=True, parents=True) ref_image_np = cv2.cvtColor(ref_img, cv2.COLOR_RGB2BGR) ref_image_np = crop_face(ref_image_np, lmk_extractor) if ref_image_np is None: return None, Image.fromarray(ref_img) ref_image_np = cv2.resize(ref_image_np, (size, size)) ref_image_pil = Image.fromarray(cv2.cvtColor(ref_image_np, cv2.COLOR_BGR2RGB)) face_result = lmk_extractor(ref_image_np) if face_result is None: return None, ref_image_pil lmks = face_result['lmks'].astype(np.float32) ref_pose = vis.draw_landmarks((ref_image_np.shape[1], ref_image_np.shape[0]), lmks, normed=True) sample = prepare_audio_feature(input_audio, wav2vec_model_path=audio_infer_config['a2m_model']['model_path']) sample['audio_feature'] = torch.from_numpy(sample['audio_feature']).float().cuda() sample['audio_feature'] = sample['audio_feature'].unsqueeze(0) # inference pred = a2m_model.infer(sample['audio_feature'], sample['seq_len']) pred = pred.squeeze().detach().cpu().numpy() pred = pred.reshape(pred.shape[0], -1, 3) pred = pred + face_result['lmks3d'] if headpose_video is not None: pose_seq = get_headpose_temp(headpose_video) else: pose_seq = np.load(config['pose_temp']) mirrored_pose_seq = np.concatenate((pose_seq, pose_seq[-2:0:-1]), axis=0) cycled_pose_seq = np.tile(mirrored_pose_seq, (sample['seq_len'] // len(mirrored_pose_seq) + 1, 1))[:sample['seq_len']] # project 3D mesh to 2D landmark projected_vertices = project_points(pred, face_result['trans_mat'], cycled_pose_seq, [height, width]) pose_images = [] for i, verts in enumerate(projected_vertices): lmk_img = vis.draw_landmarks((width, height), verts, normed=False) pose_images.append(lmk_img) pose_list = [] # pose_tensor_list = [] # pose_transform = transforms.Compose( # [transforms.Resize((height, width)), transforms.ToTensor()] # ) args_L = len(pose_images) if length==0 or length > len(pose_images) else length args_L = min(args_L, 90) for pose_image_np in pose_images[: args_L : fi_step]: # pose_image_pil = Image.fromarray(cv2.cvtColor(pose_image_np, cv2.COLOR_BGR2RGB)) # pose_tensor_list.append(pose_transform(pose_image_pil)) pose_image_np = cv2.resize(pose_image_np, (width, height)) pose_list.append(pose_image_np) pose_list = np.array(pose_list) video_length = len(pose_list) video = pipe( ref_image_pil, pose_list, ref_pose, width, height, video_length, steps, cfg, generator=generator, ).videos #video = batch_images_interpolation_tool(video, frame_inter_model, inter_frames=fi_step-1) save_path = f"{save_dir}/{size}x{size}_{time_str}_noaudio.mp4" save_videos_grid( video, save_path, n_rows=1, fps=fps, ) # save_path = f"{save_dir}/{size}x{size}_{time_str}_noaudio" # save_pil_imgs(video, save_path) # save_path = batch_images_interpolation_tool(save_path, frame_inter_model, int(fps)) stream = ffmpeg.input(save_path) audio = ffmpeg.input(input_audio) ffmpeg.output(stream.video, audio.audio, save_path.replace('_noaudio.mp4', '.mp4'), vcodec='copy', acodec='aac', shortest=None).run() os.remove(save_path) return save_path.replace('_noaudio.mp4', '.mp4'), ref_image_pil #@spaces.GPU def video2video(ref_img, source_video, size=512, steps=25, length=60, seed=42): cfg = 3.5 fi_step = 3 generator = torch.manual_seed(seed) lmk_extractor = LMKExtractor() vis = FaceMeshVisualizer() width, height = size, size date_str = datetime.now().strftime("%Y%m%d") time_str = datetime.now().strftime("%H%M") save_dir_name = f"{time_str}--seed_{seed}-{size}x{size}" save_dir = Path(f"v2v_output/{date_str}/{save_dir_name}") while os.path.exists(save_dir): save_dir = Path(f"v2v_output/{date_str}/{save_dir_name}_{np.random.randint(10000):04d}") save_dir.mkdir(exist_ok=True, parents=True) ref_image_np = cv2.cvtColor(ref_img, cv2.COLOR_RGB2BGR) # ref_image_np = crop_face(ref_image_np, lmk_extractor) if ref_image_np is None: return None, Image.fromarray(ref_img) ref_image_np = cv2.resize(ref_image_np, (size, size)) ref_image_pil = Image.fromarray(cv2.cvtColor(ref_image_np, cv2.COLOR_BGR2RGB)) face_result = lmk_extractor(ref_image_np) if face_result is None: return None, ref_image_pil lmks = face_result['lmks'].astype(np.float32) ref_pose = vis.draw_landmarks((ref_image_np.shape[1], ref_image_np.shape[0]), lmks, normed=True) source_images = read_frames(source_video) src_fps = get_fps(source_video) pose_transform = transforms.Compose( [transforms.Resize((height, width)), transforms.ToTensor()] ) step = 1 if src_fps == 60: src_fps = 30 step = 2 pose_trans_list = [] verts_list = [] bs_list = [] args_L = len(source_images) if length==0 or length*step > len(source_images) else length*step args_L = min(args_L, 90*step) for src_image_pil in source_images[: args_L : step*fi_step]: src_img_np = cv2.cvtColor(np.array(src_image_pil), cv2.COLOR_RGB2BGR) frame_height, frame_width, _ = src_img_np.shape src_img_result = lmk_extractor(src_img_np) if src_img_result is None: break pose_trans_list.append(src_img_result['trans_mat']) verts_list.append(src_img_result['lmks3d']) bs_list.append(src_img_result['bs']) trans_mat_arr = np.array(pose_trans_list) verts_arr = np.array(verts_list) bs_arr = np.array(bs_list) min_bs_idx = np.argmin(bs_arr.sum(1)) # compute delta pose pose_arr = np.zeros([trans_mat_arr.shape[0], 6]) for i in range(pose_arr.shape[0]): euler_angles, translation_vector = matrix_to_euler_and_translation(trans_mat_arr[i]) # real pose of source pose_arr[i, :3] = euler_angles pose_arr[i, 3:6] = translation_vector init_tran_vec = face_result['trans_mat'][:3, 3] # init translation of tgt pose_arr[:, 3:6] = pose_arr[:, 3:6] - pose_arr[0, 3:6] + init_tran_vec # (relative translation of source) + (init translation of tgt) pose_arr_smooth = smooth_pose_seq(pose_arr, window_size=3) pose_mat_smooth = [euler_and_translation_to_matrix(pose_arr_smooth[i][:3], pose_arr_smooth[i][3:6]) for i in range(pose_arr_smooth.shape[0])] pose_mat_smooth = np.array(pose_mat_smooth) # face retarget verts_arr = verts_arr - verts_arr[min_bs_idx] + face_result['lmks3d'] # project 3D mesh to 2D landmark projected_vertices = project_points_with_trans(verts_arr, pose_mat_smooth, [frame_height, frame_width]) pose_list = [] for i, verts in enumerate(projected_vertices): lmk_img = vis.draw_landmarks((frame_width, frame_height), verts, normed=False) pose_image_np = cv2.resize(lmk_img, (width, height)) pose_list.append(pose_image_np) pose_list = np.array(pose_list) video_length = len(pose_list) video = pipe( ref_image_pil, pose_list, ref_pose, width, height, video_length, steps, cfg, generator=generator, ).videos #video = batch_images_interpolation_tool(video, frame_inter_model, inter_frames=fi_step-1) save_path = f"{save_dir}/{size}x{size}_{time_str}_noaudio.mp4" save_videos_grid( video, save_path, n_rows=1, fps=src_fps, ) # save_path = f"{save_dir}/{size}x{size}_{time_str}_noaudio" # save_pil_imgs(video, save_path) # save_path = batch_images_interpolation_tool(save_path, frame_inter_model, int(src_fps)) audio_output = f'{save_dir}/audio_from_video.aac' # extract audio try: ffmpeg.input(source_video).output(audio_output, acodec='copy').run() # merge audio and video stream = ffmpeg.input(save_path) audio = ffmpeg.input(audio_output) ffmpeg.output(stream.video, audio.audio, save_path.replace('_noaudio.mp4', '.mp4'), vcodec='copy', acodec='aac', shortest=None).run() os.remove(save_path) os.remove(audio_output) except: shutil.move( save_path, save_path.replace('_noaudio.mp4', '.mp4') ) return save_path.replace('_noaudio.mp4', '.mp4'), ref_image_pil ################# GUI ################ title = r""" <h1>AniPortrait</h1> """ description = r""" <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/Zejun-Yang/AniPortrait' target='_blank'><b>AniPortrait: Audio-Driven Synthesis of Photorealistic Portrait Animations</b></a>.<br> """ tips = r""" Here is an accelerated version of AniPortrait. Due to limitations in computing power, the wait time will be quite long. Please utilize the source code to experience the full performance. """ with gr.Blocks() as demo: gr.Markdown(title) gr.Markdown(description) gr.Markdown(tips) with gr.Tab("Audio2video"): with gr.Row(): with gr.Column(): with gr.Row(): a2v_input_audio = gr.Audio(sources=["upload", "microphone"], type="filepath", editable=True, label="Input audio", interactive=True) a2v_ref_img = gr.Image(label="Upload reference image", sources="upload") a2v_headpose_video = gr.Video(label="Option: upload head pose reference video", sources="upload") with gr.Row(): a2v_size_slider = gr.Slider(minimum=256, maximum=512, step=8, value=384, label="Video size (-W & -H)") a2v_step_slider = gr.Slider(minimum=5, maximum=20, step=1, value=15, label="Steps (--steps)") with gr.Row(): a2v_length = gr.Slider(minimum=0, maximum=1800, step=1, value=30, label="Length (-L)") a2v_seed = gr.Number(value=42, label="Seed (--seed)") a2v_botton = gr.Button("Generate", variant="primary") a2v_output_video = gr.PlayableVideo(label="Result", interactive=False) gr.Examples( examples=[ ["configs/inference/audio/lyl.wav", "configs/inference/ref_images/Aragaki.png", None], ["configs/inference/audio/lyl.wav", "configs/inference/ref_images/solo.png", None], ["configs/inference/audio/lyl.wav", "configs/inference/ref_images/lyl.png", "configs/inference/head_pose_temp/pose_ref_video.mp4"], ], inputs=[a2v_input_audio, a2v_ref_img, a2v_headpose_video], ) with gr.Tab("Video2video"): with gr.Row(): with gr.Column(): with gr.Row(): v2v_ref_img = gr.Image(label="Upload reference image", sources="upload") v2v_source_video = gr.Video(label="Upload source video", sources="upload") with gr.Row(): v2v_size_slider = gr.Slider(minimum=256, maximum=512, step=8, value=384, label="Video size (-W & -H)") v2v_step_slider = gr.Slider(minimum=5, maximum=20, step=1, value=15, label="Steps (--steps)") with gr.Row(): v2v_length = gr.Slider(minimum=0, maximum=90, step=1, value=30, label="Length (-L)") v2v_seed = gr.Number(value=42, label="Seed (--seed)") v2v_botton = gr.Button("Generate", variant="primary") v2v_output_video = gr.PlayableVideo(label="Result", interactive=False) gr.Examples( examples=[ ["configs/inference/ref_images/Aragaki.png", "configs/inference/video/Aragaki_song.mp4"], ["configs/inference/ref_images/solo.png", "configs/inference/video/Aragaki_song.mp4"], ["configs/inference/ref_images/lyl.png", "configs/inference/head_pose_temp/pose_ref_video.mp4"], ], inputs=[v2v_ref_img, v2v_source_video, a2v_headpose_video], ) a2v_botton.click( fn=audio2video, inputs=[a2v_input_audio, a2v_ref_img, a2v_headpose_video, a2v_size_slider, a2v_step_slider, a2v_length, a2v_seed], outputs=[a2v_output_video, a2v_ref_img] ) v2v_botton.click( fn=video2video, inputs=[v2v_ref_img, v2v_source_video, v2v_size_slider, v2v_step_slider, v2v_length, v2v_seed], outputs=[v2v_output_video, v2v_ref_img] ) demo.launch() 以上代码生成的视频只有一秒,帮我看一下哪里的问题
de9aee7e851179752b3b0e7ffc1ef5a4
{ "intermediate": 0.4456411898136139, "beginner": 0.3398410975933075, "expert": 0.214517742395401 }
45,880
hi
dc63f7a2041b1b6d991a89b1314d99de
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
45,881
RestSharp with Polly asp net core 6
f839f9c0edc0bf793f1654de6cd13ec8
{ "intermediate": 0.42125606536865234, "beginner": 0.22623613476753235, "expert": 0.3525078296661377 }