row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
32,422
class ImageService: """Service for image manipulations.""" @staticmethod def get_binary_image(image: np.ndarray) -> np.ndarray: """Gets binary image from image.""" binary_image = image.copy() binary_image[np.where(binary_image != 0)] = 255 return binary_image @staticmethod def count_zero_pixels(image_gray: np.ndarray) -> int: """Counts pixels with 0 intensity on black-white image.""" zero_pixels = np.count_nonzero(image_gray == 0) return zero_pixels @staticmethod def calculate_zero_pixel_percentage(image: np.ndarray) -> float: """Calculates zero intensity pixel's percentage.""" total_pixels = image.size zero_pixels = ImageService.count_zero_pixels(image) zero_percentage = zero_pixels / total_pixels * 100 return zero_percentage class TimeService: """Service for time management.""" def __init__(self, time_max: float): self.time_max = time_max self.start_time = None def start_timer(self) -> None: """Start time point. Sets 'self.start_time'.""" self.start_time = time.time() def check_timer(self): """Checks if time more than 'self.time_max'.""" end_time = time.time() delta_time = end_time - self.start_time if delta_time > self.time_max: return False return delta_time POTENTIAL_POINTS_NUM = 200 ITERATIONS_NUM = 1000 THRESHOLD_DISTANCE = 3 THRESHOLD_K = 0.5 THRESHOLD_B = 20 NOISE_LESS = 75 IMAGE_THRESHOLD_MIN = 0 IMAGE_THRESHOLD_MAX = 100 TIME_MAX = 1.8 class CornerDetector(object): """Class for corner detection on image.""" def __init__( self, potential_points_num: int = POTENTIAL_POINTS_NUM, iterations_num: int = ITERATIONS_NUM, threshold_distance: int = THRESHOLD_DISTANCE, threshold_k: float = THRESHOLD_K, threshold_b: int = THRESHOLD_B ): self.potential_points_num = potential_points_num self.iterations_num = iterations_num self.threshold_distance = threshold_distance self.threshold_k = threshold_k self.threshold_b = threshold_b self.image = None self.image_threshold = None self.time_service = TimeService(TIME_MAX) self.random_answer = np.array([[1, 1], [2, 2], [3, 3]]) def __get_coords_by_threshold( self, image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > self.image_threshold) return coords def __get_neigh_nums_list( self, coords: tuple, kernel_size: int = 3 ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's number. """ neigh_nums = [] offset = (kernel_size - 1) // 2 for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > self.image.shape[0] - offset: continue if y < 0 + offset or y > self.image.shape[1] - offset: continue kernel = self.image[x - offset:x + offset + 1, y - offset:y + offset + 1] step_neigh_num = np.count_nonzero(kernel) - 1 neigh_nums.append([x, y, step_neigh_num]) return neigh_nums @staticmethod def __sort_neigh_nums_by_N( neigh_nums: list ) -> np.ndarray: """ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. """ np_neigh_nums = np.array(neigh_nums) np_neigh_nums = np_neigh_nums[np_neigh_nums[:, 2] != 0] sorted_indices = np.argsort(-np_neigh_nums[:, 2]) np_neigh_nums = np_neigh_nums[sorted_indices] return np_neigh_nums def __get_potential_points_coords( self, sorted_niegh_nums: np.ndarray ) -> np.ndarray: """ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. """ sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1) return sorted_neigh_nums[:self.potential_points_num] def __get_best_lines( self, potential_points: np.ndarray ) -> np.ndarray: """ Gets the best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ remaining_points = 0 best_lines = [] num_lines = 0 while num_lines < 3: if not self.time_service.check_timer(): return self.random_answer if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inlines = [] best_line = None if len(remaining_points) == 0: remaining_points = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) for i in range(self.iterations_num): sample_indices = np.random.choice( remaining_points.shape[0], size=(self.iterations_num, 3), replace=True) sample_points = remaining_points[sample_indices] sample_x = sample_points[:, 1] sample_y = sample_points[:, 0] coefficients = np.polyfit(sample_x, sample_y, deg=1) distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inlines = np.where(distances < self.threshold_distance)[0] is_similar = False for line in best_lines: diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[1] - line[1]) if diff_k <= self.threshold_k and diff_b <= self.threshold_b: is_similar = True break if not is_similar and len(inlines) > len(best_inlines): best_line = coefficients best_inlines = inlines if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inlines, axis=0) num_lines += 1 return np.array(best_lines) def find_corners(self, image: np.ndarray) -> np.ndarray: """Finding triangle corners on image process.""" self.time_service.start_timer() self.image = image zero_percentage = ImageService.calculate_zero_pixel_percentage(image) if zero_percentage > NOISE_LESS: self.image_threshold = IMAGE_THRESHOLD_MIN else: self.image_threshold = IMAGE_THRESHOLD_MAX # Noise i cannot realise. if zero_percentage < 45: return self.random_answer coords = self.__get_coords_by_threshold(image) if not self.time_service.check_timer(): return self.random_answer neigh_nums = self.__get_neigh_nums_list(coords) if not self.time_service.check_timer(): return self.random_answer sorted_neigh_nums = self.__sort_neigh_nums_by_N(neigh_nums) if not self.time_service.check_timer(): return self.random_answer potential_points = self.__get_potential_points_coords(sorted_neigh_nums) if not self.time_service.check_timer(): return self.random_answer best_lines = self.__get_best_lines(potential_points) if not self.time_service.check_timer(): return self.random_answer intersection_points = np.linalg.solve( np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), [-best_lines[0][1], -best_lines[1][1]]) intersection_points = np.vstack((intersection_points, np.linalg.solve( np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), [-best_lines[0][1], -best_lines[2][1]]))) intersection_points = np.vstack((intersection_points, np.linalg.solve( np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), [-best_lines[1][1], -best_lines[2][1]]))) return intersection_points class Solver(object): def __init__(self): self.alg = CornerDetector() def solve(self, image_gray: np.ndarray) -> np.ndarray: result = self.alg.find_corners(image_gray) return result image = cv2.imread("0.3/02.pgm", cv2.COLOR_BGR2GRAY) solver = Solver() solver.solve(image) ПОЛУЧАЮ ВОТ ТАКУЮ ОШИБКУ: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-45-4c8a0c34fe22> in <cell line: 11>() 9 image = cv2.imread("0.3/02.pgm", cv2.COLOR_BGR2GRAY) 10 solver = Solver() ---> 11 solver.solve(image) 4 frames /usr/local/lib/python3.10/dist-packages/numpy/lib/polynomial.py in polyfit(x, y, deg, rcond, full, w, cov) 634 raise ValueError("expected deg >= 0") 635 if x.ndim != 1: --> 636 raise TypeError("expected 1D vector for x") 637 if x.size == 0: 638 raise TypeError("expected non-empty vector for x") TypeError: expected 1D vector for x ЧТО ДЕЛАТЬ?!?! ИСПРАВЬ!!!
22e8a0c0549495218fb3b259c5b84e7e
{ "intermediate": 0.3217918872833252, "beginner": 0.5325292944908142, "expert": 0.1456788033246994 }
32,423
package foleon.miningcore; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.plugin.java.JavaPlugin; public class CustomChat implements Listener { private final JavaPlugin plugin; public CustomChat(JavaPlugin plugin) { this.plugin = plugin; plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler public void onPlayerChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); String message = event.getMessage(); String formattedMessage = "[" + ChatColor.GRAY + "Player" + ChatColor.RESET + "] " + player.getName() + ": " + message; event.setFormat(formattedMessage); } } добавь в этот код чтобы если игрок был оператором то он бы получал префикс [owner] и скинь итоговый код
36987e86359173f2e25a9abf332af3e3
{ "intermediate": 0.4364241361618042, "beginner": 0.27647823095321655, "expert": 0.2870975434780121 }
32,424
以下是我的模型推理代码,我想把把它变成具有ui的web网站,然后可以直接调用用户的gpu进行推理,该怎么做呢: from modelscope import AutoTokenizer, AutoModel, snapshot_download model_dir = snapshot_download("01ai/Yi-6B-200K") model = AutoModel.from_pretrained(model_dir, trust_remote_code=True).half().cuda() # model = AutoModelForCausalLM.from_pretrained("01-ai/Yi-34B", device_map="auto", torch_dtype="auto", trust_remote_code=True) tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True) inputs = tokenizer("There's a place where time stands still. A place of breath taking wonder, but also", return_tensors="pt") max_length = 256 outputs = model.generate( inputs.input_ids.cuda(), max_length=max_length, eos_token_id=tokenizer.eos_token_id, do_sample=True, repetition_penalty=1.3, no_repeat_ngram_size=5, temperature=0.7, top_k=40, top_p=0.8, ) print(tokenizer.decode(outputs[0], skip_special_tokens=True))
9a4b21b4251cfcdb6253f66aa46b63bb
{ "intermediate": 0.4655773341655731, "beginner": 0.28005334734916687, "expert": 0.2543693780899048 }
32,425
python code using BiLSTM encoder and LSTM decoder rnn and attention layer to translate English text to Arabic text by splitting data from file into train. validate and test ,Tokenize the sentences and convert them into numerical representations ,Pad or truncate the sentences to a fixed length and use test data to evaluate and example translation from test
ab8d017a43d719b227dd2e159b2adbcb
{ "intermediate": 0.34519463777542114, "beginner": 0.08485053479671478, "expert": 0.5699547529220581 }
32,426
python code using BiLSTM encoder, LSTM decoder rnn and attention layer to translate English text to Arabic text by splitting data from file into train. validate and test ,Tokenize the sentences and convert them into numerical representations ,Pad or truncate the sentences to a fixed length and example translation from test data
4ef9de83120bab71b2d3d4c2edd76c1b
{ "intermediate": 0.3584964871406555, "beginner": 0.09602220356464386, "expert": 0.5454813241958618 }
32,427
Add a sub-bit sorting to this code: #include <iostream> #include <vector> #include <ctime> using namespace std; template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>*& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T>* root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i--) { cout << " " << a[i]; } } int main() { setlocale(LC_ALL, "Russian"); int n; cout << "Введите размер массива" << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << "Бинарное дерево - 1" << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort(C); clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << "sec" << endl; return 0; }
09087555f410eea39fe846e2d70fc689
{ "intermediate": 0.32519659399986267, "beginner": 0.424150288105011, "expert": 0.25065308809280396 }
32,428
Ihad made youtube shorts on Neena Gupta podcast with RanveerAllahbadia in which she is talking about aurat khunte se bandhi dor hai aur aadmi aakash me usne wala panchi now make Stronng SEO title, description, Tags that grab youtube audience for more views
be5c9e04df96234b9a6f7de35ed687b3
{ "intermediate": 0.2913563847541809, "beginner": 0.3405923843383789, "expert": 0.3680512011051178 }
32,429
Добавь в данный код Radixsort подразрядную сортировку , не изменяя сортировку деревом#include <iostream> #include <vector> #include <ctime> using namespace std; template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>*& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T>* root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i--) { cout << " " << a[i]; } } int main() { setlocale(LC_ALL, "Russian"); int n; cout << "Введите размер массива" << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << "Бинарное дерево - 1" << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort(C); clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << "sec" << endl; return 0; }
9ea327ff87ddbc99ce81eda9011b0b1e
{ "intermediate": 0.3136706054210663, "beginner": 0.4753393530845642, "expert": 0.2109900414943695 }
32,430
Develop an algorithm and a C++ program running in O(Logn) time, to find a key k in a weight-balanced tree.
fd2ad45310f0e1b7cb9046018f37cf58
{ "intermediate": 0.058402903378009796, "beginner": 0.041603583842515945, "expert": 0.8999935388565063 }
32,431
class ImageService: “”“Service for image manipulations.”“” @staticmethod def get_binary_image(image: np.ndarray) -> np.ndarray: “”“Gets binary image from image.”“” binary_image = image.copy() binary_image[np.where(binary_image != 0)] = 255 return binary_image @staticmethod def count_zero_pixels(image_gray: np.ndarray) -> int: “”“Counts pixels with 0 intensity on black-white image.”“” zero_pixels = np.count_nonzero(image_gray == 0) return zero_pixels @staticmethod def calculate_zero_pixel_percentage(image: np.ndarray) -> float: “”“Calculates zero intensity pixel’s percentage.”“” total_pixels = image.size zero_pixels = ImageService.count_zero_pixels(image) zero_percentage = zero_pixels / total_pixels * 100 return zero_percentage class TimeService: “”“Service for time management.”“” def init(self, time_max: float): self.time_max = time_max self.start_time = None def start_timer(self) -> None: “”“Start time point. Sets ‘self.start_time’.”“” self.start_time = time.time() def check_timer(self): “”“Checks if time more than ‘self.time_max’.”“” end_time = time.time() delta_time = end_time - self.start_time if delta_time > self.time_max: return False return delta_time POTENTIAL_POINTS_NUM = 200 ITERATIONS_NUM = 1000 THRESHOLD_DISTANCE = 3 THRESHOLD_K = 0.5 THRESHOLD_B = 20 NOISE_LESS = 75 IMAGE_THRESHOLD_MIN = 0 IMAGE_THRESHOLD_MAX = 100 TIME_MAX = 1.8 class CornerDetector(object): “”“Class for corner detection on image.”“” def init( self, potential_points_num: int = POTENTIAL_POINTS_NUM, iterations_num: int = ITERATIONS_NUM, threshold_distance: int = THRESHOLD_DISTANCE, threshold_k: float = THRESHOLD_K, threshold_b: int = THRESHOLD_B ): self.potential_points_num = potential_points_num self.iterations_num = iterations_num self.threshold_distance = threshold_distance self.threshold_k = threshold_k self.threshold_b = threshold_b self.image = None self.image_threshold = None self.time_service = TimeService(TIME_MAX) self.random_answer = np.array([[1, 1], [2, 2], [3, 3]]) def __get_coords_by_threshold( self, image: np.ndarray, ) -> tuple: “”“Gets coordinates with intensity more than ‘image_threshold’.”“” coords = np.where(image > self.image_threshold) return coords def __get_neigh_nums_list( self, coords: tuple, kernel_size: int = 3 ) -> list: “”“ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood’s number. “”” neigh_nums = [] offset = (kernel_size - 1) // 2 for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > self.image.shape[0] - offset: continue if y < 0 + offset or y > self.image.shape[1] - offset: continue kernel = self.image[x - offset:x + offset + 1, y - offset:y + offset + 1] step_neigh_num = np.count_nonzero(kernel) - 1 neigh_nums.append([x, y, step_neigh_num]) return neigh_nums @staticmethod def __sort_neigh_nums_by_N( neigh_nums: list ) -> np.ndarray: “”“ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. “”” np_neigh_nums = np.array(neigh_nums) np_neigh_nums = np_neigh_nums[np_neigh_nums[:, 2] != 0] sorted_indices = np.argsort(-np_neigh_nums[:, 2]) np_neigh_nums = np_neigh_nums[sorted_indices] return np_neigh_nums def __get_potential_points_coords( self, sorted_niegh_nums: np.ndarray ) -> np.ndarray: “”“ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. “”” sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1) return sorted_neigh_nums[:self.potential_points_num] def __get_best_lines( self, potential_points: np.ndarray ) -> np.ndarray: “”“ Gets the best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. “”” remaining_points = 0 best_lines = [] num_lines = 0 while num_lines < 3: if not self.time_service.check_timer(): return self.random_answer if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}“) best_inlines = [] best_line = None if len(remaining_points) == 0: remaining_points = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) for i in range(self.iterations_num): sample_indices = np.random.choice( remaining_points.shape[0], size=(self.iterations_num, 3), replace=True) sample_points = remaining_points[sample_indices] sample_x = sample_points[:, 1] sample_y = sample_points[:, 0] coefficients = np.polyfit(sample_x, sample_y, deg=1) distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inlines = np.where(distances < self.threshold_distance)[0] is_similar = False for line in best_lines: diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[1] - line[1]) if diff_k <= self.threshold_k and diff_b <= self.threshold_b: is_similar = True break if not is_similar and len(inlines) > len(best_inlines): best_line = coefficients best_inlines = inlines if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inlines, axis=0) num_lines += 1 return np.array(best_lines) def find_corners(self, image: np.ndarray) -> np.ndarray: “”“Finding triangle corners on image process.””" self.time_service.start_timer() self.image = image zero_percentage = ImageService.calculate_zero_pixel_percentage(image) if zero_percentage > NOISE_LESS: self.image_threshold = IMAGE_THRESHOLD_MIN else: self.image_threshold = IMAGE_THRESHOLD_MAX # Noise i cannot realise. if zero_percentage < 45: return self.random_answer coords = self.__get_coords_by_threshold(image) if not self.time_service.check_timer(): return self.random_answer neigh_nums = self.__get_neigh_nums_list(coords) if not self.time_service.check_timer(): return self.random_answer sorted_neigh_nums = self.__sort_neigh_nums_by_N(neigh_nums) if not self.time_service.check_timer(): return self.random_answer potential_points = self.__get_potential_points_coords(sorted_neigh_nums) if not self.time_service.check_timer(): return self.random_answer best_lines = self.__get_best_lines(potential_points) if not self.time_service.check_timer(): return self.random_answer intersection_points = np.linalg.solve( np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), [-best_lines[0][1], -best_lines[1][1]]) intersection_points = np.vstack((intersection_points, np.linalg.solve( np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), [-best_lines[0][1], -best_lines[2][1]]))) intersection_points = np.vstack((intersection_points, np.linalg.solve( np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), [-best_lines[1][1], -best_lines[2][1]]))) return intersection_points class Solver(object): def init(self): self.alg = CornerDetector() def solve(self, image_gray: np.ndarray) -> np.ndarray: result = self.alg.find_corners(image_gray) return result image = cv2.imread(“0.3/02.pgm”, cv2.COLOR_BGR2GRAY) solver = Solver() solver.solve(image) Все та же ошибка: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-45-4c8a0c34fe22> in <cell line: 11>() 9 image = cv2.imread("0.3/02.pgm", cv2.COLOR_BGR2GRAY) 10 solver = Solver() ---> 11 solver.solve(image) 4 frames <ipython-input-45-4c8a0c34fe22> in solve(self, image_gray) 4 5 def solve(self, image_gray: np.ndarray) -> np.ndarray: ----> 6 result = self.alg.find_corners(image_gray) 7 return result 8 <ipython-input-44-d6a27acf204a> in find_corners(self, image) 167 return self.random_answer 168 --> 169 best_lines = self.__get_best_lines(potential_points) 170 if not self.time_service.check_timer(): 171 return self.random_answer <ipython-input-44-d6a27acf204a> in __get_best_lines(self, potential_points) 110 sample_x = sample_points[:, 1] 111 sample_y = sample_points[:, 0] --> 112 coefficients = np.polyfit(sample_y, sample_x, deg=1) 113 distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) 114 inlines = np.where(distances < self.threshold_distance)[0] /usr/local/lib/python3.10/dist-packages/numpy/core/overrides.py in polyfit(*args, **kwargs) /usr/local/lib/python3.10/dist-packages/numpy/lib/polynomial.py in polyfit(x, y, deg, rcond, full, w, cov) 634 raise ValueError("expected deg >= 0") 635 if x.ndim != 1: --> 636 raise TypeError("expected 1D vector for x") 637 if x.size == 0: 638 raise TypeError("expected non-empty vector for x") TypeError: expected 1D vector for x Что делать??!?!?!
3d4b5aff856c2edeb11c43d3dc72170f
{ "intermediate": 0.2589637041091919, "beginner": 0.3415154814720154, "expert": 0.39952078461647034 }
32,432
write a c++ programm printing 3 random number using default_random_engine
082f65f9aade367ca629827d99b8e7f2
{ "intermediate": 0.29418811202049255, "beginner": 0.2925143241882324, "expert": 0.413297563791275 }
32,433
Добавь в данный код Radixsort подразрядную сортировку , не изменяя сортировку деревом#include #include <vector> #include <ctime> using namespace std; template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T> root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i–) { cout << " " << a[i]; } } int main() { setlocale(LC_ALL, “Russian”); int n; cout << “Введите размер массива” << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << “Бинарное дерево - 1” << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort©; clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << “sec” << endl; return 0; }
f03bd51e31d86363f99cbc32392c580e
{ "intermediate": 0.34346508979797363, "beginner": 0.3651477098464966, "expert": 0.29138725996017456 }
32,434
#define decl_val(name, len) \ virtual uint##len##_t name() const { return 0; } #define decl_var(name, len) \ virtual uint##len##_t &name() { return j##len(); } \ decl_val(name, len)
c8fa97c38d74b5e63b76f42550fac1b4
{ "intermediate": 0.32725393772125244, "beginner": 0.4586624503135681, "expert": 0.21408355236053467 }
32,435
I need you to make a todolist app using svelte stores, demonstrate it in code
0fad754c423666eb7b05c18cc1154312
{ "intermediate": 0.3372304439544678, "beginner": 0.2555464506149292, "expert": 0.407223105430603 }
32,436
use imagemagik and python to distort the image then add an annotation at "/home/brrt/Pictures/icons/panties.png"
0559f70b08a84c0dc9bd25e8dd6d3bb7
{ "intermediate": 0.3814374506473541, "beginner": 0.2139117270708084, "expert": 0.40465086698532104 }
32,437
"0x2013": этот символ недопустим как первый символ идентификатора строка 105 синтаксическая ошибка: непредвиденный элемент ")". Ожидается "выражение" строка 103 синтаксическая ошибка: непредвиденный маркер "идентификатор" после "expression" строка 105 #include <iostream> #include <vector> #include <ctime> using namespace std; template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>*& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T>* root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i--) { cout << " " << a[i]; } } template<class T> void radixSort(vector<T>& a) { // Находим максимальное значение в массиве, чтобы определить количество позиций T max_value = *max_element(a.begin(), a.end()); // Делаем сортировку по каждой разрядности (от младшей к старшей) for (T exp = 1; max_value / exp > 0; exp *= 10) { vector<T> output(a.size()); vector<int> count(10, 0); // Подсчитываем количество элементов для каждой цифры for (int i = 0; i < a.size(); i++) { count[(a[i] / exp) % 10]++; } // Считаем сумму до текущей позиции, чтобы знать индексы for (int i = 1; i < 10; i++) { count[i] += count[i - 1]; } // Формируем отсортированный массив for (int i = a.size() - 1; i >= 0; i-) { output[count[(a[i] / exp) % 10] - 1] = a[i]; count[(a[i] / exp) % 10]–; } // Копируем отсортированный массив обратно в исходный for (int i = 0; i < a.size(); i++) { a[i] = output[i]; } } } int main() { setlocale(LC_ALL, "Russian"); int n; cout << "Введите размер массива" << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << "Бинарное дерево - 1" << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort(C); if (flag == 2) radixSort(C); clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << "sec" << endl; return 0; }
ad36252cc85c058982a37629db3f4d0d
{ "intermediate": 0.3390144407749176, "beginner": 0.37932926416397095, "expert": 0.28165629506111145 }
32,438
class Turntable { constructor(canvasId) { this.canvas = document.getElementById(canvasId); this.ctx = this.canvas.getContext('2d'); this.refreshButton = document.getElementById('update'); this.rotateButton = document.getElementById('rotate'); this.isSpinning = false; this.spinSpeed = 0.2; this.decelerationRate = 0.01; this.numberOfSectors = 0; // 存储扇形数量 this.refreshButton.addEventListener('click', () => { this.refreshTurntable(); }); this.rotateButton.addEventListener('click', () => { this.startSpinAnimation(); }); } refreshTurntable() { this.numberOfSectors = this.generateRandomNumberOfSectors(); // 更新扇形数量 this.clearTurntable(); this.drawSectors(this.numberOfSectors); } generateRandomNumberOfSectors() { return Math.floor(Math.random() * 8) + 3; // 生成3-10之间的随机整数 } clearTurntable() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); } drawSectors(numberOfSectors) { const sectorAngle = this.calculateSectorAngle(numberOfSectors); const centerX = this.canvas.width / 2; const centerY = this.canvas.height / 2; const radius = Math.min(this.canvas.width, this.canvas.height) / 2 - 20; for (let i = 0; i < numberOfSectors; i++) { const startAngle = i * sectorAngle; const endAngle = (i + 1) * sectorAngle; this.ctx.beginPath(); this.ctx.moveTo(centerX, centerY); this.ctx.arc(centerX, centerY, radius, startAngle, endAngle); this.ctx.closePath(); const hue = (i * 360) / numberOfSectors; const randomColor = this.getRandomColor(); this.ctx.fillStyle = randomColor; this.ctx.fill(); } } getRandomColor() { const letters = '0123456789ABCDEF'; let color = '#'; for (let i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } calculateSectorAngle(numberOfSectors) { return (2 * Math.PI) / numberOfSectors; } startSpinAnimation() { if (this.isSpinning) return; this.isSpinning = true; this.spinSpeed = 0.2; this.spinAnimation(); } spinAnimation() { this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); this.ctx.rotate(this.spinSpeed); this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); this.spinSpeed -= this.decelerationRate; // 减速 if (this.spinSpeed > 0) { requestAnimationFrame(() => this.spinAnimation()); } else { this.isSpinning = false; } } } const turntable = new Turntable('gameCanvas'); 为什么点击旋转后转盘没有反应
af5f18b0e2c89a2123e5ded4ee52de72
{ "intermediate": 0.22980740666389465, "beginner": 0.46149176359176636, "expert": 0.308700829744339 }
32,439
Добавь в данный код метод сортировки подразрядную , не меняя метод сортировки деревом :#include <iostream> #include <vector> #include <ctime> #include <algorithm> using namespace std; template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>*& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T>* root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i--) { cout << " " << a[i]; } } int main() { setlocale(LC_ALL, "Russian"); int n; cout << "Введите размер массива" << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << "Бинарное дерево - 1" << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort(C); clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << "sec" << endl; return 0; }
bad9b8a49b50d6fd1e4ef1dbbee543f0
{ "intermediate": 0.34164363145828247, "beginner": 0.3898009955883026, "expert": 0.26855534315109253 }
32,440
使用JS类以及html设计一个随机转盘游戏,要求点击刷新可以更新扇形分布,点击开始可以进行旋转并且逐渐减慢速度暂停,可以选择顺逆时针进行旋转
db93515f21ee0ada529ac4a8df95b818
{ "intermediate": 0.4473576545715332, "beginner": 0.26133114099502563, "expert": 0.29131120443344116 }
32,441
app.get('/api/register', (req, res) => { const q = req.query db.run(`insert into users values (${q.username}, ${q.password}, ${q.email})`) res.send('success') }) throws: [Error: SQLITE_ERROR: unrecognized token: "123password" Emitted 'error' event on Statement instance at: ] { errno: 1, code: 'SQLITE_ERROR' }
de5dcfa269460c533cb618eb07f112e7
{ "intermediate": 0.3975719213485718, "beginner": 0.36215218901634216, "expert": 0.24027594923973083 }
32,442
class Turntable { constructor(canvasId) { this.canvas = document.getElementById(canvasId); this.ctx = this.canvas.getContext('2d'); this.refreshButton = document.getElementById('update'); this.rotateButton = document.getElementById('rotate'); this.isSpinning = false; this.spinSpeed = 0.2; this.decelerationRate = 0.01; this.numberOfSectors = 0; // 存储扇形数量 this.refreshButton.addEventListener('click', () => { this.refreshTurntable(); }); this.rotateButton.addEventListener('click', () => { this.startSpinAnimation(); }); } refreshTurntable() { this.numberOfSectors = this.generateRandomNumberOfSectors(); // 更新扇形数量 this.clearTurntable(); this.drawSectors(this.numberOfSectors); } generateRandomNumberOfSectors() { return Math.floor(Math.random() * 8) + 3; // 生成3-10之间的随机整数 } clearTurntable() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); } drawSectors(numberOfSectors) { const sectorAngle = this.calculateSectorAngle(numberOfSectors); const centerX = this.canvas.width / 2; const centerY = this.canvas.height / 2; const radius = Math.min(this.canvas.width, this.canvas.height) / 2 - 20; for (let i = 0; i < numberOfSectors; i++) { const startAngle = i * sectorAngle; const endAngle = (i + 1) * sectorAngle; this.ctx.beginPath(); this.ctx.moveTo(centerX, centerY); this.ctx.arc(centerX, centerY, radius, startAngle, endAngle); this.ctx.closePath(); const hue = (i * 360) / numberOfSectors; const randomColor = this.getRandomColor(); this.ctx.fillStyle = randomColor; this.ctx.fill(); } } getRandomColor() { const letters = '0123456789ABCDEF'; let color = '#'; for (let i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } spinAnimation() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); // 清除画布 this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); this.ctx.rotate(this.spinSpeed); this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); const sectorAngle = this.calculateSectorAngle(this.numberOfSectors); const centerX = this.canvas.width / 2; const centerY = this.canvas.height / 2; const radius = Math.min(this.canvas.width, this.canvas.height) / 2 - 20; for (let i = 0; i < this.numberOfSectors; i++) { const startAngle = i * sectorAngle; const endAngle = (i + 1) * sectorAngle; this.ctx.beginPath(); this.ctx.moveTo(centerX, centerY); this.ctx.arc(centerX, centerY, radius, startAngle, endAngle); this.ctx.closePath(); const hue = (i * 360) / this.numberOfSectors; const randomColor = this.getRandomColor(); this.ctx.fillStyle = randomColor; this.ctx.fill(); } this.spinSpeed -= this.decelerationRate; if (this.spinSpeed > 0) { requestAnimationFrame(() => this.spinAnimation()); } else { this.isSpinning = false; } } calculateSectorAngle(numberOfSectors) { return (2 * Math.PI) / numberOfSectors; } startSpinAnimation() { if (this.isSpinning) return; this.isSpinning = true; this.spinSpeed = 0.2; this.spinAnimation(); } } const turntable = new Turntable('gameCanvas'); 怎样使得旋转转盘颜色不发生改变,转盘旋转前后颜色一样,不改变
312553230582ec25dccfab773ea37a8a
{ "intermediate": 0.29329583048820496, "beginner": 0.5055087804794312, "expert": 0.20119543373584747 }
32,443
ScoreboardPlugin.java: package com.example.scoreboardplugin; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.java.JavaPlugin; public class ScoreboardPlugin extends JavaPlugin implements Listener { @Override public void onEnable() { // Регистрация слушателя событий Bukkit.getPluginManager().registerEvents(this, this); // Запуск задачи обновления scoreboard каждые 10 тиков Bukkit.getScheduler().runTaskTimer(this, this::updateScoreboard, 0, 10); } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { // Создание scoreboard при присоединении игрока Player player = event.getPlayer(); ScoreboardManager.createScoreboard(player); } public void updateScoreboard() { // Обновление scoreboard для всех онлайн игроков for (Player player : Bukkit.getOnlinePlayers()) { if (player.getScoreboard().getObjective(“scoreboard”) != null) { player.getScoreboard().getObjective(“scoreboard”).unregister(); } ScoreboardManager.createScoreboard(player); } } } ScoreboardUtil.java: package com.example.scoreboardplugin; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; public class ScoreboardUtil { private final Scoreboard scoreboard; private final Objective objective; public ScoreboardUtil(String title) { scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); objective = scoreboard.registerNewObjective(“scoreboard”, “dummy”); objective.setDisplaySlot(DisplaySlot.SIDEBAR); objective.setDisplayName(title); } public void addLine(String text) { objective.getScore(text).setScore(objective.getScoreboard().getEntries().size() + 1); } public void setScoreboard(Player player) { player.setScoreboard(scoreboard); } } ScoreboardManager.java: package com.example.scoreboardplugin; import org.bukkit.Bukkit; import org.bukkit.entity.Player; public class ScoreboardManager { public static void createScoreboard(Player player) { // Создание scoreboard ScoreboardUtil scoreboard = new ScoreboardUtil(“Mining Simulator”); scoreboard.addLine(“Ваш баланс:”); scoreboard.addLine(“вы сломали”); scoreboard.setScoreboard(player); } } допиши код чтобы в "ваш баланс: " писалась сумма gold игрока с конфига и скинь итоговый код всех классов. (Конфиг уже существует)
9e0069dc4432889905272e1d5c5a80c4
{ "intermediate": 0.23623748123645782, "beginner": 0.5368449091911316, "expert": 0.22691762447357178 }
32,444
from transformers import BertTokenizer, TFBertModel import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import classification_report # Load Quora dataset quora_data = pd.read_csv('questions.csv', nrows=6000) # Select a subset of the dataset for training #train_data = quora_data.sample(n=80) # Adjust the number of samples based on your requirements # Get the minimum length between question1 and question2 min_length = min(len(quora_data['question1']), len(quora_data['question2'])) # Adjust the number of samples based on the minimum length train_data = quora_data.sample(n=min_length) # Convert the question pairs to list format question1_list = list(train_data['question1']) question2_list = list(train_data['question2']) is_duplicate = list(train_data['is_duplicate']) # Create DataFrame for the first pair data1 = pd.DataFrame({'Sentences': question1_list, 'Labels': is_duplicate}) # Create DataFrame for the second pair data2 = pd.DataFrame({'Sentences': question2_list, 'Labels': is_duplicate}) # Concatenate the two DataFrames data = pd.concat([data1, data2], ignore_index=True) # Split data into train and test sets X_train, X_test, y_train, y_test = train_test_split(data['Sentences'], data['Labels'], test_size=0.2, random_state=42) # Initialize the TF-IDF vectorizer vectorizer = TfidfVectorizer() # Vectorize the sentences in train set X_train_vectors = vectorizer.fit_transform(X_train) # Vectorize the sentences in test set X_test_vectors = vectorizer.transform(X_test) # Initialize the SVM classifier svm = SVC() # Fit the classifier to the training data svm.fit(X_train_vectors, y_train) # Predict labels for the test data y_pred = svm.predict(X_test_vectors) # Print classification report print(classification_report(y_test, y_pred)) #svm_predictions = y_pred # Save the ‘is_duplicate’ column in an Excel file #result_df = pd.DataFrame({'is_duplicate': y_pred}) #result_df.to_excel('output.xlsx', index=False) # Save the questions and classification in an Excel file #data.to_excel(‘questions_classification.xlsx’, index=False) # Create DataFrame for test predictions result_df = pd.DataFrame({ 'Question1': list(test_data['question1']), 'Question2': list(test_data['question2']), 'is_duplicate': predictions.flatten() }) # Create DataFrame for test predictions #test_predictions = pd.DataFrame({'Question1': list(test_data['question1']), 'Question2': list(test_data['question2']), 'is_duplicate': predictions}) # Create DataFrame for test predictions #test_predictions = pd.DataFrame({'Question1': test_data['question1'], 'Question2': test_data['question2'], 'is_duplicate': predictions}) # Save the test predictions in an Excel file result_df.to_excel('test_predictions_SVM.xlsx', index=False) from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, f1_score, recall_score # Calculate metrics accuracy = accuracy_score(y_test, y_pred) cm = confusion_matrix(y_test, y_pred) precision = precision_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) recall = recall_score(y_test, y_pred) # Print the results: print("Accuracy:", accuracy) print("Confusion Matrix:") print(cm) print("Precision:", precision) print("F1 Score:", f1) print("Recall:", recall) NameError: name 'test_data' is not defined
2524f2e4af1ea5d30630c7d92656eb9a
{ "intermediate": 0.4513007402420044, "beginner": 0.3444914221763611, "expert": 0.20420783758163452 }
32,446
hello
dc21b23a3ba25e119009dcb797475c13
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
32,447
Добавь в данный код сортировку методом подразрядной: #include <iostream> #include <vector> #include <ctime> using namespace std; template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>*& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T>* root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i--) { cout << " " << a[i]; } } int main() { setlocale(LC_ALL, "Russian"); int n; cout << "Введите размер массива" << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << "Бинарное дерево - 1" << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort(C); clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << "sec" << endl; return 0; }
0c794fd06925d944b22d6351b96a8a8f
{ "intermediate": 0.3618195056915283, "beginner": 0.4478703737258911, "expert": 0.19031007587909698 }
32,448
add radix sorting to this code without changing the tree sorting. #include <iostream> #include <vector> #include <ctime> using namespace std; template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>*& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T>* root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i--) { cout << " " << a[i]; } } int main() { setlocale(LC_ALL, "Russian"); int n; cout << "Введите размер массива" << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << "Бинарное дерево - 1" << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort(C); clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << "sec" << endl; return 0; }
feb8d98b2a1a014a465a995cebef7334
{ "intermediate": 0.35548505187034607, "beginner": 0.4666714370250702, "expert": 0.17784349620342255 }
32,449
need to write php class
13f20c9440c4d1b725e3e53ef37a7e26
{ "intermediate": 0.15141132473945618, "beginner": 0.6875258088111877, "expert": 0.16106288135051727 }
32,450
read data from json file and unmarshal struct type in golang
08ee5918eace3ee933b42a0dbbfd7a3e
{ "intermediate": 0.611570417881012, "beginner": 0.15904468297958374, "expert": 0.22938483953475952 }
32,451
Write a movement code for my play it's a 3d game
2a2be8619dd016c04acc03965349d474
{ "intermediate": 0.3662239611148834, "beginner": 0.2645520865917206, "expert": 0.3692239224910736 }
32,452
исправь ошибки в 25 и 27 строчке:#include <iostream> #include <vector> #include <ctime> using namespace std; template <class T> void radixSort(vector<T>& a) { if (a.empty()) { return; } T maxNum = max_element(a.begin(), a.end()); for (int exp = 1; maxNum / exp > 0; exp = 10) { vector<T> count(10, 0); vector<T> output(a.size()); for (int i = 0; i < a.size(); i++) { count[(a[i] / exp) % 10]++; } for (int i = 1; i < 10; i++) { count[i] += count[i - 1]; } for (int i = a.size() - 1; i >= 0; i-) { output[count[(a[i] / exp) % 10] - 1] = a[i]; count[(a[i] / exp) % 10] -; } for (int i = 0; i < a.size(); i++) { a[i] = output[i]; } } } template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>*& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T>* root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i--) { cout << " " << a[i]; } } int main() { setlocale(LC_ALL, "Russian"); int n; cout << "Введите размер массива" << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << "Бинарное дерево - 1" << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort(C); if (flag == 2) radixSort(C); clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << "sec" << endl; return 0; }
11ba009704923e53ae3826de0cc4140c
{ "intermediate": 0.2862851023674011, "beginner": 0.4619000256061554, "expert": 0.2518148720264435 }
32,453
can you write a script in bash that will write pihole -g in terminal and press enter
244e35dbb96a330ad693939d51165ca2
{ "intermediate": 0.31941238045692444, "beginner": 0.39735177159309387, "expert": 0.2832358479499817 }
32,454
Добавь сортировку из данного кода: template<class T> void radix_sort(vector<T> &data) { static_assert(numeric_limits<T>::is_integer && !numeric_limits<T>::is_signed, "radix_sort only supports unsigned integer types"); constexpr int word_bits = numeric_limits<T>::digits; // max_bits = floor(log n / 3) // num_groups = ceil(word_bits / max_bits) int max_bits = 1; while ((size_t(1) << (3 * (max_bits+1))) <= data.size()) { ++max_bits; } const int num_groups = (word_bits + max_bits - 1) / max_bits; // Temporary arrays. vector<size_t> count; vector<T> new_data(data.size()); // Iterate over bit groups, starting from the least significant. for (int group = 0; group < num_groups; ++group) { // The current bit range. const int start = group * word_bits / num_groups; const int end = (group+1) * word_bits / num_groups; const T mask = (size_t(1) << (end - start)) - T(1); // Count the values in the current bit range. count.assign(size_t(1) << (end - start), 0); for (const T &x : data) ++count[(x >> start) & mask]; // Compute prefix sums in count. size_t sum = 0; for (size_t &c : count) { size_t new_sum = sum + c; c = sum; sum = new_sum; } // Shuffle data elements. for (const T &x : data) { size_t &pos = count[(x >> start) & mask]; new_data[pos++] = x; } // Move the data to the original array. data.swap(new_data); } } Сюда: #include <iostream> #include <vector> #include <ctime> using namespace std; template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>*& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T>* root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i--) { cout << " " << a[i]; } } int main() { setlocale(LC_ALL, "Russian"); int n; cout << "Введите размер массива" << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << "Бинарное дерево - 1" << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort(C); clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << "sec" << endl; return 0; }
2e3380903f03f891d8c25b8fc4cc80ac
{ "intermediate": 0.42071986198425293, "beginner": 0.33610302209854126, "expert": 0.2431771159172058 }
32,455
class TradingPlatform: def buy_order(self, price, quantity): print(f"Buying ${price:.2f}\t{quantity:.4f}") def place_stop_loss_order(self, price): print(f"Stop Loss order placed at ${price:.2f}") def calculate_order_sizes(total_equity, num_orders, equity_to_risk): risk_amount = total_equity * equity_to_risk order_sizes = [] for i in range(num_orders): order_allocation = (i + 1) / num_orders order_size = risk_amount * order_allocation order_sizes.append(round(order_size, 4)) return order_sizes def adjust_position_sizes(order_sizes, stop_loss_percent): total_risk = sum(order_sizes) stop_loss_multiplier = 1 / (1 - stop_loss_percent) adjusted_sizes = [size * stop_loss_multiplier for size in order_sizes] return adjusted_sizes def place_scaled_buy_orders(entry_price, num_orders, total_equity, trading_platform, equity_to_risk, stop_loss_percent): price_range = entry_price * price_range_percent start_price = entry_price stop_price = entry_price - price_range order_sizes = calculate_order_sizes(total_equity, num_orders, equity_to_risk) adjusted_sizes = adjust_position_sizes(order_sizes, stop_loss_percent) price_gap = price_range / (num_orders - 1) orders = [] for i in range(num_orders): orders.append((round(start_price, 2), adjusted_sizes[i])) start_price -= price_gap stop_loss_price = min(orders, key=lambda x: x[0])[0] * (1 - stop_loss_percent) for order in orders: trading_platform.buy_order(order[0], order[1]) trading_platform.place_stop_loss_order(stop_loss_price) import requests, time, hashlib, hmac, uuid, user recv_window = str(5000); method_post = "POST"; method_get ="GET" def HTTP_Request(endPoint, method, payload, Info): timestamp = str(int(time.time() * 10 ** 3)) user.headers.update({'X-BAPI-TIMESTAMP': timestamp, 'X-BAPI-SIGN': genSignature(timestamp, payload, recv_window)}) url_with_endpoint = user.url_bybit_trade + endPoint; data = payload if method == "POST" else None response = requests.Session().request(method, f"{url_with_endpoint}?{payload}" if method != "POST" else url_with_endpoint, headers=user.headers, data=data) print(response.text, f"{Info}") def genSignature(time_stamp, payload, recv_window): param_str = str(time_stamp) + user.api_key + recv_window + payload hash_obj = hmac.new(bytes(user.secret_key, "utf-8"), param_str.encode("utf-8"), hashlib.sha256) signature = hash_obj.hexdigest() return signature response = requests.get(user.url_current_price, params={'symbol': user.symbol}) if response.status_code == 200: data = response.json() current_price = float(data['result'][0]['last_price']) entry_price = current_price num_orders = 15 total_equity = 10000 equity_to_risk = 0.1 stop_loss_percent = 0.1 price_range_percent = 0.02 platform = TradingPlatform() place_scaled_buy_orders(entry_price, num_orders, total_equity, platform, equity_to_risk, stop_loss_percent) buy_orderLinkId, sell_orderLinkId = uuid.uuid4().hex, uuid.uuid4().hex params_get_ballance ='category=linear&coin=USDT&accountType=CONTRACT' HTTP_Request(user.endpoint_get_ballance,method_get,params_get_ballance,"Ballance") #Get Ballance leverage_params = f'{{"category":"linear","symbol": "{user.symbol}","buyLeverage": "{user.buy_lev}","sellLeverage": "{user.sell_lev}"}}' HTTP_Request(user.endpoint_lev, method_post, leverage_params, "Leverage") # Set Leverage cancel_all_stop_params = f'{{"category":"linear","symbol": "{user.symbol}"}}' HTTP_Request(user.endpoint_cancel_all, method_post, cancel_all_stop_params, "Cancel All Unfilled Orders") the response from the user.endpoint_get_ballance contains an "equity" value which I would like to replace the "total_equity" with here is an example of the ballance responce {"retCode":0,"retMsg":"OK","result":{"list":[{"accountType":"CONTRACT","accountIMRate":"","accountMMRate":"","totalEquity":"","totalWalletBalance":"","totalMarginBalance":"","totalAvailableBalance":"","totalPerpUPL":"","totalInitialMargin":"","totalMaintenanceMargin":"","accountLTV":"","coin":[{"coin":"USDT","equity":"3023.68687057","usdValue":"","walletBalance":"3023.68687057","borrowAmount":"","availableToBorrow":"","availableToWithdraw":"3023.68687057","accruedInterest":"","totalOrderIM":"0","totalPositionIM":"0","totalPositionMM":"","unrealisedPnl":"0","cumRealisedPnl":"-6976.31312943"}]}]},"retExtInfo":{},"time":1701021698927} Ballance
f2d2143ade848dafcab87d5f4a560962
{ "intermediate": 0.28516480326652527, "beginner": 0.488953173160553, "expert": 0.22588197886943817 }
32,456
create ray tracing program in c++ under 400 lines.
a6fed1a9b2428ca13cec045654ed021c
{ "intermediate": 0.23277555406093597, "beginner": 0.12975774705410004, "expert": 0.6374667286872864 }
32,457
feature_group<-list(CognitiveSymptoms=c(1:6),CESD-10symptoms=c(7:16)) Error: unexpected symbol in "feature_group<-list(CognitiveSymptoms=c(1:6),CESD-10symptoms"該如何修改
841ff9c8bc6ade1beac954c50d603a1d
{ "intermediate": 0.323384165763855, "beginner": 0.25959476828575134, "expert": 0.4170210361480713 }
32,458
Is there any kind of Java exception that serves as a boilerplate basic exception, where I can provide to it a message and that's it?
3072d07f411f3a2b46e812cd89e701a2
{ "intermediate": 0.5912207365036011, "beginner": 0.1297547072172165, "expert": 0.27902457118034363 }
32,459
from transformers import BertTokenizer, TFBertModel import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.svm import SVC from sklearn.metrics import classification_report # Load Quora dataset quora_data = pd.read_csv('questions.csv', nrows=6000) # Select a subset of the dataset for training #train_data = quora_data.sample(n=80) # Adjust the number of samples based on your requirements # Get the minimum length between question1 and question2 #min_length = min(len(quora_data['question1']), len(quora_data['question2'])) # Adjust the number of samples based on the minimum length #train_data = quora_data_train.sample(n=5000) # Select the first 5000 samples as the training set train_data = quora_data[:5000] # Convert the question pairs to list format question1_list = list(train_data['question1']) question2_list = list(train_data['question2']) is_duplicate = list(train_data['is_duplicate']) # Create DataFrame for the first pair data1 = pd.DataFrame({'Sentences': question1_list, 'Labels': is_duplicate}) # Create DataFrame for the second pair data2 = pd.DataFrame({'Sentences': question2_list, 'Labels': is_duplicate}) # Concatenate the two DataFrames data = pd.concat([data1, data2], ignore_index=True) # Split data into train and test sets #X_train, X_test, y_train, y_test = train_test_split(data['Sentences'], data['Labels'], test_size=0.1, random_state=42) # Split data into train and test sets X_train = data['Sentences'][:5000] X_test = data['Sentences'][1000:] y_train = data['Labels'][:5000] y_test = data['Labels'][1000:] # Initialize the TF-IDF vectorizer vectorizer = TfidfVectorizer() # Vectorize the sentences in train set X_train_vectors = vectorizer.fit_transform(X_train) # Vectorize the sentences in test set X_test_vectors = vectorizer.transform(X_test) # Initialize the SVM classifier svm = SVC() # Fit the classifier to the training data svm.fit(X_train_vectors, y_train) # Predict labels for the test data y_pred = svm.predict(X_test_vectors) # Print classification report print(classification_report(y_test, y_pred)) from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, f1_score, recall_score # Calculate metrics accuracy = accuracy_score(y_test, y_pred) cm = confusion_matrix(y_test, y_pred) precision = precision_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) recall = recall_score(y_test, y_pred) # Print the results: print("Accuracy:", accuracy) print("Confusion Matrix:") print(cm) print("Precision:", precision) print("F1 Score:", f1) print("Recall:", recall) # Create DataFrame for test predictions result_df = pd.DataFrame({'Question1': X_test, 'Question2': X_test, 'Labels': y_test}) # Save the test predictions in an Excel file result_df['is_duplicate_pred'] = y_pred result_df.to_excel('test_predictions_SVM.xlsx', index=False) need to modify this code to make the test on 1000 pair
6f9432dd7f9a4f36bcd883f73d464244
{ "intermediate": 0.4368651211261749, "beginner": 0.38063791394233704, "expert": 0.18249693512916565 }
32,460
i need a prog to cypher 1 file( over 10mb)
80bb0f657c2552643558653c9523e071
{ "intermediate": 0.32759588956832886, "beginner": 0.2604403793811798, "expert": 0.4119637608528137 }
32,461
how to get latex simbols with python
885839ce547733c329acd5710c898a36
{ "intermediate": 0.3376246690750122, "beginner": 0.19961892068386078, "expert": 0.46275633573532104 }
32,462
Write me a code that hides the credit card number. The user should be able to input 16 numbers. The program should then return the formatted number back to the user with hyphens and all the digits should be masked by an asterisk (*) except for the last four. For example, when the user inputs 1234567890123456, the program should return, ****-****-****-3456
9bb81455f6452654941f5a36bef8923f
{ "intermediate": 0.4236266314983368, "beginner": 0.1498977392911911, "expert": 0.4264756143093109 }
32,463
Hi
063c2bfed0551d76163f3af87c95c994
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
32,464
Как я понимаю алгоритм лангелара, попровь если что-то не так: 1. у нас есть контейнер-фото и цвз-текст 2. цвз мы переводим в биты, набор 0 и 1 3. контейнер мы делим на блоки 8 на 8 со значениями их интенсивность цвета RGB 4. далее мы создаем маску по которой будем встраивать цвз в блоки , в маске 0 - мы ничего не меняем, 1 - встраиваем бит цвз 5.Наложить (умножить) маску на блок с RGB- компонентами – таким образом будут выделены пиксели, принадлежащие к группе B1. 6. выравниваем полученную матрицу на первом уровне Flatten[,1]. 7. Путем вычисления точечного (скалярного) произведения Dot[,] выровненной матрицы на вектор коэффициентовl = 0.299R + 0.587G + 0.114B , получить вектор яркостной составляющей для группы B1 8. Определить среднюю яркость l1. 9. Сформировать инверсную маску - BitXor[,1] , с помощью которой будем выделять группу B0. Повторить пункты 5-8 с инверсной маской и получить значение средней яркости l0. 10. Для величины порога встраивания α = 2, найти величину deltal1 при которой будут выполняться условия встраивания как для “0”, так и для “1”: l0-l1 > +α if s=1 l0-l1 < -α if s=0 (объясни подробно этот пункт, мы для каждого блока делаем данный пункт при встраивании бита цвз?) 11. С помощью вектора коэффициентов найти дельта-вектор {deltaR,deltaG,deltaB}. 12. Сформировать дельта-массив, содержащий 8х8 дельта-векторов ConstantArray{deltaR,deltaG,deltaB}.,{8,8}] и наложить на него маску группы B1. 13. Провести встраивание бита в выбранный блок путем сложения исходного блока и дельта-массива, полученного в пункте 12 14. стего-путь это путь по которому будет происходить встраивание, то есть наш стего путь -Последовательно, непрерывно, по столбцам , значит мы будет идти по каждому блоку начиная с левого-верхнего далее вниз и так по столбцам заполняя наши блоки битами из цвз что надо делать дальшее дальше
a8446f06657a1c96d0f932d2d6298f82
{ "intermediate": 0.16415554285049438, "beginner": 0.6365734934806824, "expert": 0.19927099347114563 }
32,465
help me on how to turn a top down tilemap in godot to 2d platformer, it should make so the depth becomes on the same level so things that are far away on the top down are on the same platform in 2d so if enemies are further up and you go into 2d they would be right next to you I'm using godot 4
8340ee407d0d3cbfd309e862dcd5558d
{ "intermediate": 0.5036271810531616, "beginner": 0.18434825539588928, "expert": 0.3120245039463043 }
32,466
Hi
c1099aa8c91aa719ca70959d81834406
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
32,467
make new code to use https://stablediffusion.fr/chatgpt4turbo : reevere eenegre it import gradio as gr import os import sys import json import requests MODEL = "gpt-4-1106-preview" API_URL = os.getenv("API_URL") DISABLED = os.getenv("DISABLED") == 'True' OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") print (API_URL) print (OPENAI_API_KEY) NUM_THREADS = int(os.getenv("NUM_THREADS")) print (NUM_THREADS) def exception_handler(exception_type, exception, traceback): print("%s: %s" % (exception_type.__name__, exception)) sys.excepthook = exception_handler sys.tracebacklimit = 0 #https://github.com/gradio-app/gradio/issues/3531#issuecomment-1484029099 def parse_codeblock(text): lines = text.split("\n") for i, line in enumerate(lines): if "
ba44d2e0c47c26a70e5a557934189567
{ "intermediate": 0.49010396003723145, "beginner": 0.3523193895816803, "expert": 0.15757663547992706 }
32,468
public function showBattleSelect(c:ClientObject):void { var alert:Alert; if (this.isGarageSelect) { GarageModel(Main.osgi.getService(IGarage)).objectUnloaded(null); GarageModel(Main.osgi.getService(IGarage)).kostil = false; Main.osgi.unregisterService(IGarage); this.isGarageSelect = false; } else { if (this.isTopSelect) { TopModel(Main.osgi.getService(ITopModelBase)).closeTop(null); this.isTopSelect = false; } else { if (this.isInBattle) { this.blur(); alert = new Alert(Alert.ALERT_EXIT_FROM_BATTLE); this.dialogsLayer.addChild(alert); alert.addEventListener(AlertEvent.ALERT_BUTTON_PRESSED, function (ae:AlertEvent):void { if (ae.typeButton == localeService.getText(TextConst.ALERT_ANSWER_YES)) { onExitFromBattle(); networker.send("lobby;get_data_init_battle_select"); isInBattle = false; isBattleSelect = true; (Main.osgi.getService(IGTanksLoader) as GTanksLoaderWindow).addProgress(99); } else { isBattleSelect = false; mainPanel.buttonBar.battlesButton.enable = true; unlock(); }; unblur(); }); return; }; }; }; (Main.osgi.getService(IGTanksLoader) as GTanksLoaderWindow).addProgress(99); this.networker.send("lobby;get_data_init_battle_select"); this.isBattleSelect = true; } как localeService.getText(TextConst.ALERT_ANSWER_YES) это изменить на просто чтобы свой текст ввести
2e86c4b858161954fd9eb7f89b19fc45
{ "intermediate": 0.3465747535228729, "beginner": 0.43534913659095764, "expert": 0.21807610988616943 }
32,469
hi I want a matlab code
2a883f996f51d2131fa34a65808c09df
{ "intermediate": 0.273894727230072, "beginner": 0.4027784466743469, "expert": 0.3233267664909363 }
32,470
проверь правильность кода, исправь если что-то не так For[i = 1, i <= Length[blocks], i++, maskedBlock = ImageApply[BitwiseAnd, {blocks[[i]], mask}]; flattenedBlock = Flatten[maskedBlock, 1]; l = Flatten[flattenedBlock].{0.299, 0.587, 0.114}; l1 = Mean[l]; inverseMask = BitXor[mask, 1]; invertedMaskedBlock = ImageApply[BitwiseAnd, {blocks[[i]], inverseMask}]; invertedFlattenedBlock = Flatten[invertedMaskedBlock, 1]; l0 = Flatten[invertedFlattenedBlock].{0.299, 0.587, 0.114}; deltaL1 = Abs[l0 - l1]; deltaArray = ConstantArray[deltaL1, {8, 8}]; embeddedBlock = Mod[blocks[[i]] + deltaArray, 256]; stegoPath = Flatten[Table[{i, j}, {j, 1, 8}, {i, 1, 8}], 1]; cvzBitIndex = 1; For[pixelIndex = 1, pixelIndex <= Length[stegoPath], pixelIndex++, {x, y} = stegoPath[[pixelIndex]]; If[cvzBitIndex <= Length[cvzBits], urrentPixel = embeddedBlock[[x, y]]; newPixel = BitAnd[currentPixel, BitNot[2^position]]; newPixel = BitOr[newPixel, BitShiftLeft[cvzBits[[cvzBitIndex]], position]]; cvzBitIndex++; embeddedBlock[[x, y]] = newPixel; ] ]
ad106456d6ef8dd5118a3d251ceb3003
{ "intermediate": 0.2943441867828369, "beginner": 0.3403354585170746, "expert": 0.3653202950954437 }
32,471
write a VBA code for a power point presentation about generality in soil and pedogenesis. i need 20 slides. fill the content on your own
0d12ae4ad1e3e7c5e1e13b3871bbd457
{ "intermediate": 0.3070882558822632, "beginner": 0.45156869292259216, "expert": 0.24134306609630585 }
32,472
####导入数据 library(qgraph) library(networktools) library(ggplot2) library(bootnet) library(haven) mydata1 <- read_sav("D:/1Rstudy/sav数据/抑郁与认知 - 练习.sav") mydata<-mydata1[,c("CESD1", "CESD2", "CESD3","CESD4","CESD5","CESD6","CESD7","CESD8","CESD9","CESD10","OrientationTotal","RegistrationTotal","AttentionAndCalculationTotal","RecallTotal","LanguageTotal","NamingFoods")] ####給變量編寫名字 myname3<-c("Feeling bothered","Difficulty with concentrating", "Feeling blue/depressed","Everything was an effort","Hopelessness","Feeling nervous/fearful", "Lack of happiness","Loneliness","Inability to get going","Sleep disturbances","Orientation","Registration", "Attention and Calculation", "Recall","Language","Naming") myname666<-c("CESD1", "CESD2", "CESD3","CESD4","CESD5","CESD6","CESD7","CESD8","CESD9","CESD10","Ori","Reg", "At_C", "Rec","Lan","Nam") goldbricker(mydata, p = 0.05, method = "hittner2003", threshold = 0.25, corMin = 0.5, progressbar = TRUE) mydata.frame<-myname666 colnames(mydata)<-myname666 mydata_matrix1<-as.matrix(mydata) p1 <- ncol(mydata_matrix1) #根据每列量表属性进行分组,比如1-7列属于ISI(这个名字随意) feature_group<-list(CESD_10symptoms=c(1:10),CognitiveSymptoms=c(11:16)) # Compute node predictability 体现在网络图中每个节点外的小圆圈 library(mgm) p <- ncol(mydata) mydata<-as.matrix(mydata_matrix1) fit_obj <- mgm(data = mydata, type = rep('g', p1), level = rep(1, p), lambdaSel = 'CV', ruleReg = 'OR', pbar = FALSE) pred_obj <- predict(fit_obj, mydata) # Compute graph with tuning = 0.5 (EBIC) CorMat <- cor_auto(mydata) EBICgraph <- qgraph(CorMat, nodeNames = myname3, label.cex = 0.7, negDashed = T, graph = "glasso", sampleSize = nrow(mydata),groups=feature_group, nodeNames=myname3, tuning = 0.6, layout = "spring", details = TRUE, color=c("cyan3","red")) network <- estimateNetwork(mydata, default = "EBICglasso", tuning = 0.5, corMethod = "npn") plott <- plot(mynetwork,layout = "spring",color=c("cyan3","red"),label.cex = 0.7, negDashed = T,nodeNames=myname3,groups=feature_group,legend.mode = 'style2',pie = pred_obj$error[,2]) centralityPlot(plott)代碼得到的網絡圖只想保留兩組閒的連綫,該如何寫
f9990d5e5b76a6b3b4a608b6333131a6
{ "intermediate": 0.3603731691837311, "beginner": 0.3476797938346863, "expert": 0.2919470965862274 }
32,473
исправь ошибку в 12 строчке: #include <iostream> #include <vector> #include <ctime> #include <limits> using namespace std; template<class T> void radix_sort(vector<T>& data) { static_assert(numeric_limits<T>::is_integer && !numeric_limits<T>::is_signed, “radix_sort only supports unsigned integer types”); constexpr int word_bits = numeric_limits<T>::digits; // max_bits = floor(log n / 3) // num_groups = ceil(word_bits / max_bits) int max_bits = 1; while ((size_t(1) << (3 * (max_bits + 1))) <= data.size()) { ++max_bits; } const int num_groups = (word_bits + max_bits - 1) / max_bits; // Temporary arrays. vector<size_t> count; vector<T> new_data(data.size()); // Iterate over bit groups, starting from the least significant. for (int group = 0; group < num_groups; ++group) { // The current bit range. const int start = group * word_bits / num_groups; const int end = (group + 1) * word_bits / num_groups; const T mask = (size_t(1) << (end - start)) - T(1); // Count the values in the current bit range. count.assign(size_t(1) << (end - start), 0); for (const T& x : data) ++count[(x >> start) & mask]; // Compute prefix sums in count. size_t sum = 0; for (size_t& c : count) { size_t new_sum = sum + c; c = sum; sum = new_sum; } // Shuffle data elements. for (const T& x : data) { size_t& pos = count[(x >> start) & mask]; new_data[pos++] = x; } // Move the data to the original array. data.swap(new_data); } } template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>*& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T>* root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i--) { cout << " " << a[i]; } } int main() { setlocale(LC_ALL, "Russian"); int n; cout << "Введите размер массива" << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << "Бинарное дерево - 1" << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort(C); if (flag == 2) radix_sort(C); clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << "sec" << endl; return 0; }
4ee09cb16b3514181bafb22cc0022b3b
{ "intermediate": 0.35857704281806946, "beginner": 0.39247629046440125, "expert": 0.2489466816186905 }
32,474
hi. i want you to edit a code in matlab. this code should model a one dimensional diffusion and one dimensional advection. there is a continues source of pollution in a channel with steady flow with velocity of u only in one direction. the diffusion coefficient is D . the retardation coefficient is R. the width of channel is W. the weight of pollution is M gram per seconds. i want the user to be able to input the parameters. also x is the distance from the source point in direction of the flow. y is the distance from the central line of the channel. the diffusion happens in direction of the width and the advection happens in direction of length. i want the model to run under the boundary condition of no flux sides of channel and then the boundary of the sides of channel being perfectly absorbable. the result should be an animation in a 2d plot. this is the code: clc; clear; pollutionModel(); function pollutionModel(W, R, D, u) if nargin < 1 W = 10; R = 1; D = 0.5; u = 0.5; disp('Using default values: W = 10, R = 1, D = 0.5, u = 0.5'); end dy = W / 100; dt = dy^2 / (4*D); t_end = 0.1; y = 0:dy:W; t = 0:dt:t_end; N = length(y); M = length(t); C = zeros(N, M); C(:, 1) = 1/W; for j = 2:M for i = 2:(N-1) diffusion = D * (C(i-1, j-1) - 2*C(i, j-1) + C(i+1, j-1)) / dy^2; advection = -u * (C(i+1, j-1) - C(i-1, j-1)) / (2*dy); retardation = R * C(i, j-1); C(i, j) = C(i, j-1) + dt * (diffusion + advection) / retardation; end C(1, j) = C(2, j); C(N, j) = C(N-1, j); end [X, T] = meshgrid(y, t); figure; surf(X, T, C', 'EdgeColor', 'none'); xlabel('Distance (y)'); ylabel('Time (t)'); zlabel('Concentration'); title('Pollution Model'); colorbar; end
7806e9c54a68d69648ad67d007f901ba
{ "intermediate": 0.4046650826931, "beginner": 0.32153066992759705, "expert": 0.27380433678627014 }
32,475
I have a project idea: In my college, we have to submit worksheets in online mode. So, I am thinking of creating a worksheet creator website. I will give the input worksheet and return me with same worksheet but with different name in the worksheet and uid etc. How can I make one. Here is worksheet format: Experiment No.: 8 Date/Group: 29/01/23 Section/GroupCode: 201-B Subject Details: Name: [The name of student that will be passed] UID: 21B1CS11594 Subject: CSE Branch: 5th Semester - Social Networks Subject Code: [code here] Aim: Demonstrate homophily in the subject by measuring the tendency of nodes to form connections with similar nodes. Objective: The objective of this experiment is to demonstrate homophily in a network by measuring the tendency of nodes to form connections with similar or dissimilar nodes based on attributes or characteristics using python. Technical Requirements: Software Requirement: Google Chrome, Online tools, Python IDE, similar libraries (NetworkX). Hardware Requirement: Computer/Laptop minimum 4GB RAM, Windows OS, Power Supply. Code Sample: #import networkx as nx #import matplotlib.pyplot as plt G = nx.Graph() Student_Name = “Homophily Example”
e6bf8156ada48c07beda5bf4670c12d3
{ "intermediate": 0.4766068756580353, "beginner": 0.25971946120262146, "expert": 0.26367372274398804 }
32,476
Ошибка "vector subscript out of range" возникает, когда вы пытаетесь получить доступ к элементу вектора с помощью индекса, который выходит за пределы размера вектора. В данном коде ошибка может возникать в следующих строках: В функции downHeap: В строке if (child < n && a[child] < a[child + 1]), если child равно n - 1, то a[child + 1] превышает границы вектора a. Необходимо добавить условие child + 1 < n перед выполнением этой проверки. В функции radixSort: В строке for (int i = 0; i < a.size(); i++), если размер вектора a увеличивается в процессе сортировки, то индекс i может превышать новый размер вектора sorted. Необходимо заменить условие на i < sorted.size(). В функции radixSort: В строке sorted[count[index] - 1] = a[i], если index превышает границы вектора count, то возникает ошибка. Необходимо добавить условие index < count.size() перед выполнением этой операции. В функции radixSort: В строке for (int i = 1; i < 10; i++), если count[i - 1] равно a.size(), то count[i] превышает границы вектора count. Необходимо добавить условие i < count.size() перед выполнением этой операции. В функции radixSort: В строке a[i] = sorted[i], если i превышает границы вектора sorted, то возникает ошибка. Необходимо добавить условие i < sorted.size() перед выполнением этой операции.:#include <iostream> #include <vector> #include <ctime> using namespace std; template< class T > void downHeap(vector<T>& a, long k, long n) { T new_elem; long child; new_elem = a[k]; while (k <= n / 2) { child = 2 * k; if (child < n && a[child] < a[child + 1]) child++; if (new_elem >= a[child]) break; a[k] = a[child]; k = child; } a[k] = new_elem; } template<class T> struct TreeNode { T data; TreeNode* left; TreeNode* right; TreeNode(T value) { data = value; left = nullptr; right = nullptr; } }; template<class T> void insert(TreeNode<T>*& root, T value) { if (root == nullptr) { root = new TreeNode<T>(value); return; } if (value < root->data) { insert(root->left, value); } else { insert(root->right, value); } } template<class T> void inOrderTraversal(TreeNode<T>* root, vector<T>& sortedArray) { if (root == nullptr) { return; } inOrderTraversal(root->left, sortedArray); sortedArray.push_back(root->data); inOrderTraversal(root->right, sortedArray); } template<class T> void binaryTreeSort(vector<T>& a) { TreeNode<T>* root = nullptr; for (const T& value : a) { insert(root, value); } a.clear(); inOrderTraversal(root, a); for (int i = a.size() - 1; i >= 0; i--) { cout << " " << a[i]; } } template<class T> void radixSort(vector<T>& a) { int maxVal = *max_element(a.begin(), a.end()); int exp = 1; vector<T> sorted(a.size()); while (maxVal / exp > 0) { vector<int> count(10, 0); for (int i = 0; i < a.size(); i++) { count[(a[i] / exp) % 10]++; } for (int i = 1; i < 10; i++) { count[i] += count[i - 1]; } for (int i = a.size() - 1; i >= 0; i--) { int index = (a[i] / exp) % 10; // Добавленная строка sorted[count[index] - 1] = a[i]; count[index]--; } for (int i = 0; i < a.size(); i++) { a[i] = sorted[i]; } exp *= 10; } } int main() { setlocale(LC_ALL, "Russian"); int n; cout << "Введите размер массива" << endl; cin >> n; vector<int> A(n); vector<int> B(n); vector<int> C; for (int i = 0; i < n; i++) { A[i] = -10000 + rand() % 20001; B[i] = -10000 + rand() % 20001; } for (int i = 0; i < n; i++) { cout << " " << A[i]; } cout << endl; for (int i = 0; i < n; i++) { cout << " " << B[i]; } for (int i = 0; i < n; i++) { if (A[i] % 2 == 0) { C.push_back(A[i]); } if (B[i] % 2 != 0) { C.push_back(B[i]); } } cout << endl; for (int i = 0; i < C.size(); i++) { cout << " " << C[i]; } cout << endl << "Бинарное дерево - 1" << endl; int flag; cin >> flag; clock_t start_time = clock(); if (flag == 1) binaryTreeSort(C); if (flag == 2) radixSort(C); clock_t end_time = clock(); double duration = (static_cast<double>(end_time - start_time)) / CLOCKS_PER_SEC; cout << " Time: " << duration << "sec" << endl; return 0; }
fbb9586ae362aa5c2daa7b29f62798d1
{ "intermediate": 0.23921120166778564, "beginner": 0.5244395732879639, "expert": 0.23634913563728333 }
32,477
convert this python code to c++: import pyautogui as pag import keyboard def ZOV_NOL(): pag.keyDown('shift') pag.click(1060, 250) pag.click(1138, 250) pag.click(1138, 250) pag.keyUp('shift') pag.click(900, 205) pag.press('backspace') pag.click(647, 217) pag.click(647, 217) keyboard.add_hotkey('X', ZOV_NOL) keyboard.wait('Ctrl + Q')
12f82b4e44c7c0599a400c0fb4ad1270
{ "intermediate": 0.4383632242679596, "beginner": 0.28933021426200867, "expert": 0.27230650186538696 }
32,478
Implement a program in C# that performs a depth-first search on a tree of integers.
664fa6d8daac37de1c5fca330ac94fb1
{ "intermediate": 0.28303807973861694, "beginner": 0.09637410938739777, "expert": 0.6205878257751465 }
32,479
How do I have my discord bot send unicode characters with markdown?
a55b8b27677ff109510b9f04db36c0ed
{ "intermediate": 0.4847355782985687, "beginner": 0.13747861981391907, "expert": 0.3777858018875122 }
32,480
How do I send a unicode character (U+266A) to be interpreted as the character to discord bot?
578790feccf26189e91801f5cf6559d9
{ "intermediate": 0.4155856668949127, "beginner": 0.09924858063459396, "expert": 0.4851657450199127 }
32,481
Bayesian Beta-Binomial models are a good way of modelling the probability of success based on a fixed number of trials. For instance, imagine we flip a coin n=10 times and observed the number of times, k, the coin lands on heads. We can then find our posterior distribution of θ by combining appropriate distributions for the likelihood and prior. In this question we will write some simple code to calculate the posterior distribution for different values of θ. For this you will need the factorial function. To calculate x! you can use the following code, where x is 3 in this case import math math.factorial(3) (a) Firstly, write a function, 'binomial_pmf', for the binomial distribution we will use as a likelihood. The function takes the following form: (n! / (k!(n-k)!)) θ^k (1-θ)^(n-k) Your function should take 'k', 'n', and 'theta' as inputs and return the value of the function. (b) Secondly, write a function, 'beta_pdf', for the Beta distribution we will use as a prior. The function takes the following form: ((a+b-1)! / ((a-1)!(b-1)!) θ^(a-1) (1-θ)^(b-1) Your function should take 'theta', 'a', and 'b' as inputs and return the value of the function. (c) Finally, write a function for the posterior which can be calculated by multiplying the likelihood by the prior. Your function should take 'k', 'theta', 'a', and 'b' as inputs and return the posterior value. You must use your functions from parts (a) and (b) here.
e703ddda376be270f489abbda509b1cc
{ "intermediate": 0.38789817690849304, "beginner": 0.2807924747467041, "expert": 0.3313092887401581 }
32,482
Can you solve my task
afd173f4de84ee096327d3a972177cd1
{ "intermediate": 0.36653733253479004, "beginner": 0.3015410602092743, "expert": 0.33192160725593567 }
32,483
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyHealth : MonoBehaviour { public int maxHealth = 1; private int currentHealth; private void Start() { currentHealth = maxHealth; } public void TakeDamage(int damageAmount) { currentHealth -= damageAmount; if (currentHealth <= 0) { Die(); } } private void Die() { // Destroy the enemy object when health reaches 0 Destroy(gameObject); } } make it so if the enemy dies the score goes up +50 points. Here is the ScoreCounter script for reference: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //This line enables use of uGUI classes like Text. public class ScoreCounter : MonoBehaviour { [Header("Dynamic")] public int score = 0; private Text uiText; // Start is called before the first frame update void Start() { uiText = GetComponent<Text>(); } // Update is called once per frame void Update() { uiText.text = score.ToString("Score:#,0"); //This 0 is a zero! } }
30cc93c7ee90fb0aec40d13a49464dda
{ "intermediate": 0.34843382239341736, "beginner": 0.38054367899894714, "expert": 0.2710224390029907 }
32,484
#include <iostream> #include <string> using namespace std; int main(int argc, char **argv) { int value_first = 100, value_second = 100; string str_first, str_second; int len, count; int i = 0, j = 0; cout << "Числа-палиндромы:" << endl; while (i != 50) // Палиндром { count = 0; ++value_first; str_first = to_string(value_first); len = str_first.length(); for (int k = 0; i < len; ++k) { for(int l = len - 1; l > -1; --l) { if (str_first[k] == str_first[l]) { ++count; } } } if (count == len) { ++i; cout << i << ": " << value_first << endl; } } return 0; } Результат в консоли: Числа-палиндромы: Segmentation fault (core dumped) В чем проблема?
ac7aacd772a51040f21396aadb18b9fb
{ "intermediate": 0.3524978458881378, "beginner": 0.341304749250412, "expert": 0.3061973452568054 }
32,485
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class BossHealth : MonoBehaviour { public int maxHealth = 5; private int currentHealth; private ScoreCounter scoreCounter; // Reference to the ScoreCounter script private void Start() { currentHealth = maxHealth; scoreCounter = FindObjectOfType<ScoreCounter>(); // Find the ScoreCounter script in the scene } public void TakeDamage(int damageAmount) { currentHealth -= damageAmount; if (currentHealth <= 0) { Die(); } } private void Die() { // Add 300 points to the score when the boss dies scoreCounter.score += 300; // Destroy the boss object when health reaches 0 Destroy(gameObject); // Check if the current scene is "Level1" and change to "Level2" if true if (SceneManager.GetActiveScene().name.Equals("Level1")) { SceneManager.LoadScene("Level2"); } } } make it so when the scene changes the score does not change
47f14d886524a5a8868a8eb43e7225c7
{ "intermediate": 0.4431140720844269, "beginner": 0.3493402600288391, "expert": 0.2075456976890564 }
32,486
Please list all 007 Bond films and year made, for the years 1955-1990
cd8da0f0242ab68dfe01ea43ba526fdb
{ "intermediate": 0.34736737608909607, "beginner": 0.2792850434780121, "expert": 0.37334761023521423 }
32,487
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //This line enables use of uGUI classes like Text. public class ScoreCounter : MonoBehaviour { private Text uiText; private ScoreManager scoreManager; // Reference to the ScoreManager script // Start is called before the first frame update void Start() { uiText = GetComponent<Text>(); scoreManager = ScoreManager.Instance; // Get the ScoreManager instance } // Update is called once per frame void Update() { uiText.text = scoreManager.GetScore().ToString("Score:#,0"); } } write a ScoreManager script that makes it so the score does not change when changing scenes
dcce948a9ceb73e6b2871c70ebd691ed
{ "intermediate": 0.38281646370887756, "beginner": 0.4188831150531769, "expert": 0.19830042123794556 }
32,488
please write a VBA code for a powerpoint presentation about design pattern:builder, i need12 slides, fill the content on your own.
ac35a2692598c8d1f1d8cc6aa61e6ac6
{ "intermediate": 0.33049169182777405, "beginner": 0.443461537361145, "expert": 0.22604681551456451 }
32,489
Сделай так, чтобы функция radixSort могла работать с отрицательными цифрами и после сортировки выводила их
8d1ebf2ab6e32271dfad884758cd3751
{ "intermediate": 0.3075513541698456, "beginner": 0.1880580186843872, "expert": 0.5043906569480896 }
32,490
How would i make a user rewrite the fields in a forms application if they get a messagebox shown and then run it again after they click submit
ba4398e342569c36f5c5d6609e4a1009
{ "intermediate": 0.48997962474823, "beginner": 0.23362937569618225, "expert": 0.27639099955558777 }
32,491
write a PowerBASIC program to save a 3 dimensional array to a file
f169d4ef6f6049d77ef6d41b491951cf
{ "intermediate": 0.36817502975463867, "beginner": 0.227809876203537, "expert": 0.40401509404182434 }
32,492
write a PowerBASIC function to save a 3 dimensional array to a file
3aa49d9a6252a11c4f5387fa5514be6d
{ "intermediate": 0.3964550197124481, "beginner": 0.32467326521873474, "expert": 0.2788717746734619 }
32,493
Tell me about yourself
eef8bb07dfdd1262dbbf86c356dd0e88
{ "intermediate": 0.41631922125816345, "beginner": 0.30509600043296814, "expert": 0.2785848081111908 }
32,494
create a basic game template using python pyglet
a28a275ae9d671137c81311f99764002
{ "intermediate": 0.35295355319976807, "beginner": 0.34334996342658997, "expert": 0.30369648337364197 }
32,495
cypress test ssr angular
abdc092a5e4d858b7a9b1732b81eac4d
{ "intermediate": 0.4997929632663727, "beginner": 0.3241459131240845, "expert": 0.17606110870838165 }
32,496
cypress intercept api request
f64742b4788a07bfaf446e264bebdb09
{ "intermediate": 0.5260962843894958, "beginner": 0.21461722254753113, "expert": 0.25928646326065063 }
32,497
Hi! I want a program in python with an usser and password using functions, for, while and download the information in a dictionary
cf71277ca80a16541ab2fa2d70e37a21
{ "intermediate": 0.36232343316078186, "beginner": 0.47877204418182373, "expert": 0.1589045524597168 }
32,498
Hi can you help me with CSS problem?
c65ad8eedf8b3558e33c27288f569c37
{ "intermediate": 0.2824953496456146, "beginner": 0.4568464457988739, "expert": 0.26065823435783386 }
32,499
help me to create a 100 unique and highquality sddingment for my university the question is:What is meaning of word " Cyber"? Write your ideas about cyber security and how we can secure e-commerce/m-commerce trading platform?
62e6fb0af3d86da09c5131a6cd3810a1
{ "intermediate": 0.3207249939441681, "beginner": 0.33303511142730713, "expert": 0.3462398946285248 }
32,500
<? namespace Bit\FileDownloads; use \Bitrix\Main\Context; class EventManager { static function onProlog() { if(Context::getCurrent()->getRequest()->isAdminSection() === false) { \CJSCore::registerExt( "bit.filedownloads", [ "js" => "/local/js/bit.filedownloads/script.js", "css" => "/local/js/bit.filedownloads/style.css", "rel" => ["ui", "ui.entity-selector", "ajax", "popup", "jquery"] ] ); \CJSCore::init("bit.filedownloads"); } } public static function cleanZipDir() { $dirPath = $_SERVER["DOCUMENT_ROOT"] . '/upload/zip/'; if(is_dir($dirPath)) { if($dir = opendir($dirPath)) { while ($file = readDir($dir)) { if(in_array($file, ['.', '..'])) continue; unlink($_SERVER["DOCUMENT_ROOT"] . '/upload/zip/'.$file); } } } return '\Bit\FileDownloads\EventManager::cleanZipDir();'; } } ?> обьясни код
3285297b1e65052e4fe5f1b1628cff6a
{ "intermediate": 0.5599153637886047, "beginner": 0.2689403295516968, "expert": 0.1711442619562149 }
32,501
class Turntable { constructor(canvasId) { this.canvas = document.getElementById(canvasId); this.ctx = this.canvas.getContext('2d'); this.refreshButton = document.getElementById('update'); this.rotateButton = document.getElementById('rotate'); this.isSpinning = false; this.spinSpeed = 0.2; this.decelerationRate = 0.01; this.numberOfSectors = 0; // 存储扇形数量 this.sectorPrizes = ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6', '奖品7', '奖品8', '奖品9', '奖品10']; // 设置奖项 this.refreshButton.addEventListener('click', () => { this.refreshTurntable(); }); this.rotateButton.addEventListener('click', () => { this.startSpinAnimation(); }); } refreshTurntable() { this.numberOfSectors = this.generateRandomNumberOfSectors(); // 更新扇形数量 this.clearTurntable(); this.drawSectors(this.numberOfSectors); } generateRandomNumberOfSectors() { return Math.floor(Math.random() * 8) + 3; // 生成3-10之间的随机整数 } clearTurntable() { this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); } drawSectors() { const sectorAngle = this.calculateSectorAngle(this.numberOfSectors); const centerX = this.canvas.width / 2; const centerY = this.canvas.height / 2; const radius = Math.min(this.canvas.width, this.canvas.height) / 2 - 20; for (let i = 0; i < this.numberOfSectors; i++) { const startAngle = i * sectorAngle; const endAngle = (i + 1) * sectorAngle; this.ctx.beginPath(); this.ctx.moveTo(centerX, centerY); this.ctx.arc(centerX, centerY, radius, startAngle, endAngle); this.ctx.closePath(); const hue = (i * 360) / this.numberOfSectors; const randomColor = this.getRandomColor(); this.ctx.fillStyle = randomColor; this.ctx.fill(); const text = this.sectorPrizes[Math.floor(Math.random() * 10) + 1]; // 根据索引获取奖项,循环使用奖项数组 const textAngle = startAngle + sectorAngle / 2; // 计算文字所在的角度 const textX = centerX + Math.cos(textAngle) * radius * 0.6; // 计算文字的 x 坐标 const textY = centerY + Math.sin(textAngle) * radius * 0.6; // 计算文字的 y 坐标 this.ctx.save(); // 保存当前的绘图状态 this.ctx.translate(textX, textY); // 平移到文字的位置 this.ctx.rotate(textAngle + Math.PI / 2); // 旋转文字方向为正 this.ctx.textAlign = 'center'; this.ctx.textBaseline = 'middle'; this.ctx.font = '16px Arial'; this.ctx.fillStyle = '#000000'; this.ctx.fillText(text, 0, 0); // 在平移后的位置绘制文字 this.ctx.restore(); // 恢复之前保存的绘图状态 } } getRandomColor() { const letters = '0123456789ABCDEF'; let color = '#'; for (let i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } spinAnimation() { const numberOfSectors = this.numberOfSectors; // 使用之前保存的扇形数量 const sectorAngle = this.calculateSectorAngle(numberOfSectors); const centerX = this.canvas.width / 2; const centerY = this.canvas.height / 2; const radius = Math.min(this.canvas.width, this.canvas.height) / 2 - 20; this.clearTurntable(); // 清除画布 this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2); this.ctx.rotate(this.spinSpeed); this.ctx.translate(-this.canvas.width / 2, -this.canvas.height / 2); for (let i = 0; i < numberOfSectors; i++) { const startAngle = i * sectorAngle; const endAngle = (i + 1) * sectorAngle; this.ctx.beginPath(); this.ctx.moveTo(centerX, centerY); this.ctx.arc(centerX, centerY, radius, startAngle, endAngle); this.ctx.closePath(); const hue = (i * 360) / numberOfSectors; const randomColor = this.getRandomColor(); this.ctx.fillStyle = randomColor; this.ctx.fill(); const text = this.sectorPrizes[i % this.sectorPrizes.length]; // 根据索引获取奖项,循环使用奖项数组 const textAngle = startAngle + sectorAngle / 2; // 计算文字所在的角度 const textX = centerX + Math.cos(textAngle) * radius * 0.6; // 计算文字的 x 坐标 const textY = centerY + Math.sin(textAngle) * radius * 0.6; // 计算文字的 y 坐标 this.ctx.save(); // 保存当前的绘图状态 this.ctx.translate(textX, textY); // 平移到文字的位置 this.ctx.rotate(textAngle + Math.PI / 2); // 旋转文字方向为正 this.ctx.textAlign = 'center'; this.ctx.textBaseline = 'middle'; this.ctx.font = '16px Arial'; this.ctx.fillStyle = '#000000'; this.ctx.fillText(text, 0, 0); // 在平移后的位置绘制文字 this.ctx.restore(); // 恢复之前保存的绘图状态 } this.spinSpeed -= this.decelerationRate; if (this.spinSpeed > 0) { requestAnimationFrame(() => this.spinAnimation()); } else { this.isSpinning = false; } } calculateSectorAngle(numberOfSectors) { return (2 * Math.PI) / numberOfSectors; } startSpinAnimation() { if (this.isSpinning) return; this.isSpinning = true; this.spinSpeed = 0.2; this.spinAnimation(); } } const turntable = new Turntable('gameCanvas'); 在本身的canvas添加一个同圆心圆环<div>元素
22ff601042e5666b1084cac39d495ea0
{ "intermediate": 0.2647414803504944, "beginner": 0.5487921833992004, "expert": 0.1864663064479828 }
32,502
Review this code: pub fn bed2gtf(input: &String, isoforms: &String, output: &String) -> Result<(), Box<dyn Error>> { msg(); simple_logger::init_with_level(Level::Info)?; let start = Instant::now(); let isf = reader(isoforms).unwrap_or_else(|_| { let message = format!("Isoforms file {} not found.", isoforms); panic!("{}", message); }); let bed = bed_reader(input); let isoforms = get_isoforms(&isf); let gene_track = custom_par_parse(&bed).unwrap(); let coords = combine_maps_par(&isoforms, &gene_track); let results: Vec<_> = bed .par_iter() .map(|record| to_gtf(&record, &isoforms)) .collect(); let flat_results: Vec<_> = results.into_iter().flatten().collect(); let mut combined = [coords, flat_results].concat(); combined.par_sort_unstable_by(|a, b| { let chr_cmp = compare(&a.0, &b.0); if chr_cmp == std::cmp::Ordering::Equal { a.2.cmp(&b.2) } else { chr_cmp } }); let output = File::create(output).unwrap(); let mut writer = BufWriter::new(output); comments(&mut writer); for (chrom, gene_type, start, end, strand, phase, attr) in combined { let gtf_line = format!( "{}\t{}\t{}\t{}\t{}\t.\t{}\t{}\t{}\n", chrom, SOURCE, gene_type, start, end, strand, phase, attr ); writer.write_all(gtf_line.as_bytes()).unwrap(); } let peak_mem = PEAK_ALLOC.peak_usage_as_mb(); log::info!("Memory usage: {} MB", peak_mem); log::info!("Elapsed: {:.4?} secs", start.elapsed().as_secs_f32()); Ok(()) } fn to_gtf( bedline: &BedRecord, isoforms: &HashMap<String, String>, ) -> Vec<(String, String, u32, u32, String, String, String)> { let mut result: Vec<(String, String, u32, u32, String, String, String)> = Vec::new(); let gene = isoforms.get(&bedline.name).unwrap_or_else(|| { let message = format!( "Isoform {} not found. Check your isoforms file", bedline.name ); panic!("{}", message); }); let fcodon = first_codon(bedline) .unwrap_or_else(|| panic!("No start codon found for {}.", bedline.name)); let lcodon = last_codon(bedline).unwrap_or_else(|| { panic!("No stop codon found for {}.", bedline.name); }); let first_utr_end = bedline.cds_start; let last_utr_start = bedline.cds_end; let frames = bedline.get_frames(); let cds_end: u32 = if bedline.strand == "+" && codon_complete(&lcodon) { move_pos(bedline, lcodon.end, -3) } else { bedline.cds_end }; let cds_start = if bedline.strand == "-" && codon_complete(&fcodon) { move_pos(bedline, fcodon.start, 3) } else { bedline.cds_start }; build_gtf_line( bedline, gene, "transcript", bedline.tx_start, bedline.tx_end, 3, -1, &mut result, ); for i in 0..bedline.exon_count as usize { build_gtf_line( bedline, gene, "exon", bedline.exon_start[i], bedline.exon_end[i], 3, i as i16, &mut result, ); if cds_start < cds_end { write_features( i, bedline, gene, first_utr_end, cds_start, cds_end, last_utr_start, frames[i] as u32, &mut result, ); } } if bedline.strand != "-" { if codon_complete(&fcodon) { write_codon(bedline, gene, "start_codon", fcodon, &mut result); } if codon_complete(&lcodon) { write_codon(bedline, gene, "stop_codon", lcodon, &mut result); } } else { if codon_complete(&lcodon) { write_codon(bedline, gene, "start_codon", lcodon, &mut result); } if codon_complete(&fcodon) { write_codon(bedline, gene, "stop_codon", fcodon, &mut result); } } result } If there is any improvement to make it more efficient or faster please implement it and give a description of all you have done
1e21caa82f6ad4161a8b054a9a4565a6
{ "intermediate": 0.37107041478157043, "beginner": 0.46634605526924133, "expert": 0.16258352994918823 }
32,503
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Random Spin Game</title> <style> body { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; } .ring { width: 460px; height: 460px; display: block; border-radius: 50%; background-color:deepskyblue; position: relative; } </style> </head> <body> <div class="ring"> <canvas id="gameCanvas" width="400" height="400"></canvas> </div> <button onclick="startSpin()">开始旋转</button> <script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const radius = 200; // 转盘半径 const centerX = canvas.width / 2; // 转盘中心点的 x 坐标 const centerY = canvas.height / 2; // 转盘中心点的 y 坐标 const sectorColors = ['#FF5733', '#FFC300', '#4CAF50', '#3498db', '#9B59B6', '#E74C3C', '#F39C12', '#2C3E50']; // 扇形的颜色 const sectorPrizes = ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6', '奖品7', '奖品8']; // 奖项 function drawWheel() { const numberOfSectors = sectorPrizes.length; const sectorAngle = (2 * Math.PI) / numberOfSectors; for (let i = 0; i < numberOfSectors; i++) { const startAngle = i * sectorAngle; const endAngle = (i + 1) * sectorAngle; ctx.beginPath(); ctx.moveTo(centerX, centerY); ctx.arc(centerX, centerY, radius, startAngle, endAngle); ctx.closePath(); ctx.fillStyle = sectorColors[i % sectorColors.length]; ctx.fill(); const text = sectorPrizes[i]; const textAngle = startAngle + sectorAngle / 2; const textX = centerX + Math.cos(textAngle) * radius * 0.5; const textY = centerY + Math.sin(textAngle) * radius * 0.5; ctx.save(); ctx.translate(textX, textY); ctx.rotate(textAngle + Math.PI / 2); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.font = '16px Arial'; ctx.fillStyle = '#fff'; ctx.fillText(text, 0, 0); ctx.restore(); } } function startSpin() { const numberOfSpins = 2; // 旋转圈数 const targetSector = Math.floor(Math.random() * sectorPrizes.length); // 随机选择一个奖项作为目标扇形 const totalAngle = targetSector * (2 * Math.PI / sectorPrizes.length) + (2 * Math.PI) * numberOfSpins; let currentAngle = 0; const spinSpeed = 0.08; // 旋转速度 function spinAnimation() { currentAngle += spinSpeed; if (currentAngle >= totalAngle) { // 到达目标角度,停止旋转 return; } ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.save(); ctx.translate(centerX, centerY); ctx.rotate(currentAngle); ctx.translate(-centerX, -centerY); drawWheel(); ctx.restore(); requestAnimationFrame(spinAnimation); } spinAnimation(); } drawWheel(); // 初始绘制转盘 </script> </body> </html> 如何使得div元素和canvas元素圆心对齐
73431b249bd7b89ad664c3ee1f9ce996
{ "intermediate": 0.273590087890625, "beginner": 0.46949923038482666, "expert": 0.2569107115268707 }
32,504
Write following statement in your own words: It discussed about general capital assets, accounting for donated assets, trade-ins, asset impairments, and investments in marketable securities. These general capital assets are differentiated from other captital assets accounted for under propriety and fiduciary funds. As for purchased assets, they are reported in historical cost plus any other costs to put an asset into use, and for constructed assets are costed with direct labor and materials, overhead cost plus any other costs such as insurance premiums, however, interests incurred are not capitalized but expensed. Donated assets and investments are reported based on their fair market value. Infrastructure assets may not be depreciated if they can demonstrate that those being maintained preserved at specified condition level. GASB # 34 does not require capitalization of artworks if they are held for public exhibition or research, protected and preserved, and proceeds from sale are used to acquire other collectibles. Video also showed how to compute and journalize impairment loss.
4252b5bc2395db327b13546a0b3132a2
{ "intermediate": 0.348888635635376, "beginner": 0.2698012590408325, "expert": 0.3813101649284363 }
32,505
Hi ,i want to solve this qusation in redhot write or use needed commands to accomplish the following: Each time the user logs in, a detailed list of all files – in the /var global directory and its subs - that is being modified for the past 5 days should be produced and saved in a log file in the backups/November directory. The file name should reflect the date and time it’s created at, for example: if it’s been created at: November 15th 2023 3:34 P.M. the file should be named: 20231115-1534.log. Be aware that: - the phrase: detailed list of files means it should contain information like files sizes, modification dates, ownership, permissions, inodes numbers and links. - The files list shouldn’t contain any error messages resulted by executing the search command.
5769fc61f96892db5ea38c53f7180ca8
{ "intermediate": 0.5131943225860596, "beginner": 0.19666370749473572, "expert": 0.2901419997215271 }
32,506
from matplotlib import pyplot as plt import numpy as np import math import cv2 potential_points_num = 200 image_threshold = 100 def hough_line(edge): theta = np.arange(0, 180, 1) cos = np.cos(np.deg2rad(theta)) sin = np.sin(np.deg2rad(theta)) rho_range = round(math.sqrt(edge.shape[0]**2 + edge.shape[1]**2)) accumulator = np.zeros((2 * rho_range, len(theta)), dtype=np.uint8) edge_pixels = np.where(edge == 255) coordinates = list(zip(edge_pixels[0], edge_pixels[1])) for p in range(len(coordinates)): for t in range(len(theta)): rho = int(round(coordinates[p][1] * cos[t] + coordinates[p][0] * sin[t])) accumulator[rho, t] += 2 return accumulator def get_coords_by_threshold( image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > image_threshold) return coords def get_neigh_nums_list( coords: tuple, kernel_size: int = 3 ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's number. """ neigh_nums = [] offset = (kernel_size - 1) // 2 for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > image.shape[0] - offset: continue if y < 0 + offset or y > image.shape[1] - offset: continue kernel = image[x-offset:x+offset+1, y-offset:y+offset+1] step_neigh_num = np.count_nonzero(kernel) - 1 neigh_nums.append([x, y, step_neigh_num]) return neigh_nums def sort_neigh_nums_by_N( neigh_nums: list ) -> np.ndarray: """ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. """ np_neigh_nums = np.array(neigh_nums) np_neigh_nums = np_neigh_nums[ (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] np_neigh_nums = np_neigh_nums[ np.argsort(-np_neigh_nums[:, 2])] return np_neigh_nums def get_potential_points_coords( sorted_niegh_nums: np.ndarray ) -> np.ndarray: """ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. """ sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1) return sorted_neigh_nums[:potential_points_num] image = cv2.imread("0.0/00.pgm", cv2.COLOR_BGR2GRAY) # my code coords_by_threshold = get_coords_by_threshold(image) neigh_nums = get_neigh_nums_list(coords_by_threshold) sorted_neigh_nums = sort_neigh_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) # end my code Нужен алгоритм (Монжо использовать преобразование хафа, например), который будет написан только на numpy, который находит уравнения прямых и рисует их на изображении. Прямых должно быть три, они должны быть разные, мы детектируем треугольник, минимальный угол которого равен 30 градусам
48f39ca3f60e2b0c0eaae7c68a8815d4
{ "intermediate": 0.43884220719337463, "beginner": 0.3191887140274048, "expert": 0.24196913838386536 }
32,507
Write a c++ program. User enters a string. A function prints the word ant another ine counts them
1f45a483ffd96e148643b0e391a83903
{ "intermediate": 0.21366065740585327, "beginner": 0.6183148622512817, "expert": 0.16802455484867096 }
32,508
use streamlit and sqlqlchemy to make web app for an education center and add more specific information for students and make page for data add and anther for search and one for editing or delete data
1bfa6a992a4da35dd654ff1de9d37c62
{ "intermediate": 0.8128916025161743, "beginner": 0.045006800442934036, "expert": 0.14210158586502075 }
32,509
from matplotlib import pyplot as plt import numpy as np import math import cv2 potential_points_num = 200 image_threshold = 100 def hough_line(edge): theta = np.arange(0, 180, 1) cos = np.cos(np.deg2rad(theta)) sin = np.sin(np.deg2rad(theta)) rho_range = round(math.sqrt(edge.shape[0]**2 + edge.shape[1]**2)) accumulator = np.zeros((2 * rho_range, len(theta)), dtype=np.uint8) edge_pixels = np.where(edge == 255) coordinates = list(zip(edge_pixels[0], edge_pixels[1])) for p in range(len(coordinates)): for t in range(len(theta)): rho = int(round(coordinates[p][1] * cos[t] + coordinates[p][0] * sin[t])) accumulator[rho, t] += 2 return accumulator def get_coords_by_threshold( image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > image_threshold) return coords def get_neigh_nums_list( coords: tuple, kernel_size: int = 3 ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's number. """ neigh_nums = [] offset = (kernel_size - 1) // 2 for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > image.shape[0] - offset: continue if y < 0 + offset or y > image.shape[1] - offset: continue kernel = image[x-offset:x+offset+1, y-offset:y+offset+1] step_neigh_num = np.count_nonzero(kernel) - 1 neigh_nums.append([x, y, step_neigh_num]) return neigh_nums def sort_neigh_nums_by_N( neigh_nums: list ) -> np.ndarray: """ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. """ np_neigh_nums = np.array(neigh_nums) np_neigh_nums = np_neigh_nums[ (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] np_neigh_nums = np_neigh_nums[ np.argsort(-np_neigh_nums[:, 2])] return np_neigh_nums def get_potential_points_coords( sorted_niegh_nums: np.ndarray ) -> np.ndarray: """ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. """ sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1) return sorted_neigh_nums[:potential_points_num] image = cv2.imread("0.0/00.pgm", cv2.COLOR_BGR2GRAY) # my code coords_by_threshold = get_coords_by_threshold(image) neigh_nums = get_neigh_nums_list(coords_by_threshold) sorted_neigh_nums = sort_neigh_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) # end my code Доработай алгоритм с помощью только numpy так, чтобы он находил три самые лучшие прямые. 1. Находим самую лучшую прямую, такую, что количество potential_points на ней максимальное 2. Удаляем potential_points, которые лежат на лучшей прямой, чтобы не найти её снова 3. Повторяем так со второй и третьей прямой, каждый раз проверяя, что k и b у наденных прямых отличаются одновременно на 0.5 и 20 соответственно
9593745d97b6b1e9f2bf9943143edea3
{ "intermediate": 0.43884220719337463, "beginner": 0.3191887140274048, "expert": 0.24196913838386536 }
32,510
how to highlight attribute of block reference c++?
19966f8429b8ea65c6c38ae273f8f1d4
{ "intermediate": 0.3910307288169861, "beginner": 0.277824342250824, "expert": 0.33114486932754517 }
32,511
binary tree searcg algith for ds18b20 in C language
d725502c40cc4c255033331fbae96d88
{ "intermediate": 0.17268307507038116, "beginner": 0.19287951290607452, "expert": 0.6344373226165771 }
32,512
Write code that takes two pil images (already opened) and then it concatantes them into one where the first image is on the top half and the second image is on the bottom half then you ask a yes or no question, the filename is gonna be either 1 or 0 depending on the answer.
02009ba09c553dd44c7e6e1f4a6cfe4a
{ "intermediate": 0.3605926036834717, "beginner": 0.19505365192890167, "expert": 0.44435378909111023 }
32,513
from matplotlib import pyplot as plt import numpy as np import math import cv2 potential_points_num = 200 image_threshold = 0 import numpy as np import math def rgb2gray(rgb): return np.dot(rgb[..., :3], [0.299, 0.587, 0.114]).astype(np.uint8) def fast_hough_line(img, angle_step=1, lines_are_white=True, value_threshold=5): """hough line using vectorized numpy operations, may take more memory, but takes much less time""" # Rho and Theta ranges thetas = np.deg2rad(np.arange(-90.0, 90.0, angle_step)) #can be changed #width, height = col.size #if we use pillow width, height = img.shape diag_len = int(np.ceil(np.sqrt(width * width + height * height))) # max_dist rhos = np.linspace(-diag_len, diag_len, diag_len * 2) # Cache some resuable values cos_theta = np.cos(thetas) sin_theta = np.sin(thetas) num_thetas = len(thetas) # Hough accumulator array of theta vs rho accumulator = np.zeros((2 * diag_len, num_thetas)) are_edges = img > value_threshold if lines_are_white else img < value_threshold #are_edges = cv2.Canny(img,50,150,apertureSize = 3) y_idxs, x_idxs = np.nonzero(are_edges) # (row, col) indexes to edges # Vote in the hough accumulator xcosthetas = np.dot(x_idxs.reshape((-1,1)), cos_theta.reshape((1,-1))) ysinthetas = np.dot(y_idxs.reshape((-1,1)), sin_theta.reshape((1,-1))) rhosmat = np.round(xcosthetas + ysinthetas) + diag_len rhosmat = rhosmat.astype(np.int16) for i in range(num_thetas): rhos,counts = np.unique(rhosmat[:,i], return_counts=True) accumulator[rhos,i] = counts return accumulator, thetas, rhos def show_hough_line(img, accumulator, thetas, rhos): import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 2, figsize=(10, 10)) ax[0].imshow(img) ax[0].set_title('Input image') ax[0].axis('image') ax[1].imshow( accumulator, cmap='jet', extent=[np.rad2deg(thetas[-1]), np.rad2deg(thetas[0]), rhos[-1], rhos[0]]) ax[1].set_aspect('equal', adjustable='box') ax[1].set_title('Hough transform') ax[1].set_xlabel('Angles (degrees)') ax[1].set_ylabel('Distance (pixels)') ax[1].axis('image') plt.show() if __name__ == "__main__": image = cv2.imread("0.0/00.pgm", cv2.COLOR_BGR2GRAY) accumulator, thetas, rhos = fast_hough_line(image) show_hough_line(image, accumulator, thetas, rhos) Визуализируй прямые, которые получились в результате преобразования Хафа, выведи на печать их уравнения
cb4f421b5b31f9f73636a5617c61f144
{ "intermediate": 0.31805333495140076, "beginner": 0.3897414207458496, "expert": 0.29220521450042725 }
32,514
from matplotlib import pyplot as plt import numpy as np import math import cv2 potential_points_num = 200 image_threshold = 0 import numpy as np import math def fast_hough_line(img, angle_step=1, lines_are_white=True, value_threshold=5): """ Hough line using vectorized numpy operations. May take more memory, but takes much less time. """ # Rho and Theta ranges thetas = np.deg2rad(np.arange(-90.0, 90.0, angle_step)) #can be changed width, height = img.shape diag_len = int(np.ceil(np.sqrt(width * width + height * height))) rhos = np.linspace(-diag_len, diag_len, diag_len * 2) # Cache some resuable values cos_theta = np.cos(thetas) sin_theta = np.sin(thetas) num_thetas = len(thetas) # Hough accumulator array of theta vs rho accumulator = np.zeros((2 * diag_len, num_thetas)) are_edges = img > value_threshold if lines_are_white else img < value_threshold #are_edges = cv2.Canny(img,50,150,apertureSize = 3) y_idxs, x_idxs = np.nonzero(are_edges) # (row, col) indexes to edges # Vote in the hough accumulator xcosthetas = np.dot(x_idxs.reshape((-1,1)), cos_theta.reshape((1,-1))) ysinthetas = np.dot(y_idxs.reshape((-1,1)), sin_theta.reshape((1,-1))) rhosmat = np.round(xcosthetas + ysinthetas) + diag_len rhosmat = rhosmat.astype(np.int16) for i in range(num_thetas): rhos,counts = np.unique(rhosmat[:,i], return_counts=True) accumulator[rhos,i] = counts return accumulator, thetas, rhos def show_hough_line(img, accumulator, thetas, rhos): import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 2, figsize=(10, 10)) ax[0].imshow(img) ax[0].set_title("Input image") ax[0].axis("image") ax[1].imshow( accumulator, cmap="jet", extent=[np.rad2deg(thetas[-1]), np.rad2deg(thetas[0]), rhos[-1], rhos[0]]) ax[1].set_aspect("equal", adjustable="box") ax[1].set_title("Hough transform") ax[1].set_xlabel("Angles (degrees)") ax[1].set_ylabel("Distance (pixels)") ax[1].axis("image") plt.show() if __name__ == "__main__": image = cv2.imread("0.0/00.pgm", cv2.COLOR_BGR2GRAY) accumulator, thetas, rhos = fast_hough_line(image) show_hough_line(image, accumulator, thetas, rhos) # Obtaining the lines from the accumulator sorted_idxs = np.dstack(np.unravel_index(np.argsort(accumulator.ravel()), accumulator.shape))[0][::-1] lines = [] for i, j in sorted_idxs: if accumulator[i, j] > 0: theta = np.deg2rad(thetas[j]) rho = rhos[i] - int(accumulator.shape[0] / 2) a = np.cos(theta) b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) lines.append(((x1, y1), (x2, y2))) # Printing the equations of the lines for line in lines: (x1, y1), (x2, y2) = line slope = (y2 - y1) / (x2 - x1) if (x2 - x1) != 0 else math.inf # @@@ intercept = y1 - slope * x1 print(f"y = {slope}x + {intercept}") НА ЭТОТ КОД ПОЛУЧАЮ ОШИБКУ: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-22-10a89d2e0053> in <cell line: 66>() 75 if accumulator[i, j] > 0: 76 theta = np.deg2rad(thetas[j]) ---> 77 rho = rhos[i] - int(accumulator.shape[0] / 2) 78 a = np.cos(theta) 79 b = np.sin(theta) IndexError: index 889 is out of bounds for axis 0 with size 298 ЧТО ДЕЛАТЬ?!
0bf6c2644b382e145ba03d261150b196
{ "intermediate": 0.2958414852619171, "beginner": 0.4432579576969147, "expert": 0.2609005868434906 }
32,515
Optimize python code
844b5f5af636952ad9923a78f662a6ee
{ "intermediate": 0.18916307389736176, "beginner": 0.3037698566913605, "expert": 0.5070670247077942 }
32,516
from matplotlib import pyplot as plt import numpy as np import math import cv2 potential_points_num = 200 image_threshold = 0 import numpy as np import math def fast_hough_line(img, angle_step=1, lines_are_white=True, value_threshold=5): """ Hough line using vectorized numpy operations. May take more memory, but takes much less time. """ # Rho and Theta ranges thetas = np.deg2rad(np.arange(-90.0, 90.0, angle_step)) #can be changed width, height = img.shape diag_len = int(np.ceil(np.sqrt(width * width + height * height))) rhos = np.linspace(-diag_len, diag_len, diag_len * 2) # Cache some resuable values cos_theta = np.cos(thetas) sin_theta = np.sin(thetas) num_thetas = len(thetas) # Hough accumulator array of theta vs rho accumulator = np.zeros((2 * diag_len, num_thetas)) are_edges = img > value_threshold if lines_are_white else img < value_threshold #are_edges = cv2.Canny(img,50,150,apertureSize = 3) y_idxs, x_idxs = np.nonzero(are_edges) # (row, col) indexes to edges # Vote in the hough accumulator xcosthetas = np.dot(x_idxs.reshape((-1,1)), cos_theta.reshape((1,-1))) ysinthetas = np.dot(y_idxs.reshape((-1,1)), sin_theta.reshape((1,-1))) rhosmat = np.round(xcosthetas + ysinthetas) + diag_len rhosmat = rhosmat.astype(np.int16) for i in range(num_thetas): rhos,counts = np.unique(rhosmat[:,i], return_counts=True) accumulator[rhos,rhosmat[:, i]] = counts return accumulator, thetas, rhos def show_hough_line(img, accumulator, thetas, rhos): import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 2, figsize=(10, 10)) ax[0].imshow(img) ax[0].set_title("Input image") ax[0].axis("image") ax[1].imshow( accumulator, cmap="jet", extent=[np.rad2deg(thetas[-1]), np.rad2deg(thetas[0]), rhos[-1], rhos[0]]) ax[1].set_aspect("equal", adjustable="box") ax[1].set_title("Hough transform") ax[1].set_xlabel("Angles (degrees)") ax[1].set_ylabel("Distance (pixels)") ax[1].axis("image") plt.show() image = cv2.imread("0.0/00.pgm", cv2.COLOR_BGR2GRAY) accumulator, thetas, rhos = fast_hough_line(image) show_hough_line(image, accumulator, thetas, rhos) # Obtaining the lines from the accumulator sorted_idxs = np.dstack(np.unravel_index(np.argsort(accumulator.ravel()), accumulator.shape))[0][::-1] lines = [] for i, j in sorted_idxs: if accumulator[i, j] > 0: theta = np.deg2rad(thetas[j]) rho = rhos[i] - int(accumulator.shape[0] / 2) a = np.cos(theta) b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) lines.append(((x1, y1), (x2, y2))) # Printing the equations of the lines for line in lines: (x1, y1), (x2, y2) = line slope = (y2 - y1) / (x2 - x1) if (x2 - x1) != 0 else math.inf # @@@ intercept = y1 - slope * x1 print(f"y = {slope}x + {intercept}") ПОЛУЧАЮ ТАКУЮ ОШИБКУ: --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-23-70a697845ba5> in <cell line: 66>() 66 if __name__ == "__main__": 67 image = cv2.imread("0.0/00.pgm", cv2.COLOR_BGR2GRAY) ---> 68 accumulator, thetas, rhos = fast_hough_line(image) 69 show_hough_line(image, accumulator, thetas, rhos) 70 <ipython-input-23-70a697845ba5> in fast_hough_line(img, angle_step, lines_are_white, value_threshold) 39 for i in range(num_thetas): 40 rhos,counts = np.unique(rhosmat[:,i], return_counts=True) ---> 41 accumulator[rhos,rhosmat[:, i]] = counts 42 return accumulator, thetas, rhos 43 IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (298,) (1307,) ЧТО ДЕЛАТЬ?!
992433ee005b0312a3aa8b950ca1ee33
{ "intermediate": 0.40628084540367126, "beginner": 0.367410808801651, "expert": 0.22630833089351654 }
32,517
Push your commits to your remote repository branch.
039f4c9af783fac792a944ebe6318b5b
{ "intermediate": 0.36974474787712097, "beginner": 0.23793497681617737, "expert": 0.39232027530670166 }
32,518
The following code is not working as intented, even though an error should be raised when the content vector is null it skips it you know why? for _ in range(RETRY_COUNT): try: doc["content_vector"] = embeddings_engine.embed_query(doc["content"] ) break except: sleep(30) if doc["content_vector"] is None: raise Exception(f"Error getting embedding for chunk={chunk}")
94aece54001adfd9d9cdc95439e730e1
{ "intermediate": 0.5597975254058838, "beginner": 0.19019627571105957, "expert": 0.25000616908073425 }
32,519
build one intensive malaysia lottery software
52326385f6a6b1896bb391370ce05af0
{ "intermediate": 0.19885969161987305, "beginner": 0.1769503504037857, "expert": 0.6241899728775024 }
32,520
Write a c++ program. User enters a string. A function prints the words and another one counts them. Use c-strings
8cddc177d9275a58530e8f3908612341
{ "intermediate": 0.3108764886856079, "beginner": 0.48562338948249817, "expert": 0.2035001963376999 }
32,521
from matplotlib import pyplot as plt import numpy as np import math import cv2 potential_points_num = 200 image_threshold = 0 import numpy as np import math def hough_line(img, angle_step=1, lines_are_white=True, value_threshold=5): """ Hough line using vectorized numpy operations. May take more memory, but takes much less time. """ # Rho and Theta ranges thetas = np.deg2rad(np.arange(-90.0, 90.0, angle_step)) width, height = img.shape diag_len = int(round(math.sqrt(width * width + height * height))) rhos = np.linspace(-diag_len, diag_len, diag_len * 2) # Cache some resuable values cos_t = np.cos(thetas) sin_t = np.sin(thetas) num_thetas = len(thetas) # Hough accumulator array of theta vs rho accumulator = np.zeros((2 * diag_len, num_thetas), dtype=np.uint8) # (row, col) indexes to edges are_edges = img > value_threshold if lines_are_white else img < value_threshold y_idxs, x_idxs = np.nonzero(are_edges) # Vote in the hough accumulator for i in range(len(x_idxs)): x = x_idxs[i] y = y_idxs[i] for t_idx in range(num_thetas): # Calculate rho. diag_len is added for a positive index rho = diag_len + int(round(x * cos_t[t_idx] + y * sin_t[t_idx])) accumulator[rho, t_idx] += 1 return accumulator, thetas, rhos def show_hough_line(img, accumulator, thetas, rhos): import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 2, figsize=(10, 10)) ax[0].imshow(img) ax[0].set_title("Input image") ax[0].axis("image") ax[1].imshow( accumulator, cmap="jet", extent=[np.rad2deg(thetas[-1]), np.rad2deg(thetas[0]), rhos[-1], rhos[0]]) ax[1].set_aspect("equal", adjustable="box") ax[1].set_title("Hough transform") ax[1].set_xlabel("Angles (degrees)") ax[1].set_ylabel("Distance (pixels)") ax[1].axis("image") plt.show() image = cv2.imread("0.0/00.pgm", cv2.COLOR_BGR2GRAY) accumulator, thetas, rhos = hough_line(image) show_hough_line(image, accumulator, thetas, rhos) # Obtaining the lines from the accumulator sorted_idxs = np.dstack(np.unravel_index(np.argsort(accumulator.ravel()), accumulator.shape))[0][::-1] lines = [] for i, j in sorted_idxs: if accumulator[i, j] > 0: theta = np.deg2rad(thetas[j]) rho = rhos[i] - int(accumulator.shape[0] / 2) a = np.cos(theta) b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) lines.append(((x1, y1), (x2, y2))) # Printing the equations of the lines for line in lines: (x1, y1), (x2, y2) = line slope = (y2 - y1) / (x2 - x1) if (x2 - x1) != 0 else math.inf # @@@ intercept = y1 - slope * x1 print(f"y = {slope}x + {intercept}") Надо, чтобы выводил три лучшие прямые только
1b98bbcc17e53e0af056ccf479f544d1
{ "intermediate": 0.28391751646995544, "beginner": 0.44599148631095886, "expert": 0.2700909376144409 }
32,522
Write a c++ program. User enters a string. A function prints the words and another one counts them. The length of the string is unknown. Use c-strings (char arrays)
656d2c832b483dac684866aa774b9a77
{ "intermediate": 0.29284924268722534, "beginner": 0.4862426519393921, "expert": 0.220908060669899 }