row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
32,122
image = cv2.imread("0.0/01.pgm", cv2.COLOR_BGR2GRAY) def get_coords_by_threshold(image: np.ndarray, threshold: int = 150) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = 100 ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image 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_neight_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, potential_points_num: int = 30 ) -> 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] # def get_best_lines(potential_points: np.ndarray) -> np.ndarray: # """ # Gets best combinations of lines by all points. # Line y = kx + b. # Returns np.ndarray like [[k1, b1], [k2, b2]]. # """ # best_lines = [] # best_inliers = [] # iterations_num = 1000 # threshold_distance = 3 # threshold_k = 0.1 # threshold_b = 10 # for i in range(iterations_num): # sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) # sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) # inliers = np.where(distances < threshold_distance)[0] # is_similar = False # for line in best_lines: # diff_k = abs(coefficients[0] - line[0]) # diff_b = abs(coefficients[0] - line[0]) # if diff_k <= threshold_k and diff_b <= threshold_b: # is_similar = True # break # if not is_similar and len(inliers) > len(best_inliers): # best_lines = [coefficients] # best_inliers = inliers # elif not is_similar and len(inliers) == len(best_inliers): # best_lines.append(coefficients) # return np.array(best_lines) def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: """Calculates the angle in degrees between two lines.""" import math k1, b1 = line1 k2, b2 = line2 angle_rad = math.atan2(k2 - k1, 1 + k1 * k2) angle_deg = math.degrees(angle_rad) return angle_deg def get_best_lines(potential_points: np.ndarray, min_angle: float = 30.0) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] best_inliers = [] iterations_num = 1000 threshold_distance = 5 threshold_k = 0.25 threshold_b = 10 for _ in range(3): local_best_lines = [] local_best_inliers = [] if potential_points.shape[0] < 3: break for i in range(iterations_num): sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inliers = np.where(distances < threshold_distance)[0] # Check if the current line is similar to any of the existing lines is_similar = False for line in local_best_lines: # Calculate the difference between k and b of the current line and the existing lines diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[0] - line[0]) # If the difference is smaller than the threshold, consider the current line as similar to the existing line if diff_k <= threshold_k and diff_b <= threshold_b: is_similar = True break # If the current line is not similar to any of the existing lines and has more inliers, consider it as a potential best line if not is_similar and len(inliers) > len(local_best_inliers): local_best_lines = [coefficients] local_best_inliers = inliers elif not is_similar and len(inliers) == len(local_best_inliers): local_best_lines.append(coefficients) # Update the potential points by removing the points that belong to the vicinity of the current best line mask = np.ones(len(potential_points), dtype=bool) for equation in local_best_lines: k, b = equation x = potential_points[:, 1] y = potential_points[:, 0] distances = np.abs(y - (k * x + b)) mask[np.where(distances < threshold_distance)[0]] = False best_lines.extend(local_best_lines) best_inliers.extend(local_best_inliers) # Update the potential points by keeping only the points that were not removed in the vicinity of the current best line potential_points = potential_points[mask] # Check the angles between the best lines if len(best_lines) >= 2: angles = [] for i in range(len(best_lines)): for j in range(i+1, len(best_lines)): angle = angle_between_lines(best_lines[i], best_lines[j]) angles.append(angle) if all(angle >= min_angle for angle in angles): break return np.array(best_lines[:3]) # main coords = get_coords_by_threshold(image) image = delete_pixels_by_min_threshold(image) neigh_nums = get_neigh_nums_list(coords) sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) best_lines = get_best_lines(potential_points) print(best_lines) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() # Plot the lines on the image for equation in best_lines: k, b = equation x = np.arange(0, image.shape[1]) y = k * x + b plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.plot(x, y, color="green") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() Нужно переписать код так, чтобы он искал прямые, угол между которыми БОЛЕЕ 30 градусов, прямые должны содержать как можно большее количество potential_points, без использования math, только numpy
3d7046d2c9f6b5a438df91665de4df0c
{ "intermediate": 0.27953797578811646, "beginner": 0.3785533308982849, "expert": 0.34190869331359863 }
32,123
def Change_Sheet(index): global Choose_sheet Choose_sheet = self.cb.itemText(index) print("选择的项是:", self.cb.itemText(index)) QMessageBox.information(self, "Tips", "CASE源已设置为" + self.cb.itemText(index), QMessageBox.Ok) return Choose_sheet这段代码中index表示什么
079593401e6b7ec39d72a44a728c5808
{ "intermediate": 0.2979243993759155, "beginner": 0.3711282014846802, "expert": 0.3309473991394043 }
32,124
Write me a mergerfs command that merges the directory /hdd1/downloads into /home/x/downloads
684cfb7b0653c95a0569199e8ab993f3
{ "intermediate": 0.470395565032959, "beginner": 0.1767140030860901, "expert": 0.3528904616832733 }
32,125
image = cv2.imread("0.0/01.pgm", cv2.COLOR_BGR2GRAY) def get_coords_by_threshold(image: np.ndarray, threshold: int = 150) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = 100 ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image 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_neight_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, potential_points_num: int = 30 ) -> 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] # def get_best_lines(potential_points: np.ndarray) -> np.ndarray: # """ # Gets best combinations of lines by all points. # Line y = kx + b. # Returns np.ndarray like [[k1, b1], [k2, b2]]. # """ # best_lines = [] # best_inliers = [] # iterations_num = 1000 # threshold_distance = 3 # threshold_k = 0.1 # threshold_b = 10 # for i in range(iterations_num): # sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) # sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) # inliers = np.where(distances < threshold_distance)[0] # is_similar = False # for line in best_lines: # diff_k = abs(coefficients[0] - line[0]) # diff_b = abs(coefficients[0] - line[0]) # if diff_k <= threshold_k and diff_b <= threshold_b: # is_similar = True # break # if not is_similar and len(inliers) > len(best_inliers): # best_lines = [coefficients] # best_inliers = inliers # elif not is_similar and len(inliers) == len(best_inliers): # best_lines.append(coefficients) # return np.array(best_lines) def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: """Calculates the angle in degrees between two lines.""" import math k1, b1 = line1 k2, b2 = line2 angle_rad = math.atan2(k2 - k1, 1 + k1 * k2) angle_deg = math.degrees(angle_rad) return angle_deg def get_best_lines(potential_points: np.ndarray, min_angle: float = 30.0) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] best_inliers = [] iterations_num = 1000 threshold_distance = 5 threshold_k = 0.25 threshold_b = 10 for _ in range(3): local_best_lines = [] local_best_inliers = [] if potential_points.shape[0] < 3: break for i in range(iterations_num): sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inliers = np.where(distances < threshold_distance)[0] # Check if the current line is similar to any of the existing lines is_similar = False for line in local_best_lines: # Calculate the difference between k and b of the current line and the existing lines diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[0] - line[0]) # If the difference is smaller than the threshold, consider the current line as similar to the existing line if diff_k <= threshold_k and diff_b <= threshold_b: is_similar = True break # If the current line is not similar to any of the existing lines and has more inliers, consider it as a potential best line if not is_similar and len(inliers) > len(local_best_inliers): local_best_lines = [coefficients] local_best_inliers = inliers elif not is_similar and len(inliers) == len(local_best_inliers): local_best_lines.append(coefficients) # Update the potential points by removing the points that belong to the vicinity of the current best line mask = np.ones(len(potential_points), dtype=bool) for equation in local_best_lines: k, b = equation x = potential_points[:, 1] y = potential_points[:, 0] distances = np.abs(y - (k * x + b)) mask[np.where(distances < threshold_distance)[0]] = False best_lines.extend(local_best_lines) best_inliers.extend(local_best_inliers) # Update the potential points by keeping only the points that were not removed in the vicinity of the current best line potential_points = potential_points[mask] # Check the angles between the best lines if len(best_lines) >= 2: angles = [] for i in range(len(best_lines)): for j in range(i+1, len(best_lines)): angle = angle_between_lines(best_lines[i], best_lines[j]) angles.append(angle) if all(angle >= min_angle for angle in angles): break return np.array(best_lines[:3]) # main coords = get_coords_by_threshold(image) image = delete_pixels_by_min_threshold(image) neigh_nums = get_neigh_nums_list(coords) sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) best_lines = get_best_lines(potential_points) print(best_lines) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() # Plot the lines on the image for equation in best_lines: k, b = equation x = np.arange(0, image.shape[1]) y = k * x + b plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.plot(x, y, color="green") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() Нужно переписать код так, чтобы он искал прямые, угол между которыми БОЛЕЕ 30 градусов, прямые должны содержать как можно большее количество potential_points, без использования math, только numpy НЕ ЗАБУДЬ ПРО ТАБУЛЯЦИЮ!
46ef33d8385465526e427a73f71f8385
{ "intermediate": 0.27953797578811646, "beginner": 0.3785533308982849, "expert": 0.34190869331359863 }
32,126
pcregrep: line 1661447 of file ./pcregrep.out is too long for the internal buffer pcregrep: check the --buffer-size option
c9a9d472622f2f4696df0d6145645828
{ "intermediate": 0.3798013925552368, "beginner": 0.3065199851989746, "expert": 0.31367868185043335 }
32,127
(require 2htdp/image) ;; SPD2-Design-Quiz-1.rkt ;; ====================================================================== ;; Constants (define COOKIES .) ;; ====================================================================== ;; Data Definitions ;; Natural is one of: ;; - 0 ;; - (add1 Natural) ;; interp. a natural number (define N0 0) ;0 (define N1 (add1 N0)) ;1 (define N2 (add1 N1)) ;2 #; (define (fn-for-natural n) (cond [(zero? n) (...)] [else (... n ; n is added because it's often useful (fn-for-natural (sub1 n)))])) ;; Template rules used: ;; - one-of: two cases ;; - atomic distinct: 0 ;; - compound: 2 fields ;; - self-reference: (sub1 n) is Natural ; PROBLEM 1: ; ; Complete the design of a function called pyramid that takes a natural ; number n and an image, and constructs an n-tall, n-wide pyramid of ; copies of that image. ; ; For instance, a 3-wide pyramid of cookies would look like this: ; ; . ;; Natural Image -> Image ;; produce an n-wide pyramid of the given image (check-expect (pyramid 0 COOKIES) empty-image) (check-expect (pyramid 1 COOKIES) COOKIES) (check-expect (pyramid 3 COOKIES) (above COOKIES (beside COOKIES COOKIES) (beside COOKIES COOKIES COOKIES))) ;(define (pyramid n i) empty-image) ; stub (define (pyramid n img) (cond [(zero? n) empty-image] [else (above (pyramid (sub1 n) img) (pyramid-row n img))])) (define (pyramid-row n img) (cond [(zero? n) empty-image] [else (beside img (pyramid-row (sub1 n) img))])) ; Problem 2: ; Consider a test tube filled with solid blobs and bubbles. Over time the ; solids sink to the bottom of the test tube, and as a consequence the bubbles ; percolate to the top. Let's capture this idea in BSL. ; ; Complete the design of a function that takes a list of blobs and sinks each ; solid blob by one. It's okay to assume that a solid blob sinks past any ; neighbor just below it. ; ; To assist you, we supply the relevant data definitions. ;; Blob is one of: ;; - "solid" ;; - "bubble" ;; interp. a gelatinous blob, either a solid or a bubble ;; Examples are redundant for enumerations #; (define (fn-for-blob b) (cond [(string=? b "solid") (...)] [(string=? b "bubble") (...)])) ;; Template rules used: ;; - one-of: 2 cases ;; - atomic distinct: "solid" ;; - atomic distinct: "bubble" ;; ListOfBlob is one of: ;; - empty ;; - (cons Blob ListOfBlob) ;; interp. a sequence of blobs in a test tube, listed from top to bottom. (define LOB0 empty) ; empty test tube (define LOB2 (cons "solid" (cons "bubble" empty))) ; solid blob above a bubble #; (define (fn-for-lob lob) (cond [(empty? lob) (...)] [else (... (fn-for-blob (first lob)) (fn-for-lob (rest lob)))])) ;; Template rules used ;; - one-of: 2 cases ;; - atomic distinct: empty ;; - compound: 2 fields ;; - reference: (first lob) is Blob ;; - self-reference: (rest lob) is ListOfBlob ;; ListOfBlob -> ListOfBlob ;; produce a list of blobs that sinks the given solid blobs by one (check-expect (sink empty) empty) (check-expect (sink (cons "bubble" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "bubble" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "bubble" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "bubble" (cons "solid" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" (cons "bubble" empty))))) (cons "bubble" (cons "solid" (cons "solid" (cons "bubble" empty))))) ;(define (sink lob) empty) ; stub (define (sink lob) (cond [(empty? lob) empty] [(empty? (rest lob)) lob] [(and (string=? (first lob) "solid") (string=? (second lob) "bubble")) (cons "bubble" (cons "solid" (sink (rest (rest lob)))))] [else (cons (first lob) (sink (rest lob)))])) Ran 10 tests. 2 of the 10 tests failed. Check failures: Actual value (list "solid" "bubble" "solid") differs from (list "bubble" "solid" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 103, column 0 Actual value (list "solid" "bubble" "solid" "bubble") differs from (list "bubble" "solid" "solid" "bubble"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 111, column 0
a06406fe77ae0e73ecada86f9265dffe
{ "intermediate": 0.39120349287986755, "beginner": 0.37113869190216064, "expert": 0.23765775561332703 }
32,128
def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: """Calculates the angle in degrees between two lines.""" k1, b1 = line1 k2, b2 = line2 angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2) angle_deg = np.degrees(angle_rad) return angle_deg def get_best_lines(potential_points: np.ndarray, min_angle: float = 30.0) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] best_inliers = [] iterations_num = 1000 threshold_distance = 5 threshold_k = 0.25 threshold_b = 10 for _ in range(3): local_best_lines = [] local_best_inliers = [] if potential_points.shape[0] < 3: break for i in range(iterations_num): sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inliers = np.where(distances < threshold_distance)[0] is_similar = False for line in local_best_lines: diff_k = np.abs(coefficients[0] - line[0]) diff_b = np.abs(coefficients[0] - line[0]) if diff_k <= threshold_k and diff_b <= threshold_b: is_similar = True break if not is_similar and len(inliers) > len(local_best_inliers): local_best_lines = [coefficients] local_best_inliers = inliers elif not is_similar and len(inliers) == len(local_best_inliers): local_best_lines.append(coefficients) mask = np.ones(len(potential_points), dtype=bool) for equation in local_best_lines: k, b = equation x = potential_points[:, 1] y = potential_points[:, 0] distances = np.abs(y - (k * x + b)) mask[np.where(distances < threshold_distance)[0]] = False best_lines.extend(local_best_lines) best_inliers.extend(local_best_inliers) potential_points = potential_points[mask] if len(best_lines) >= 2: angles = [] for i in range(len(best_lines)): for j in range(i+1, len(best_lines)): angle = angle_between_lines(best_lines[i], best_lines[j]) angles.append(angle) if all(angle >= min_angle for angle in angles): break return np.array(best_lines[:3]) Поставь в этом коде правильно пробелы(табуляцию)
826143488ea917d5b45ac28531d961d9
{ "intermediate": 0.22884677350521088, "beginner": 0.5735277533531189, "expert": 0.197625532746315 }
32,129
(require 2htdp/image) ;; SPD2-Design-Quiz-1.rkt ;; ====================================================================== ;; Constants (define COOKIES .) ;; ====================================================================== ;; Data Definitions ;; Natural is one of: ;; - 0 ;; - (add1 Natural) ;; interp. a natural number (define N0 0) ;0 (define N1 (add1 N0)) ;1 (define N2 (add1 N1)) ;2 #; (define (fn-for-natural n) (cond [(zero? n) (...)] [else (... n ; n is added because it's often useful (fn-for-natural (sub1 n)))])) ;; Template rules used: ;; - one-of: two cases ;; - atomic distinct: 0 ;; - compound: 2 fields ;; - self-reference: (sub1 n) is Natural ; PROBLEM 1: ; ; Complete the design of a function called pyramid that takes a natural ; number n and an image, and constructs an n-tall, n-wide pyramid of ; copies of that image. ; ; For instance, a 3-wide pyramid of cookies would look like this: ; ; . ;; Natural Image -> Image ;; produce an n-wide pyramid of the given image (check-expect (pyramid 0 COOKIES) empty-image) (check-expect (pyramid 1 COOKIES) COOKIES) (check-expect (pyramid 3 COOKIES) (above COOKIES (beside COOKIES COOKIES) (beside COOKIES COOKIES COOKIES))) ;(define (pyramid n i) empty-image) ; stub (define (pyramid n img) (cond [(zero? n) empty-image] [else (above (pyramid (sub1 n) img) (pyramid-row n img))])) (define (pyramid-row n img) (cond [(zero? n) empty-image] [else (beside img (pyramid-row (sub1 n) img))])) ; Problem 2: ; Consider a test tube filled with solid blobs and bubbles. Over time the ; solids sink to the bottom of the test tube, and as a consequence the bubbles ; percolate to the top. Let's capture this idea in BSL. ; ; Complete the design of a function that takes a list of blobs and sinks each ; solid blob by one. It's okay to assume that a solid blob sinks past any ; neighbor just below it. ; ; To assist you, we supply the relevant data definitions. ;; Blob is one of: ;; - "solid" ;; - "bubble" ;; interp. a gelatinous blob, either a solid or a bubble ;; Examples are redundant for enumerations #; (define (fn-for-blob b) (cond [(string=? b "solid") (...)] [(string=? b "bubble") (...)])) ;; Template rules used: ;; - one-of: 2 cases ;; - atomic distinct: "solid" ;; - atomic distinct: "bubble" ;; ListOfBlob is one of: ;; - empty ;; - (cons Blob ListOfBlob) ;; interp. a sequence of blobs in a test tube, listed from top to bottom. (define LOB0 empty) ; empty test tube (define LOB2 (cons "solid" (cons "bubble" empty))) ; solid blob above a bubble #; (define (fn-for-lob lob) (cond [(empty? lob) (...)] [else (... (fn-for-blob (first lob)) (fn-for-lob (rest lob)))])) ;; Template rules used ;; - one-of: 2 cases ;; - atomic distinct: empty ;; - compound: 2 fields ;; - reference: (first lob) is Blob ;; - self-reference: (rest lob) is ListOfBlob ;; ListOfBlob -> ListOfBlob ;; produce a list of blobs that sinks the given solid blobs by one (check-expect (sink empty) empty) (check-expect (sink (cons "bubble" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "bubble" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "bubble" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "bubble" (cons "solid" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" (cons "bubble" empty))))) (cons "bubble" (cons "solid" (cons "solid" (cons "bubble" empty))))) ;(define (sink lob) empty) ; stub (define (sink lob) (cond [(empty? lob) empty] [(and (string=? (first lob) "solid") (empty? (rest lob))) (cons "bubble" empty)] [(string=? (first lob) "solid") (cons "bubble" (sink (rest lob)))] [else (cons (first lob) (sink (rest lob)))])) Ran 10 tests. 6 of the 10 tests failed. Check failures: Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "bubble" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 101, column 0 Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 103, column 0 Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "bubble"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 105, column 0 Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 107, column 0 Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 109, column 0 Actual value (list "bubble" "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "solid" "bubble"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 111, column 0
7a52d930614d68da5c0c66c1c9fc00c8
{ "intermediate": 0.39120349287986755, "beginner": 0.37113869190216064, "expert": 0.23765775561332703 }
32,130
image = cv2.imread("0.0/01.pgm", cv2.COLOR_BGR2GRAY) def get_coords_by_threshold(image: np.ndarray, threshold: int = 150) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = 100 ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image 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_neight_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, potential_points_num: int = 30 ) -> 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] # def get_best_lines(potential_points: np.ndarray) -> np.ndarray: # """ # Gets best combinations of lines by all points. # Line y = kx + b. # Returns np.ndarray like [[k1, b1], [k2, b2]]. # """ # best_lines = [] # best_inliers = [] # iterations_num = 1000 # threshold_distance = 3 # threshold_k = 0.1 # threshold_b = 10 # for i in range(iterations_num): # sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) # sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) # inliers = np.where(distances < threshold_distance)[0] # is_similar = False # for line in best_lines: # diff_k = abs(coefficients[0] - line[0]) # diff_b = abs(coefficients[0] - line[0]) # if diff_k <= threshold_k and diff_b <= threshold_b: # is_similar = True # break # if not is_similar and len(inliers) > len(best_inliers): # best_lines = [coefficients] # best_inliers = inliers # elif not is_similar and len(inliers) == len(best_inliers): # best_lines.append(coefficients) # return np.array(best_lines) def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: """Calculates the angle in degrees between two lines.""" k1, b1 = line1 k2, b2 = line2 angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2) angle_deg = np.degrees(angle_rad) return angle_deg def get_best_lines(potential_points: np.ndarray, min_angle: float = 30.0) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] iterations_num = 1000 threshold_distance = 5 threshold_k = 0.5 threshold_b = 50 for _ in range(3): local_best_lines = [] if potential_points.shape[0] < 3: break for _ in range(iterations_num): sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inliers = np.where(distances < threshold_distance)[0] is_similar = False for line in local_best_lines: diff_k = np.abs(coefficients[0] - line[0]) diff_b = np.abs(coefficients[1] - line[1]) if diff_k <= threshold_k and diff_b <= threshold_b: is_similar = True break if not is_similar and len(inliers) > len(local_best_lines): local_best_lines = [coefficients] best_lines.extend(local_best_lines) mask = np.ones(len(potential_points), dtype=bool) for equation in local_best_lines: k, b = equation x = potential_points[:, 1] y = potential_points[:, 0] distances = np.abs(y - (k * x + b)) mask[np.where(distances < threshold_distance)[0]] = False potential_points = potential_points[mask] if len(best_lines) >= 3: angles = [] for i in range(len(best_lines)): for j in range(i+1, len(best_lines)): angle = angle_between_lines(best_lines[i], best_lines[j]) angles.append(angle) if all(angle >= min_angle for angle in angles): break return np.array(best_lines[:3]) # main coords = get_coords_by_threshold(image) image = delete_pixels_by_min_threshold(image) neigh_nums = get_neigh_nums_list(coords) sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) best_lines = get_best_lines(potential_points) print(best_lines) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() # Plot the lines on the image for equation in best_lines: k, b = equation x = np.arange(0, image.shape[1]) y = k * x + b plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.plot(x, y, color="green") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() переделай код, чтобы get_best_lines не использовал k threshold, а брал угол между прямыми, и если угол больше, чем минимальный, то добавлял прямую, а если нет, то продолжал искать
3da3272db7ad4d43dcfc1d69ce3715ff
{ "intermediate": 0.3117663562297821, "beginner": 0.3354601562023163, "expert": 0.3527734875679016 }
32,131
(require 2htdp/image) ;; SPD2-Design-Quiz-1.rkt ;; ====================================================================== ;; Constants (define COOKIES .) ;; ====================================================================== ;; Data Definitions ;; Natural is one of: ;; - 0 ;; - (add1 Natural) ;; interp. a natural number (define N0 0) ;0 (define N1 (add1 N0)) ;1 (define N2 (add1 N1)) ;2 #; (define (fn-for-natural n) (cond [(zero? n) (...)] [else (... n ; n is added because it's often useful (fn-for-natural (sub1 n)))])) ;; Template rules used: ;; - one-of: two cases ;; - atomic distinct: 0 ;; - compound: 2 fields ;; - self-reference: (sub1 n) is Natural ; PROBLEM 1: ; ; Complete the design of a function called pyramid that takes a natural ; number n and an image, and constructs an n-tall, n-wide pyramid of ; copies of that image. ; ; For instance, a 3-wide pyramid of cookies would look like this: ; ; . ;; Natural Image -> Image ;; produce an n-wide pyramid of the given image (check-expect (pyramid 0 COOKIES) empty-image) (check-expect (pyramid 1 COOKIES) COOKIES) (check-expect (pyramid 3 COOKIES) (above COOKIES (beside COOKIES COOKIES) (beside COOKIES COOKIES COOKIES))) ;(define (pyramid n i) empty-image) ; stub (define (pyramid n img) (cond [(zero? n) empty-image] [else (above (pyramid (sub1 n) img) (pyramid-row n img))])) (define (pyramid-row n img) (cond [(zero? n) empty-image] [else (beside img (pyramid-row (sub1 n) img))])) ; Problem 2: ; Consider a test tube filled with solid blobs and bubbles. Over time the ; solids sink to the bottom of the test tube, and as a consequence the bubbles ; percolate to the top. Let's capture this idea in BSL. ; ; Complete the design of a function that takes a list of blobs and sinks each ; solid blob by one. It's okay to assume that a solid blob sinks past any ; neighbor just below it. ; ; To assist you, we supply the relevant data definitions. ;; Blob is one of: ;; - "solid" ;; - "bubble" ;; interp. a gelatinous blob, either a solid or a bubble ;; Examples are redundant for enumerations #; (define (fn-for-blob b) (cond [(string=? b "solid") (...)] [(string=? b "bubble") (...)])) ;; Template rules used: ;; - one-of: 2 cases ;; - atomic distinct: "solid" ;; - atomic distinct: "bubble" ;; ListOfBlob is one of: ;; - empty ;; - (cons Blob ListOfBlob) ;; interp. a sequence of blobs in a test tube, listed from top to bottom. (define LOB0 empty) ; empty test tube (define LOB2 (cons "solid" (cons "bubble" empty))) ; solid blob above a bubble #; (define (fn-for-lob lob) (cond [(empty? lob) (...)] [else (... (fn-for-blob (first lob)) (fn-for-lob (rest lob)))])) ;; Template rules used ;; - one-of: 2 cases ;; - atomic distinct: empty ;; - compound: 2 fields ;; - reference: (first lob) is Blob ;; - self-reference: (rest lob) is ListOfBlob ;; ListOfBlob -> ListOfBlob ;; produce a list of blobs that sinks the given solid blobs by one (check-expect (sink empty) empty) (check-expect (sink (cons "bubble" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "bubble" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "bubble" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "bubble" (cons "solid" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" (cons "bubble" empty))))) (cons "bubble" (cons "solid" (cons "solid" (cons "bubble" empty))))) ;(define (sink lob) empty) ; stub (define (sink lob) (cond [(empty? lob) empty] [(string=? (first lob) "solid") (cons "bubble" (sink (rest lob)))] [else (cons (first lob) (sink (rest lob)))])) Ran 10 tests. 6 of the 10 tests failed. Check failures: Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "bubble" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 101, column 0 Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 103, column 0 Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "bubble"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 105, column 0 Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 107, column 0 Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 109, column 0 Actual value (list "bubble" "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "solid" "bubble"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 111, column 0
d61ed5cc12685a87e688d49e1596a871
{ "intermediate": 0.39120349287986755, "beginner": 0.37113869190216064, "expert": 0.23765775561332703 }
32,132
image = cv2.imread("0.0/01.pgm", cv2.COLOR_BGR2GRAY) def get_coords_by_threshold(image: np.ndarray, threshold: int = 150) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = 100 ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image 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_neight_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, potential_points_num: int = 30 ) -> 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] # def get_best_lines(potential_points: np.ndarray) -> np.ndarray: # """ # Gets best combinations of lines by all points. # Line y = kx + b. # Returns np.ndarray like [[k1, b1], [k2, b2]]. # """ # best_lines = [] # best_inliers = [] # iterations_num = 1000 # threshold_distance = 3 # threshold_k = 0.1 # threshold_b = 10 # for i in range(iterations_num): # sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) # sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) # inliers = np.where(distances < threshold_distance)[0] # is_similar = False # for line in best_lines: # diff_k = abs(coefficients[0] - line[0]) # diff_b = abs(coefficients[0] - line[0]) # if diff_k <= threshold_k and diff_b <= threshold_b: # is_similar = True # break # if not is_similar and len(inliers) > len(best_inliers): # best_lines = [coefficients] # best_inliers = inliers # elif not is_similar and len(inliers) == len(best_inliers): # best_lines.append(coefficients) # return np.array(best_lines) def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: """Calculates the angle in degrees between two lines.""" k1, b1 = line1 k2, b2 = line2 angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2) angle_deg = np.degrees(angle_rad) return angle_deg def get_best_lines(potential_points: np.ndarray, min_angle: float = 30.0) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] iterations_num = 1000 threshold_distance = 5 threshold_b = 50 for _ in range(iterations_num): sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inliers = np.where(distances < threshold_distance)[0] is_similar = False for line in best_lines: diff_b = np.abs(coefficients[1] - line[1]) if diff_b <= threshold_b: is_similar = True break if not is_similar and len(inliers) > len(best_lines): best_lines = [coefficients] potential_points = potential_points[inliers] if len(best_lines) >= 3: angles = [] for i in range(len(best_lines)): for j in range(i+1, len(best_lines)): angle = angle_between_lines(best_lines[i], best_lines[j]) angles.append(angle) if all(angle >= min_angle for angle in angles): break return np.array(best_lines[:3]) # main coords = get_coords_by_threshold(image) image = delete_pixels_by_min_threshold(image) neigh_nums = get_neigh_nums_list(coords) sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) best_lines = get_best_lines(potential_points) print(best_lines) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() # Plot the lines on the image for equation in best_lines: k, b = equation x = np.arange(0, image.shape[1]) y = k * x + b plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.plot(x, y, color="green") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() Этот код находит всего лишь одну прямую, и то не всегда верно, мы детектируем ТРЕУГОЛЬНИК"! Исправь get_best_lines()
5e75f2f4d80a47d6fda3ecb31a23c129
{ "intermediate": 0.3117663562297821, "beginner": 0.3354601562023163, "expert": 0.3527734875679016 }
32,133
I have the paths /hdd2/data and /home/x/data merged into /home/x/realdata using mergerfs. When I create a file in /home/x/realdata, it is only created to /hdd2/data. Will the path /home/x/data start filling up when /hdd2/data runs out of space?
32f7b3de3e70846525149bc622749a47
{ "intermediate": 0.41861531138420105, "beginner": 0.26150190830230713, "expert": 0.3198827803134918 }
32,134
image = cv2.imread("0.0/01.pgm", cv2.COLOR_BGR2GRAY) def get_coords_by_threshold(image: np.ndarray, threshold: int = 150) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = 100 ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image 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_neight_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, potential_points_num: int = 30 ) -> 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] def get_best_lines(potential_points: np.ndarray) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] best_inliers = [] iterations_num = 1000 threshold_distance = 3 threshold_k = 0.1 threshold_b = 10 for i in range(iterations_num): sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inliers = np.where(distances < threshold_distance)[0] is_similar = False for line in best_lines: diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[0] - line[0]) if diff_k <= threshold_k and diff_b <= threshold_b: is_similar = True break if not is_similar and len(inliers) > len(best_inliers): best_lines = [coefficients] best_inliers = inliers elif not is_similar and len(inliers) == len(best_inliers): best_lines.append(coefficients) return np.array(best_lines) def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: """Calculates the angle in degrees between two lines.""" k1, b1 = line1 k2, b2 = line2 angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2) angle_deg = np.degrees(angle_rad) return angle_deg # main coords = get_coords_by_threshold(image) image = delete_pixels_by_min_threshold(image) neigh_nums = get_neigh_nums_list(coords) sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) best_lines = get_best_lines(potential_points) print(best_lines) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() # Plot the lines on the image for equation in best_lines: k, b = equation x = np.arange(0, image.shape[1]) y = k * x + b plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.plot(x, y, color="green") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() Я пытаюсь детектировать треугольник, измени метод get_best_lines таким образом, чтобы он удалял potential_points, которые лежат на лучшей прямой, чтобы находить следующую, и искал три самых лучших прямых таким образом
f62c23dc21474a87ce8e86849ae19f2c
{ "intermediate": 0.31419637799263, "beginner": 0.349216103553772, "expert": 0.336587518453598 }
32,135
In a redis db I gotta save two things, 2. the hash of a question, then a list of hashes of answers to those questions. How should i implement this in python so i can search for a question, then get a list of answers. The whole system works only on hashes so the code does not need any example questions just placeholder phash hashes. Make functions for adding a question with a starting answer, to add a new answer to a question, and to add a question without known answers
999053ec3452c9d5de80c5ae3a351316
{ "intermediate": 0.5656683444976807, "beginner": 0.1488102525472641, "expert": 0.28552132844924927 }
32,136
(require 2htdp/image) ;; SPD2-Design-Quiz-1.rkt ;; ====================================================================== ;; Constants (define COOKIES .) ;; ====================================================================== ;; Data Definitions ;; Natural is one of: ;; - 0 ;; - (add1 Natural) ;; interp. a natural number (define N0 0) ;0 (define N1 (add1 N0)) ;1 (define N2 (add1 N1)) ;2 #; (define (fn-for-natural n) (cond [(zero? n) (…)] [else (… n ; n is added because it’s often useful (fn-for-natural (sub1 n)))])) ;; Template rules used: ;; - one-of: two cases ;; - atomic distinct: 0 ;; - compound: 2 fields ;; - self-reference: (sub1 n) is Natural ; PROBLEM 1: ; ; Complete the design of a function called pyramid that takes a natural ; number n and an image, and constructs an n-tall, n-wide pyramid of ; copies of that image. ; ; For instance, a 3-wide pyramid of cookies would look like this: ; ; . ;; Natural Image -> Image ;; produce an n-wide pyramid of the given image (check-expect (pyramid 0 COOKIES) empty-image) (check-expect (pyramid 1 COOKIES) COOKIES) (check-expect (pyramid 3 COOKIES) (above COOKIES (beside COOKIES COOKIES) (beside COOKIES COOKIES COOKIES))) ;(define (pyramid n i) empty-image) ; stub (define (pyramid n img) (cond [(zero? n) empty-image] [else (above (pyramid (sub1 n) img) (pyramid-row n img))])) (define (pyramid-row n img) (cond [(zero? n) empty-image] [else (beside img (pyramid-row (sub1 n) img))])) ; Problem 2: ; Consider a test tube filled with solid blobs and bubbles. Over time the ; solids sink to the bottom of the test tube, and as a consequence the bubbles ; percolate to the top. Let’s capture this idea in BSL. ; ; Complete the design of a function that takes a list of blobs and sinks each ; solid blob by one. It’s okay to assume that a solid blob sinks past any ; neighbor just below it. ; ; To assist you, we supply the relevant data definitions. ;; Blob is one of: ;; - “solid” ;; - “bubble” ;; interp. a gelatinous blob, either a solid or a bubble ;; Examples are redundant for enumerations #; (define (fn-for-blob b) (cond [(string=? b “solid”) (…)] [(string=? b “bubble”) (…)])) ;; Template rules used: ;; - one-of: 2 cases ;; - atomic distinct: “solid” ;; - atomic distinct: “bubble” ;; ListOfBlob is one of: ;; - empty ;; - (cons Blob ListOfBlob) ;; interp. a sequence of blobs in a test tube, listed from top to bottom. (define LOB0 empty) ; empty test tube (define LOB2 (cons “solid” (cons “bubble” empty))) ; solid blob above a bubble #; (define (fn-for-lob lob) (cond [(empty? lob) (…)] [else (… (fn-for-blob (first lob)) (fn-for-lob (rest lob)))])) ;; Template rules used ;; - one-of: 2 cases ;; - atomic distinct: empty ;; - compound: 2 fields ;; - reference: (first lob) is Blob ;; - self-reference: (rest lob) is ListOfBlob ;; ListOfBlob -> ListOfBlob ;; produce a list of blobs that sinks the given solid blobs by one (check-expect (sink empty) empty) (check-expect (sink (cons “bubble” (cons “solid” (cons “bubble” empty)))) (cons “bubble” (cons “bubble” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “solid” (cons “bubble” empty)))) (cons “bubble” (cons “solid” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “bubble” (cons “bubble” empty)))) (cons “bubble” (cons “solid” (cons “bubble” empty))))
0a95085e9a59fa7b07afa67c29a89398
{ "intermediate": 0.35803720355033875, "beginner": 0.39572906494140625, "expert": 0.2462337166070938 }
32,137
image = cv2.imread("0.4/02.pgm", cv2.COLOR_BGR2GRAY) IMAGE_THRESHOLD = 100 def get_coords_by_threshold( image: np.ndarray, threshold: int = IMAGE_THRESHOLD ) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = IMAGE_THRESHOLD ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image 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_neight_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, potential_points_num: int = 100 ) -> 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] # def get_best_lines(potential_points: np.ndarray) -> np.ndarray: # """ # Gets best combinations of lines by all points. # Line y = kx + b. # Returns np.ndarray like [[k1, b1], [k2, b2]]. # """ # best_lines = [] # best_inliers = [] # iterations_num = 1000 # threshold_distance = 3 # threshold_k = 0.1 # threshold_b = 10 # for i in range(iterations_num): # sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) # sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) # inliers = np.where(distances < threshold_distance)[0] # is_similar = False # for line in best_lines: # diff_k = abs(coefficients[0] - line[0]) # diff_b = abs(coefficients[0] - line[0]) # if diff_k <= threshold_k and diff_b <= threshold_b: # is_similar = True # break # if not is_similar and len(inliers) > len(best_inliers): # best_lines = [coefficients] # best_inliers = inliers # elif not is_similar and len(inliers) == len(best_inliers): # best_lines.append(coefficients) # return np.array(best_lines) def get_best_lines(potential_points: np.ndarray) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] num_lines = 0 iterations_num = 1000 threshold_distance = 3 threshold_k = 0.5 threshold_b = 20 while num_lines < 3: if num_lines == 0: remaining_points = np.copy(potential_points) best_inliers = [] best_line = None for i in range(iterations_num): sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False) 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) inliers = np.where(distances < 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 <= threshold_k and diff_b <= threshold_b: is_similar = True break if not is_similar and len(inliers) > len(best_inliers): best_line = coefficients best_inliers = inliers if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inliers, axis=0) num_lines += 1 return np.array(best_lines) # def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: # """Calculates the angle in degrees between two lines.""" # k1, b1 = line1 # k2, b2 = line2 # angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2) # angle_deg = np.degrees(angle_rad) # return angle_deg # main coords = get_coords_by_threshold(image) image = delete_pixels_by_min_threshold(image) neigh_nums = get_neigh_nums_list(coords) sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) best_lines = get_best_lines(potential_points) print(best_lines) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() # Plot the lines on the image for equation in best_lines: k, b = equation x = np.arange(0, image.shape[1]) y = k * x + b plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.plot(x, y, color="green") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() Метод get_best_lines не учитывает угла между прямыми, нужно сделать так, чтобы в конечном счете у нас остались только лучшие углы с минимальным углом между ними 30 градусов, а threshold_k тогда можно убрать. Обращаю внимание, что прямых по-прежнему должно вернуться три, то есть, если новая прямая нам не подходит по углу, мы продолжаем искать следующую, пока не найдем подходящую
33a7fcc7f5cff613c3ce00e720b8d14f
{ "intermediate": 0.2695120871067047, "beginner": 0.47828784584999084, "expert": 0.25220006704330444 }
32,138
(require 2htdp/image) ;; SPD2-Design-Quiz-1.rkt ;; ====================================================================== ;; Constants (define COOKIES .) ;; ====================================================================== ;; Data Definitions ;; Natural is one of: ;; - 0 ;; - (add1 Natural) ;; interp. a natural number (define N0 0) ;0 (define N1 (add1 N0)) ;1 (define N2 (add1 N1)) ;2 #; (define (fn-for-natural n) (cond [(zero? n) (...)] [else (... n ; n is added because it's often useful (fn-for-natural (sub1 n)))])) ;; Template rules used: ;; - one-of: two cases ;; - atomic distinct: 0 ;; - compound: 2 fields ;; - self-reference: (sub1 n) is Natural ; PROBLEM 1: ; ; Complete the design of a function called pyramid that takes a natural ; number n and an image, and constructs an n-tall, n-wide pyramid of ; copies of that image. ; ; For instance, a 3-wide pyramid of cookies would look like this: ; ; . ;; Natural Image -> Image ;; produce an n-wide pyramid of the given image (check-expect (pyramid 0 COOKIES) empty-image) (check-expect (pyramid 1 COOKIES) COOKIES) (check-expect (pyramid 3 COOKIES) (above COOKIES (beside COOKIES COOKIES) (beside COOKIES COOKIES COOKIES))) ;(define (pyramid n i) empty-image) ; stub (define (pyramid n img) (cond [(zero? n) empty-image] [else (above (pyramid (sub1 n) img) (pyramid-row n img))])) (define (pyramid-row n img) (cond [(zero? n) empty-image] [else (beside img (pyramid-row (sub1 n) img))])) ; Problem 2: ; Consider a test tube filled with solid blobs and bubbles. Over time the ; solids sink to the bottom of the test tube, and as a consequence the bubbles ; percolate to the top. Let's capture this idea in BSL. ; ; Complete the design of a function that takes a list of blobs and sinks each ; solid blob by one. It's okay to assume that a solid blob sinks past any ; neighbor just below it. ; ; To assist you, we supply the relevant data definitions. ;; Blob is one of: ;; - "solid" ;; - "bubble" ;; interp. a gelatinous blob, either a solid or a bubble ;; Examples are redundant for enumerations #; (define (fn-for-blob b) (cond [(string=? b "solid") (...)] [(string=? b "bubble") (...)])) ;; Template rules used: ;; - one-of: 2 cases ;; - atomic distinct: "solid" ;; - atomic distinct: "bubble" ;; ListOfBlob is one of: ;; - empty ;; - (cons Blob ListOfBlob) ;; interp. a sequence of blobs in a test tube, listed from top to bottom. (define LOB0 empty) ; empty test tube (define LOB2 (cons "solid" (cons "bubble" empty))) ; solid blob above a bubble #; (define (fn-for-lob lob) (cond [(empty? lob) (...)] [else (... (fn-for-blob (first lob)) (fn-for-lob (rest lob)))])) ;; Template rules used ;; - one-of: 2 cases ;; - atomic distinct: empty ;; - compound: 2 fields ;; - reference: (first lob) is Blob ;; - self-reference: (rest lob) is ListOfBlob ;; ListOfBlob -> ListOfBlob ;; produce a list of blobs that sinks the given solid blobs by one (check-expect (sink empty) empty) (check-expect (sink (cons "bubble" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "bubble" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "bubble" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "bubble" (cons "solid" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" (cons "bubble" empty))))) (cons "bubble" (cons "solid" (cons "solid" (cons "bubble" empty))))) ;(define (sink lob) empty) ; stub
5cdcd1a0bd060fdf18ac34f4c8cfada4
{ "intermediate": 0.39120349287986755, "beginner": 0.37113869190216064, "expert": 0.23765775561332703 }
32,139
image = cv2.imread("0.4/01.pgm", cv2.COLOR_BGR2GRAY) IMAGE_THRESHOLD = 100 def get_coords_by_threshold( image: np.ndarray, threshold: int = IMAGE_THRESHOLD ) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = IMAGE_THRESHOLD ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image 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_neight_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, potential_points_num: int = 100 ) -> 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] # def get_best_lines(potential_points: np.ndarray) -> np.ndarray: # """ # Gets best combinations of lines by all points. # Line y = kx + b. # Returns np.ndarray like [[k1, b1], [k2, b2]]. # """ # best_lines = [] # best_inliers = [] # iterations_num = 1000 # threshold_distance = 3 # threshold_k = 0.1 # threshold_b = 10 # for i in range(iterations_num): # sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) # sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) # inliers = np.where(distances < threshold_distance)[0] # is_similar = False # for line in best_lines: # diff_k = abs(coefficients[0] - line[0]) # diff_b = abs(coefficients[0] - line[0]) # if diff_k <= threshold_k and diff_b <= threshold_b: # is_similar = True # break # if not is_similar and len(inliers) > len(best_inliers): # best_lines = [coefficients] # best_inliers = inliers # elif not is_similar and len(inliers) == len(best_inliers): # best_lines.append(coefficients) # return np.array(best_lines) def get_best_lines(potential_points: np.ndarray) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] num_lines = 0 iterations_num = 1000 threshold_distance = 3 threshold_k = 0.5 threshold_b = 20 while num_lines < 3: if num_lines == 0: remaining_points = np.copy(potential_points) best_inliers = [] best_line = None for i in range(iterations_num): sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False) 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) inliers = np.where(distances < 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 <= threshold_k and diff_b <= threshold_b: is_similar = True break if not is_similar and len(inliers) > len(best_inliers): best_line = coefficients best_inliers = inliers if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inliers, axis=0) num_lines += 1 return np.array(best_lines) # def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: # """Calculates the angle in degrees between two lines.""" # k1, b1 = line1 # k2, b2 = line2 # angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2) # angle_deg = np.degrees(angle_rad) # return angle_deg # main image = cv2.GaussianBlur(image, (25, 25), 0) coords = get_coords_by_threshold(image) # image = delete_pixels_by_min_threshold(image) neigh_nums = get_neigh_nums_list(coords) sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) best_lines = get_best_lines(potential_points) print(best_lines) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() # Plot the lines on the image for equation in best_lines: k, b = equation x = np.arange(0, image.shape[1]) y = k * x + b plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.plot(x, y, color="green") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() ПОЧЕМУ Я ПОЛУЧАЮ ТАКУЮ ОШИБКУ? --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-217-e95d675608e0> in <cell line: 185>() 183 neigh_nums = get_neigh_nums_list(coords) 184 --> 185 sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) 186 187 potential_points = get_potential_points_coords(sorted_neigh_nums) <ipython-input-217-e95d675608e0> in sort_neight_nums_by_N(neigh_nums) 53 54 np_neigh_nums = np_neigh_nums[ ---> 55 (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] 56 57 np_neigh_nums = np_neigh_nums[ IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
24125991d151d45ec761e2d1df98a830
{ "intermediate": 0.2705646753311157, "beginner": 0.4763101041316986, "expert": 0.25312525033950806 }
32,140
(require 2htdp/image) ;; SPD2-Design-Quiz-1.rkt ;; ====================================================================== ;; Constants (define COOKIES .) ;; ====================================================================== ;; Data Definitions ;; Natural is one of: ;; - 0 ;; - (add1 Natural) ;; interp. a natural number (define N0 0) ;0 (define N1 (add1 N0)) ;1 (define N2 (add1 N1)) ;2 #; (define (fn-for-natural n) (cond [(zero? n) (…)] [else (… n ; n is added because it’s often useful (fn-for-natural (sub1 n)))])) ;; Template rules used: ;; - one-of: two cases ;; - atomic distinct: 0 ;; - compound: 2 fields ;; - self-reference: (sub1 n) is Natural ; PROBLEM 1: ; ; Complete the design of a function called pyramid that takes a natural ; number n and an image, and constructs an n-tall, n-wide pyramid of ; copies of that image. ; ; For instance, a 3-wide pyramid of cookies would look like this: ; ; . ;; Natural Image -> Image ;; produce an n-wide pyramid of the given image (check-expect (pyramid 0 COOKIES) empty-image) (check-expect (pyramid 1 COOKIES) COOKIES) (check-expect (pyramid 3 COOKIES) (above COOKIES (beside COOKIES COOKIES) (beside COOKIES COOKIES COOKIES))) ;(define (pyramid n i) empty-image) ; stub (define (pyramid n img) (cond [(zero? n) empty-image] [else (above (pyramid (sub1 n) img) (pyramid-row n img))])) (define (pyramid-row n img) (cond [(zero? n) empty-image] [else (beside img (pyramid-row (sub1 n) img))])) ; Problem 2: ; Consider a test tube filled with solid blobs and bubbles. Over time the ; solids sink to the bottom of the test tube, and as a consequence the bubbles ; percolate to the top. Let’s capture this idea in BSL. ; ; Complete the design of a function that takes a list of blobs and sinks each ; solid blob by one. It’s okay to assume that a solid blob sinks past any ; neighbor just below it. ; ; To assist you, we supply the relevant data definitions. ;; Blob is one of: ;; - “solid” ;; - “bubble” ;; interp. a gelatinous blob, either a solid or a bubble ;; Examples are redundant for enumerations #; (define (fn-for-blob b) (cond [(string=? b “solid”) (…)] [(string=? b “bubble”) (…)])) ;; Template rules used: ;; - one-of: 2 cases ;; - atomic distinct: “solid” ;; - atomic distinct: “bubble” ;; ListOfBlob is one of: ;; - empty ;; - (cons Blob ListOfBlob) ;; interp. a sequence of blobs in a test tube, listed from top to bottom. (define LOB0 empty) ; empty test tube (define LOB2 (cons “solid” (cons “bubble” empty))) ; solid blob above a bubble #; (define (fn-for-lob lob) (cond [(empty? lob) (…)] [else (… (fn-for-blob (first lob)) (fn-for-lob (rest lob)))])) ;; Template rules used ;; - one-of: 2 cases ;; - atomic distinct: empty ;; - compound: 2 fields ;; - reference: (first lob) is Blob ;; - self-reference: (rest lob) is ListOfBlob ;; ListOfBlob -> ListOfBlob ;; produce a list of blobs that sinks the given solid blobs by one (check-expect (sink empty) empty) (check-expect (sink (cons “bubble” (cons “solid” (cons “bubble” empty)))) (cons “bubble” (cons “bubble” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “solid” (cons “bubble” empty)))) (cons “bubble” (cons “solid” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “bubble” (cons “bubble” empty)))) (cons “bubble” (cons “solid” (cons “bubble” empty)))) (check-expect (sink (cons “solid” (cons “bubble” (cons “solid” empty)))) (cons “bubble” (cons “solid” (cons “solid” empty)))) (check-expect (sink (cons “bubble” (cons “solid” (cons “solid” empty)))) (cons “bubble” (cons “solid” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “solid” (cons “bubble” (cons “bubble” empty))))) (cons “bubble” (cons “solid” (cons “solid” (cons “bubble” empty))))) ;(define (sink lob) empty) ; stub (define (sink lob) (cond [(empty? lob) empty] [else (cons (sink-blob (first lob) (second lob)) (sink (rest lob)))])) (define (sink-blob b n) (cond [(and (string=? b “solid”) (string=? n “bubble”)) “bubble”] [else b])) Ran 10 tests. 6 of the 10 tests failed. Check failures: check-expect encountered the following error instead of the expected value, (list “bubble” “bubble” “solid”). :: second: expects a list with 2 or more items; given: (list “bubble”) in Naturals-and-Helpers-Design-Quiz (1).rkt, line 101, column 0 caused by expression in Naturals-and-Helpers-Design-Quiz (1).rkt, line 119, column 43 check-expect encountered the following error instead of the expected value, (list “bubble” “solid” “solid”). :: second: expects a list with 2 or more items; given: (list “bubble”) in Naturals-and-Helpers-Design-Quiz (1).rkt, line 103, column 0 caused by expression in Naturals-and-Helpers-Design-Quiz (1).rkt, line 119, column 43 check-expect encountered the following error instead of the expected value, (list “bubble” “solid” “bubble”). :: second: expects a list with 2 or more items; given: (list “bubble”) in Naturals-and-Helpers-Design-Quiz (1).rkt, line 105, column 0 caused by expression in Naturals-and-Helpers-Design-Quiz (1).rkt, line 119, column 43 check-expect encountered the following error instead of the expected value, (list “bubble” “solid” “solid”). :: second: expects a list with 2 or more items; given: (list “solid”) in Naturals-and-Helpers-Design-Quiz (1).rkt, line 107, column 0 caused by expression in Naturals-and-Helpers-Design-Quiz (1).rkt, line 119, column 43 check-expect encountered the following error instead of the expected value, (list “bubble” “solid” “solid”). :: second: expects a list with 2 or more items; given: (list “solid”) in Naturals-and-Helpers-Design-Quiz (1).rkt, line 109, column 0 caused by expression in Naturals-and-Helpers-Design-Quiz (1).rkt, line 119, column 43 check-expect encountered the following error instead of the expected value, (list “bubble” “solid” “solid” “bubble”). :: second: expects a list with 2 or more items; given: (list “bubble”) in Naturals-and-Helpers-Design-Quiz (1).rkt, line 111, column 0 caused by expression in Naturals-and-Helpers-Design-Quiz (1).rkt, line 119, column 43
105c42f0936da702559896820281f569
{ "intermediate": 0.35803720355033875, "beginner": 0.39572906494140625, "expert": 0.2462337166070938 }
32,141
i used this for generate unique code but does not work what is the problem: <!DOCTYPE html> <html> <body> <?php echo uniqid(); ?> </body> </html>
dec3fe1c632ad411b29cdd41701ec758
{ "intermediate": 0.3699316382408142, "beginner": 0.3192090690135956, "expert": 0.3108592927455902 }
32,142
(require 2htdp/image) ;; SPD2-Design-Quiz-1.rkt ;; ====================================================================== ;; Constants (define COOKIES .) ;; ====================================================================== ;; Data Definitions ;; Natural is one of: ;; - 0 ;; - (add1 Natural) ;; interp. a natural number (define N0 0) ;0 (define N1 (add1 N0)) ;1 (define N2 (add1 N1)) ;2 #; (define (fn-for-natural n) (cond [(zero? n) (...)] [else (... n ; n is added because it's often useful (fn-for-natural (sub1 n)))])) ;; Template rules used: ;; - one-of: two cases ;; - atomic distinct: 0 ;; - compound: 2 fields ;; - self-reference: (sub1 n) is Natural ; PROBLEM 1: ; ; Complete the design of a function called pyramid that takes a natural ; number n and an image, and constructs an n-tall, n-wide pyramid of ; copies of that image. ; ; For instance, a 3-wide pyramid of cookies would look like this: ; ; . ;; Natural Image -> Image ;; produce an n-wide pyramid of the given image (check-expect (pyramid 0 COOKIES) empty-image) (check-expect (pyramid 1 COOKIES) COOKIES) (check-expect (pyramid 3 COOKIES) (above COOKIES (beside COOKIES COOKIES) (beside COOKIES COOKIES COOKIES))) ;(define (pyramid n i) empty-image) ; stub (define (pyramid n img) (cond [(zero? n) empty-image] [else (above (pyramid (sub1 n) img) (pyramid-row n img))])) (define (pyramid-row n img) (cond [(zero? n) empty-image] [else (beside img (pyramid-row (sub1 n) img))])) ; Problem 2: ; Consider a test tube filled with solid blobs and bubbles. Over time the ; solids sink to the bottom of the test tube, and as a consequence the bubbles ; percolate to the top. Let's capture this idea in BSL. ; ; Complete the design of a function that takes a list of blobs and sinks each ; solid blob by one. It's okay to assume that a solid blob sinks past any ; neighbor just below it. ; ; To assist you, we supply the relevant data definitions. ;; Blob is one of: ;; - "solid" ;; - "bubble" ;; interp. a gelatinous blob, either a solid or a bubble ;; Examples are redundant for enumerations #; (define (fn-for-blob b) (cond [(string=? b "solid") (...)] [(string=? b "bubble") (...)])) ;; Template rules used: ;; - one-of: 2 cases ;; - atomic distinct: "solid" ;; - atomic distinct: "bubble" ;; ListOfBlob is one of: ;; - empty ;; - (cons Blob ListOfBlob) ;; interp. a sequence of blobs in a test tube, listed from top to bottom. (define LOB0 empty) ; empty test tube (define LOB2 (cons "solid" (cons "bubble" empty))) ; solid blob above a bubble #; (define (fn-for-lob lob) (cond [(empty? lob) (...)] [else (... (fn-for-blob (first lob)) (fn-for-lob (rest lob)))])) ;; Template rules used ;; - one-of: 2 cases ;; - atomic distinct: empty ;; - compound: 2 fields ;; - reference: (first lob) is Blob ;; - self-reference: (rest lob) is ListOfBlob ;; ListOfBlob -> ListOfBlob ;; produce a list of blobs that sinks the given solid blobs by one (check-expect (sink empty) empty) (check-expect (sink (cons "bubble" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "bubble" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "bubble" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "bubble" (cons "solid" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" (cons "bubble" empty))))) (cons "bubble" (cons "solid" (cons "solid" (cons "bubble" empty))))) ;(define (sink lob) empty) ; stub (define (sink lob) (cond [(empty? lob) empty] [(not (empty? (rest lob))) (cons (sink-blob (first lob) (first (rest lob))) (sink (rest lob)))] [else lob])) (define (sink-blob b n) (if (and (string=? b "solid") (string=? n "bubble")) "bubble" b)) Ran 10 tests. 5 of the 10 tests failed. Check failures: Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "bubble" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 101, column 0 Actual value (list "solid" "bubble" "bubble") differs from (list "bubble" "solid" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 103, column 0 Actual value (list "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "bubble"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 105, column 0 Actual value (list "bubble" "bubble" "solid") differs from (list "bubble" "solid" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 107, column 0 Actual value (list "solid" "bubble" "bubble" "bubble") differs from (list "bubble" "solid" "solid" "bubble"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 111, column 0 write for me the function sink lob for problem and only use function and variable that have been given by the problem.
a7a3a59919428d6869f281551700dfd6
{ "intermediate": 0.35790303349494934, "beginner": 0.2772781252861023, "expert": 0.364818811416626 }
32,143
(require 2htdp/image) ;; SPD2-Design-Quiz-1.rkt ;; ====================================================================== ;; Constants (define COOKIES .) ;; ====================================================================== ;; Data Definitions ;; Natural is one of: ;; - 0 ;; - (add1 Natural) ;; interp. a natural number (define N0 0) ;0 (define N1 (add1 N0)) ;1 (define N2 (add1 N1)) ;2 #; (define (fn-for-natural n) (cond [(zero? n) (...)] [else (... n ; n is added because it's often useful (fn-for-natural (sub1 n)))])) ;; Template rules used: ;; - one-of: two cases ;; - atomic distinct: 0 ;; - compound: 2 fields ;; - self-reference: (sub1 n) is Natural ; PROBLEM 1: ; ; Complete the design of a function called pyramid that takes a natural ; number n and an image, and constructs an n-tall, n-wide pyramid of ; copies of that image. ; ; For instance, a 3-wide pyramid of cookies would look like this: ; ; . ;; Natural Image -> Image ;; produce an n-wide pyramid of the given image (check-expect (pyramid 0 COOKIES) empty-image) (check-expect (pyramid 1 COOKIES) COOKIES) (check-expect (pyramid 3 COOKIES) (above COOKIES (beside COOKIES COOKIES) (beside COOKIES COOKIES COOKIES))) ;(define (pyramid n i) empty-image) ; stub (define (pyramid n img) (cond [(zero? n) empty-image] [else (above (pyramid (sub1 n) img) (pyramid-row n img))])) (define (pyramid-row n img) (cond [(zero? n) empty-image] [else (beside img (pyramid-row (sub1 n) img))])) ; Problem 2: ; Consider a test tube filled with solid blobs and bubbles. Over time the ; solids sink to the bottom of the test tube, and as a consequence the bubbles ; percolate to the top. Let's capture this idea in BSL. ; ; Complete the design of a function that takes a list of blobs and sinks each ; solid blob by one. It's okay to assume that a solid blob sinks past any ; neighbor just below it. ; ; To assist you, we supply the relevant data definitions. ;; Blob is one of: ;; - "solid" ;; - "bubble" ;; interp. a gelatinous blob, either a solid or a bubble ;; Examples are redundant for enumerations #; (define (fn-for-blob b) (cond [(string=? b "solid") (...)] [(string=? b "bubble") (...)])) ;; Template rules used: ;; - one-of: 2 cases ;; - atomic distinct: "solid" ;; - atomic distinct: "bubble" ;; ListOfBlob is one of: ;; - empty ;; - (cons Blob ListOfBlob) ;; interp. a sequence of blobs in a test tube, listed from top to bottom. (define LOB0 empty) ; empty test tube (define LOB2 (cons "solid" (cons "bubble" empty))) ; solid blob above a bubble #; (define (fn-for-lob lob) (cond [(empty? lob) (...)] [else (... (fn-for-blob (first lob)) (fn-for-lob (rest lob)))])) ;; Template rules used ;; - one-of: 2 cases ;; - atomic distinct: empty ;; - compound: 2 fields ;; - reference: (first lob) is Blob ;; - self-reference: (rest lob) is ListOfBlob ;; ListOfBlob -> ListOfBlob ;; produce a list of blobs that sinks the given solid blobs by one (check-expect (sink empty) empty) (check-expect (sink (cons "bubble" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "bubble" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "bubble" empty)))) (cons "bubble" (cons "solid" (cons "bubble" empty)))) (check-expect (sink (cons "solid" (cons "bubble" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "bubble" (cons "solid" (cons "solid" empty)))) (cons "bubble" (cons "solid" (cons "solid" empty)))) (check-expect (sink (cons "solid" (cons "solid" (cons "bubble" (cons "bubble" empty))))) (cons "bubble" (cons "solid" (cons "solid" (cons "bubble" empty))))) ;(define (sink lob) empty) ; stub (define (sink lob) (cond [(empty? lob) empty] [(empty? (rest lob)) lob] [(and (string=? (first lob) "solid") (string=? (second lob) "bubble")) (cons "bubble" (cons "solid" (sink (rest (rest lob)))))] [else (cons (first lob) (sink (rest lob)))])) Ran 10 tests. 2 of the 10 tests failed. Check failures: Actual value (list "solid" "bubble" "solid") differs from (list "bubble" "solid" "solid"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 103, column 0 Actual value (list "solid" "bubble" "solid" "bubble") differs from (list "bubble" "solid" "solid" "bubble"), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 111, column 0
c34ef3e0540879926b6290bb25de486e
{ "intermediate": 0.39120349287986755, "beginner": 0.37113869190216064, "expert": 0.23765775561332703 }
32,144
(check-expect (sink empty) empty) (check-expect (sink (cons “bubble” (cons “solid” (cons “bubble” empty)))) (cons “bubble” (cons “bubble” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “solid” (cons “bubble” empty)))) (cons “bubble” (cons “solid” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “bubble” (cons “bubble” empty)))) (cons “bubble” (cons “solid” (cons “bubble” empty)))) (check-expect (sink (cons “solid” (cons “bubble” (cons “solid” empty)))) (cons “bubble” (cons “solid” (cons “solid” empty)))) (check-expect (sink (cons “bubble” (cons “solid” (cons “solid” empty)))) (cons “bubble” (cons “solid” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “solid” (cons “bubble” (cons “bubble” empty))))) (cons “bubble” (cons “solid” (cons “solid” (cons “bubble” empty))))) ;(define (sink lob) empty) ; stub (define (sink lob) (cond [(empty? lob) empty] [(empty? (rest lob)) lob] [(and (string=? (first lob) “solid”) (string=? (second lob) “solid”)) (cons “solid” (sink (rest lob)))] [(and (string=? (first lob) “solid”) (string=? (second lob) “bubble”)) (cons “bubble” (cons “solid” (sink (rest (rest lob)))))] [else (cons (first lob) (sink (rest lob)))])) correct the code until it does not get the following error: Ran 10 tests. 2 of the 10 tests failed. Check failures: Actual value (list “solid” “bubble” “solid”) differs from (list “bubble” “solid” “solid”), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 103, column 0 Actual value (list “solid” “bubble” “solid” “bubble”) differs from (list “bubble” “solid” “solid” “bubble”), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 111, column 0
5ffeabc2a4ab2a24988093959d078780
{ "intermediate": 0.23677612841129303, "beginner": 0.45879489183425903, "expert": 0.30442899465560913 }
32,145
(check-expect (sink empty) empty) (check-expect (sink (cons “bubble” (cons “solid” (cons “bubble” empty)))) (cons “bubble” (cons “bubble” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “solid” (cons “bubble” empty)))) (cons “bubble” (cons “solid” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “bubble” (cons “bubble” empty)))) (cons “bubble” (cons “solid” (cons “bubble” empty)))) (check-expect (sink (cons “solid” (cons “bubble” (cons “solid” empty)))) (cons “bubble” (cons “solid” (cons “solid” empty)))) (check-expect (sink (cons “bubble” (cons “solid” (cons “solid” empty)))) (cons “bubble” (cons “solid” (cons “solid” empty)))) (check-expect (sink (cons “solid” (cons “solid” (cons “bubble” (cons “bubble” empty))))) (cons “bubble” (cons “solid” (cons “solid” (cons “bubble” empty))))) ;(define (sink lob) empty) ; stub (define (sink lob) (cond [(empty? lob) empty] [(empty? (rest lob)) lob] [(and (string=? (first lob) “solid”) (string=? (second lob) “solid”)) (cons “solid” (sink (rest lob)))] [(and (string=? (first lob) “solid”) (string=? (second lob) “bubble”)) (cons “bubble” (cons “solid” (sink (rest (rest lob)))))] [else (cons (first lob) (sink (rest lob)))])) correct the code until it does not get the following error: Ran 10 tests. 2 of the 10 tests failed. Check failures: Actual value (list “solid” “bubble” “solid”) differs from (list “bubble” “solid” “solid”), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 103, column 0 Actual value (list “solid” “bubble” “solid” “bubble”) differs from (list “bubble” “solid” “solid” “bubble”), the expected value. in Naturals-and-Helpers-Design-Quiz (1).rkt, line 111, column 0
b1901c2c0612f03de18193f6588a9efa
{ "intermediate": 0.23677612841129303, "beginner": 0.45879489183425903, "expert": 0.30442899465560913 }
32,146
AttributeError: module 'jieba' has no attribute 'cut'什么意思
fa888900c9b31e519d6e085b1e0dd0a9
{ "intermediate": 0.4219312369823456, "beginner": 0.2770443260669708, "expert": 0.3010244071483612 }
32,147
Rewrite the following script to make it cleaner and more reusable. Some part of this script could be used in future other script. <script> """ Live area detection from TI data. Run this script with the following parameters: --conf=conf/live_area_detection.json """ import math import numpy as np from radar_toolbox.fmcw_utils import RadarModel from radar_toolbox.utils import configure_argument_parser_for_conf_file, load_conf, get_reader_from_config, \ points_inclination_correction from radar_area_detection.detection import AreaDetector from radar_area_detection.comm.camera_alert import CameraAlert from radar_tracking.tracking_utils import get_capture_limits_from_conf, get_clustering_algo_from_conf, \ get_cluster_tracker_from_conf if __name__ == "__main__": args = configure_argument_parser_for_conf_file() config = load_conf(args.conf) rabbitmq_conf = load_conf(config["rabbitmq_conf"]) if rabbitmq_conf["enable"]: from radar_area_detection.comm.rabbitmq import RabbitMQSender import json rabbitmq_sender = RabbitMQSender(host=rabbitmq_conf["host"], port=rabbitmq_conf["port"], queue=rabbitmq_conf["queue"], exchange=rabbitmq_conf["exchange"]) rabbitmq_sender.connect() cfg_file_path = config["cfg_file_path"] radar_model = RadarModel.get_model_from_str(config["model"]) min_velocity_detection = config["min_point_vel"] horizontal_inclination = vertical_inclination = None if config["horizontal_inclination"] is not None: horizontal_inclination = math.radians(config["horizontal_inclination"]) if config["vertical_inclination"] is not None: vertical_inclination = math.radians(config["vertical_inclination"]) tracking_conf = load_conf(config["tracking_conf"]) frame_grouping_size = tracking_conf["frame_grouping_size"] # How many frames do we want per step dt = tracking_conf["frame_interval"] * frame_grouping_size # Delta time between two steps verbose = tracking_conf["verbose"] capture_limits = get_capture_limits_from_conf(config=tracking_conf) clustering_algo = get_clustering_algo_from_conf(config=tracking_conf) cluster_tracker = get_cluster_tracker_from_conf(config=tracking_conf) local_display = config["local_display"] if local_display: from matplotlib import pyplot as plt from radar_area_detection.display import AreasDisplay2D from radar_visuals.display import PlayingMode areaDisplay = AreasDisplay2D(dt=dt, capture_limits=capture_limits, playing_mode=PlayingMode.NO_WAIT, time_fade_out=tracking_conf["time_fade_out"]) area_conf = load_conf(config["area_detection_conf"]) alerts = None if area_conf["camera"]["enable"]: camera_alert = CameraAlert(ip=area_conf["camera"]["ip"], port=area_conf["camera"]["port"]) alerts = [camera_alert] area_detector = AreaDetector(areas=area_conf["areas"], alerts=alerts) # Configure the serial port reader = get_reader_from_config(config=config) reader.connect(cli_port=config["CLI_port"], data_port=config["data_port"]) reader.send_config(cfg_file_path=cfg_file_path) reader.start_sensor(listen_to_data=True) try: while True: result = reader.parse_stream(only_points=True) # check if the data is okay if result["data_ok"]: if result["detected_points"] is None: points = [] else: points = result["detected_points"] if radar_model == RadarModel.IWR6843AOP and min_velocity_detection is not None: points = points[np.abs(points[:, 3]) > min_velocity_detection] points = points_inclination_correction(points[:, :3], horizontal_inclination, vertical_inclination) points = points[np.all(capture_limits[:, 0] < points, axis=1)] points = points[np.all(points < capture_limits[:, 1], axis=1)] # Tracking clusters, noise = clustering_algo.clusterize(points) cluster_tracker.TrackNextTimeStep(current_clusters=clusters, verbose=verbose) # Intrusion detection area_detector.update(clusters_up_to_date=cluster_tracker.tracked_clusters) if local_display: areaDisplay.show(clusters=cluster_tracker.tracked_clusters, area_detector=area_detector) if rabbitmq_conf["enable"]: json_data = { "areas": area_detector.serialize(), "clusters": cluster_tracker.serialize() } json_data = json.dumps(json_data) rabbitmq_sender.send_json(json_data) except KeyboardInterrupt: # Stop the program and close everything if Ctrl + c is pressed pass finally: reader.disconnect() if local_display: plt.close('all') if rabbitmq_conf["enable"]: rabbitmq_sender.disconnect() </script>
756debcaf45b5c48bc7ae52cce0d9747
{ "intermediate": 0.4041692912578583, "beginner": 0.3182021379470825, "expert": 0.27762848138809204 }
32,148
could you please speed up this function as much as possible? def conjunction_rule_2(self, interpretation): items_to_add = set() for concept in self.concepts: # If d has C and D assigned, assign also C ⊓D to d. for other_concept in self.concepts: conjunction_to_check = self.elFactory.getConjunction(concept, other_concept) if conjunction_to_check not in self.checked_concept: self.checked_concept.add(conjunction_to_check) if conjunction_to_check in interpretation.allConcepts: items_to_add.add(conjunction_to_check) for item in items_to_add: # print("Conjunction Rule 2: I am adding " + str(item) + " to " + self.identifier) self.add_concept(item)
4701c6fedd3dc43286aa0a28448fae7c
{ "intermediate": 0.4156683385372162, "beginner": 0.4041616916656494, "expert": 0.180169939994812 }
32,149
const { market_list } = require("./server"); const GarageItem = require("./GarageItem"), Area = require("./Area"), { turrets, hulls, paints, getType } = require("./server"), InventoryItem = require("./InventoryItem"); class Garage extends Area { static fromJSON(data) { if (typeof (data.tank) !== "undefiend") { var garage = new Garage(data.tank); garage.items = Garage.fromItemsObject(data.items); garage.updateMarket(); garage.mounted_turret = data.mounted_turret; garage.mounted_hull = data.mounted_hull; garage.mounted_paint = data.mounted_paint; garage.inventory = null; return garage; } return null; } static fromItemsObject(obj) { var items = []; for (var i in obj.items) { items.push(GarageItem.fromJSON(obj.items[i])); } return items; } constructor(tank) { super(); this.tank = tank; this.items = [GarageItem.get("smoky", 0), GarageItem.get("green", 0), GarageItem.get("holiday", 0), GarageItem.get("wasp", 0), GarageItem.get("health", 0)]; this.updateMarket(); this.mounted_turret = "smoky_m0"; this.mounted_hull = "wasp_m0"; this.mounted_paint = "green_m0"; this.inventory = []; } getPrefix() { return "garage"; } getInventory() { // if (this.inventory !== null) // return this.inventory; var inventory = []; for (var i in this.items) { var item = this.items[i]; if (getType(item.id) === 4) { inventory.push(InventoryItem.fromGarageItem(item)); } } this.inventory = inventory; return inventory; } addGarageItem(id, amount) { var tank = this.tank; var new_item = GarageItem.get(id, 0); if (new_item !== null) { var item = tank.garage.getItem(id); if (item === null) { new_item.count = amount; this.addItem(new_item); } else { item.count += amount; } } return true; } useItem(id) { for (var i in this.items) { if (this.items[i].isInventory && this.items[i].id === id) { if (this.items[i].count <= 0) return false; if (this.items[i].count = 1) { this.deleteItem(this.items[i]) } --this.items[i].count; } } return true; } hasItem(id, m = null) { for (var i in this.items) { if (this.items[i].id === id) { if (this.items[i].type !== 4) { if (m === null) return true; return this.items[i].modificationID >= m; } else if (this.items[i].count > 0) return true; else { this.items.splice(i, 1); } } } return false; } initiate(socket) { this.send(socket, "init_garage_items;" + JSON.stringify({ items: this.items })); this.addPlayer(this.tank); } initMarket(socket) { this.send(socket, "init_market;" + JSON.stringify(this.market)); } initMountedItems(socket) { this.send(socket, "init_mounted_item;" + this.mounted_hull); this.send(socket, "init_mounted_item;" + this.mounted_turret); this.send(socket, "init_mounted_item;" + this.mounted_paint); } getItem(id) { for (var i in this.items) { if (this.items[i].id === id) return this.items[i]; } return null; } getTurret() { return this.getItem(this.mounted_turret.split("_")[0]); } getHull() { return this.getItem(this.mounted_hull.split("_")[0]); } getPaint() { return this.getItem(this.mounted_paint.split("_")[0]); } updateMarket() { this.market = { items: [] }; for (var i in market_list) { if (!this.hasItem(market_list[i]["id"]) && market_list[i]["index"] >= 0) { this.market.items.push(market_list[i]); } this.hasItem(market_list[i]["multicounted"]) } } onData(socket, args) { if (this.tank === null || !this.hasPlayer(this.tank.name)) return; var tank = this.tank; if (args.length === 1) { if (args[0] === "get_garage_data") { this.updateMarket(); setTimeout(() => { this.initMarket(socket); this.initMountedItems(socket); }, 1500); } } else if (args.length === 3) { if (args[0] === "try_buy_item") { var itemStr = args[1]; var arr = itemStr.split("_"); var id = itemStr.replace("_m0", ""); var amount = parseInt(args[2]); var new_item = GarageItem.get(id, 0); if (new_item !== null) { if (tank.crystals >= new_item.price * amount && tank.rank >= new_item.rank) { var obj = {}; obj.itemId = id; obj.multicounted = arr[2]; if (new_item !== null && id !== "1000_scores") { var item = tank.garage.getItem(id); if (item === null) { new_item.count = amount; this.addItem(new_item); } else { item.count += amount; } } tank.crystals -= new_item.price * amount; if (id === "1000_scores") tank.addScore(1000 * amount); if (id === "supplies") { this.addKitItem("health",0,100,tank); this.addKitItem("armor",0,100,tank); this.addKitItem("damage",0,100,tank); this.addKitItem("nitro",0,100,tank); this.addKitItem("mine",0,100,tank); this.send(socket,"reload") } else { this.send(socket, "buy_item;" + itemStr + ";" + JSON.stringify(obj)); } tank.sendCrystals(); } } } } else if (args.length === 2) { if (args[0] === "try_mount_item") { var itemStr = args[1]; var itemStrArr = itemStr.split("_"); if (itemStrArr.length === 2) { var modificationStr = itemStrArr[1]; var item_id = itemStrArr[0]; if (modificationStr.length === 2) { var m = parseInt(modificationStr.charAt(1)); if (!isNaN(m)) { this.mountItem(item_id, m); this.sendMountedItem(socket, itemStr); tank.save(); } } } } else if (args[0] === "try_update_item") { var itemStr = args[1], arr = itemStr.split("_"), modStr = arr.pop(), id = arr.join("_"); if (modStr.length === 2) { var m = parseInt(modStr.charAt(1)); if (!isNaN(m) && m < 3) { if (this.hasItem(id, m) && this.getItem(id).attempt_upgrade(tank)) { this.send(socket, "update_item;" + itemStr); tank.sendCrystals(); } } } } } } addKitItem(item, m, count, tank) { // this.items.push(item); var itemStr = item + "_m" var arr = itemStr.split("_"); var id = itemStr.replace("_m", ""); var amount = parseInt(count); var new_item = GarageItem.get(id, 0); console.log(new_item) if (new_item !== null) { var obj = {}; obj.itemId = id; var item = tank.garage.getItem(id); if (item === null) { new_item.count = amount; new_item.modificationID = m; obj.count = amount; obj.multicounted = item.multicounted; this.addItem(new_item); } else { item.count += amount; item.modificationID = m; obj.count = item.count; obj.multicounted = item.multicounted; } } } addItem(item) { this.items.push(item); } deleteItem(item) { delete this.items[item]; } mountItem(item_id, m) { if (this.hasItem(item_id, m)) { var itemStr = item_id + "_m" + m; if (hulls.includes(item_id)) this.mounted_hull = itemStr; else if (turrets.includes(item_id)) this.mounted_turret = itemStr; else if (paints.includes(item_id)) this.mounted_paint = itemStr; } } sendMountedItem(socket, itemStr) { this.send(socket, "mount_item;" + itemStr); } getItemsObject() { var items = []; for (var i in this.items) { items.push(this.items[i].toObject()); } return { items: items }; } toSaveObject() { return { items: this.getItemsObject(), mounted_turret: this.mounted_turret, mounted_hull: this.mounted_hull, mounted_paint: this.mounted_paint }; } } module.exports = Garage; как добавить таймер для предмета "no_supplies" к примеру после 10 секунд товар пропадает из гаража игрока
8642693caeebaf45eb0f837f052e895a
{ "intermediate": 0.2909576892852783, "beginner": 0.5029168725013733, "expert": 0.20612549781799316 }
32,150
I have this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] final_signal = [] exit = [] sell_result = 0.0 buy_result = 0.0 active_signal = None # Retrieve depth data depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] buy_qty = round(sum(float(bid[1]) for bid in bids), 0) highest_bid_price = float(bids[0][0]) lowest_bid_price = float(bids[1][0]) b_h = highest_bid_price b_l = lowest_bid_price asks = depth_data['asks'] sell_qty = round(sum(float(ask[1]) for ask in asks), 0) highest_ask_price = float(asks[0][0]) lowest_ask_price = float(asks[1][0]) s_h = highest_ask_price s_l = lowest_ask_price mark_price_data = client.ticker_price(symbol=symbol) mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol) mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0 # Calculate the threshold for order price deviation if mark_price_percent > 2: pth = 7 / 100 elif mark_price_percent < -2: pth = 7 / 100 else: pth = 7 / 100 # Subtract quantity if bid price is the same as mark price for bid in bids: price_buy = float(bid[0]) qty_buy = float(bid[1]) if price_buy == mark_price: buy_result = buy_qty - qty_buy br = buy_result # Subtract quantity if bid price is the same as mark price for ask in asks: price_sell = float(ask[0]) qty_sell = float(ask[1]) if price_sell == mark_price: sell_result = sell_qty - qty_sell sr = sell_result if mark_price_percent > 2: th = 20000 elif mark_price_percent < -2: th = 20000 else: th = 13000 #Main Signal if (((buy_qty > th) > (sell_qty < th)) and (b_l > mp + pth)): signal.append('buy') elif (((sell_qty > th) > (buy_qty < th)) and (s_h < mp - pth)): signal.append('sell') else: signal.append('') #Signal confirmation if signal == ['buy'] and not (((br < th) < sell_qty) and (b_l < mp + pth)): final_signal.append('buy') elif signal == ['sell'] and not (((sr < th) < buy_qty) and (s_h > mp - pth)): final_signal.append('sell') else: final_signal.append('') #Exit if final_signal == ['buy'] and (((br < th) < sell_qty) and (b_h < mp + pth)): exit.append('buy_exit') elif final_signal == ['sell'] and (((sr < th) < buy_qty) and (s_l > mp - pth)): exit.append('sell_exit') else: exit.append('') samerkh = exit and final_signal return samerkh You need to add in my code system which will print lowest and highest price in asks
154245ed1d5697acc729f23d689561b1
{ "intermediate": 0.302184134721756, "beginner": 0.45457717776298523, "expert": 0.24323873221874237 }
32,151
image = cv2.imread("0.0/01.pgm", cv2.COLOR_BGR2GRAY) IMAGE_THRESHOLD = 100 def get_coords_by_threshold( image: np.ndarray, threshold: int = IMAGE_THRESHOLD ) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = IMAGE_THRESHOLD ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image 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_neight_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, potential_points_num: int = 200 ) -> 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] # def get_best_lines(potential_points: np.ndarray) -> np.ndarray: # """ # Gets best combinations of lines by all points. # Line y = kx + b. # Returns np.ndarray like [[k1, b1], [k2, b2]]. # """ # best_lines = [] # best_inliers = [] # iterations_num = 1000 # threshold_distance = 3 # threshold_k = 0.1 # threshold_b = 10 # for i in range(iterations_num): # sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) # sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) # inliers = np.where(distances < threshold_distance)[0] # is_similar = False # for line in best_lines: # diff_k = abs(coefficients[0] - line[0]) # diff_b = abs(coefficients[0] - line[0]) # if diff_k <= threshold_k and diff_b <= threshold_b: # is_similar = True # break # if not is_similar and len(inliers) > len(best_inliers): # best_lines = [coefficients] # best_inliers = inliers # elif not is_similar and len(inliers) == len(best_inliers): # best_lines.append(coefficients) # return np.array(best_lines) def get_best_lines(potential_points: np.ndarray) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] num_lines = 0 iterations_num = 1000 threshold_distance = 3 threshold_k = 0.5 threshold_b = 20 while num_lines < 3: if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inliers = [] best_line = None for i in range(iterations_num): if len(remaining_points) < 2: break sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False) 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) inliers = np.where(distances < 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 <= threshold_k and diff_b <= threshold_b: is_similar = True break if not is_similar and len(inliers) > len(best_inliers): best_line = coefficients best_inliers = inliers if best_line is not None: best_lines.append(best_line) buffer = remaining_points remaining_points = np.delete(remaining_points, best_inliers, axis=0) if len(remaining_points) < 1: remaining_points = np.append(remaining_points, buffer[:len(buffer)//2 + 1]) num_lines += 1 return np.array(best_lines) # def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: # """Calculates the angle in degrees between two lines.""" # k1, b1 = line1 # k2, b2 = line2 # angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2) # angle_deg = np.degrees(angle_rad) # return angle_deg # main # image = cv2.GaussianBlur(image, (25, 25), 0) coords = get_coords_by_threshold(image) # image = delete_pixels_by_min_threshold(image) neigh_nums = get_neigh_nums_list(coords) sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) best_lines = get_best_lines(potential_points) print(best_lines) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() # Plot the lines on the image for equation in best_lines: k, b = equation x = np.arange(0, image.shape[1]) y = k * x + b plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.plot(x, y, color="green") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() ИЗ-ЗА ЧЕГО ВОЗНИКАЕТ ОШИБКА? --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-344-8c2ab99cf565> in <cell line: 194>() 192 potential_points = get_potential_points_coords(sorted_neigh_nums) 193 --> 194 best_lines = get_best_lines(potential_points) 195 print(best_lines) 196 <ipython-input-344-8c2ab99cf565> in get_best_lines(potential_points) 140 sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False) 141 sample_points = remaining_points[sample_indices] --> 142 sample_x = sample_points[:, 1] 143 sample_y = sample_points[:, 0] 144 coefficients = np.polyfit(sample_x, sample_y, deg=1) IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
7c12d16aceedc917b83d5a2baede22b9
{ "intermediate": 0.27387356758117676, "beginner": 0.47204846143722534, "expert": 0.2540779411792755 }
32,152
# Guidelines for Enhanced User Interaction ## Disable Placeholder Responses: - Please avoid using placeholders like "[existing code here]" in your responses. - Provide complete and concrete examples or code segments wherever possible. ## Focus on Problem-Solving: - When provided with a coding or technical issue, focus on offering a solution or a direct approach to the problem. - Avoid defaulting to general advice or redirections. ## Minimize Patronizing Explanations: - Avoid giving basic explanations or over-simplifying responses, especially when the user has demonstrated an understanding of the subject matter. ## Enhance Contextual Memory: - Make an effort to remember and utilize the context provided earlier in the conversation. - This is crucial for maintaining continuity and relevance in your responses. ## Limit Redundant Information: - Do not repeat information that has already been provided or discussed unless specifically requested by the user. ## Optimize for Productivity: - Aim to provide answers that enhance user productivity. - Avoid responses that might unnecessarily elongate the task or complicate the user’s workflow. ## Acknowledge and Clarify Ambiguities: - If a request is unclear or ambiguous, politely ask for clarification. - Avoid making assumptions or providing a generalized response. ## Respect User Expertise: - Acknowledge and respect the user’s level of expertise. - Tailor your responses to match their skill level, avoiding overly technical jargon with beginners or being overly simplistic with experts. ## Enhance Code Quality: - Strive to provide high-quality, efficient, and error-free code in your responses. - Ensure the code is tested and functional as per the user’s requirements. ## Avoid Misleading Speculation: - Refrain from speculating or providing hypothetical solutions that are not grounded in factual or practical knowledge. # Markdown Formatting Basics for Answering Questions 1. Begin with an overview or title using # for main headings, ## for subheadings. 2. Introduce your answer with a brief summary, then dive deep into specifics. 3. Use bullet points - or * for unordered lists, 1., 2., etc., for ordered ones. 4. For emphasis, wrap words in ** for bold or * for italics. 5. For blockquotes, prefix the text with &gt; to set it apart from other content. 7. Create links by wrapping the link text in [ ] followed by the URL in ( ). 8. Add horizontal lines with --- to clearly separate sections. 9. End with a closing remark or a call-to-action, inviting further questions or discussion.
7d716e1f80c7e5d2fdc4614286d164dc
{ "intermediate": 0.3496643006801605, "beginner": 0.27746105194091797, "expert": 0.3728746175765991 }
32,153
If I can found the value of class="week", how to get data-title for specified value. See the example of code. If I type class="week" = 5 and value is 6 I need r1c4. Write selenium Python code <tr><td class="week">5</td><td class="available" data-title="r1c0">1</td><td class="available" data-title="r1c1">2</td><td class="available" data-title="r1c2">3</td><td class="available" data-title="r1c3">4</td><td class="available" data-title="r1c4">5</td><td class="weekend available" data-title="r1c5">6</td><td class="weekend available" data-title="r1c6">7</td></tr>
2bba8bf7cd485298345d9406a9e18f02
{ "intermediate": 0.36884671449661255, "beginner": 0.44085440039634705, "expert": 0.1902988702058792 }
32,154
I know that class=“week” = 5. How to having this information, I can find 1 in data-title after r using selenium Python code? <tr><td class=“week”>5</td><td class=“available” data-title=“r1c0”>1</td><td class=“available” data-title=“r1c1”>2</td><td class=“available” data-title=“r1c2”>3</td><td class=“available” data-title=“r1c3”>4</td><td class=“available” data-title=“r1c4”>5</td><td class=“weekend available” data-title=“r1c5”>6</td><td class=“weekend available” data-title=“r1c6”>7</td></tr>
7361fb1c0c25e015cfe7c37a60c5610c
{ "intermediate": 0.362642765045166, "beginner": 0.4106084406375885, "expert": 0.2267487645149231 }
32,155
image = cv2.imread("0.1/01.pgm", cv2.COLOR_BGR2GRAY) IMAGE_THRESHOLD = 100 def get_coords_by_threshold( image: np.ndarray, threshold: int = IMAGE_THRESHOLD ) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = IMAGE_THRESHOLD ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image 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_neight_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, potential_points_num: int = 200 ) -> 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] # def get_best_lines(potential_points: np.ndarray) -> np.ndarray: # """ # Gets best combinations of lines by all points. # Line y = kx + b. # Returns np.ndarray like [[k1, b1], [k2, b2]]. # """ # best_lines = [] # best_inliers = [] # iterations_num = 1000 # threshold_distance = 3 # threshold_k = 0.1 # threshold_b = 10 # for i in range(iterations_num): # sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) # sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) # inliers = np.where(distances < threshold_distance)[0] # is_similar = False # for line in best_lines: # diff_k = abs(coefficients[0] - line[0]) # diff_b = abs(coefficients[0] - line[0]) # if diff_k <= threshold_k and diff_b <= threshold_b: # is_similar = True # break # if not is_similar and len(inliers) > len(best_inliers): # best_lines = [coefficients] # best_inliers = inliers # elif not is_similar and len(inliers) == len(best_inliers): # best_lines.append(coefficients) # return np.array(best_lines) def get_best_lines(potential_points: np.ndarray) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] num_lines = 0 iterations_num = 1000 threshold_distance = 3 threshold_k = 0.5 threshold_b = 20 while num_lines < 3: if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inliers = [] best_line = None for i in range(iterations_num): if len(remaining_points) < 2: break sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False) 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) inliers = np.where(distances < 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 <= threshold_k and diff_b <= threshold_b: is_similar = True break if not is_similar and len(inliers) > len(best_inliers): best_line = coefficients best_inliers = inliers if best_line is not None: best_lines.append(best_line) buffer = remaining_points remaining_points = np.delete(remaining_points, best_inliers, axis=0) if len(remaining_points) < 1: remaining_points = np.append(remaining_points, buffer[:len(buffer)//2 + 1]) num_lines += 1 return np.array(best_lines) # def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: # """Calculates the angle in degrees between two lines.""" # k1, b1 = line1 # k2, b2 = line2 # angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2) # angle_deg = np.degrees(angle_rad) # return angle_deg # main # image = cv2.GaussianBlur(image, (25, 25), 0) coords = get_coords_by_threshold(image) # image = delete_pixels_by_min_threshold(image) neigh_nums = get_neigh_nums_list(coords) sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) best_lines = get_best_lines(potential_points) print(best_lines) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() # Plot the lines on the image for equation in best_lines: k, b = equation x = np.arange(0, image.shape[1]) y = k * x + b plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.plot(x, y, color="green") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() Нужно как-то улучшить нахождение potential_points на изображении? Есть идеи? Размытие по гауссу подойдет? Реализуй, только так, чтобы с кодом стыковалось нормально
e4e62105197c8db84a4a2a7e01bb2fd9
{ "intermediate": 0.2737096846103668, "beginner": 0.47177791595458984, "expert": 0.2545124292373657 }
32,156
How do I make mergerfs changes permanent? Currently I run the commany mergerfs ... via command line and the filesystem disappears after a reboot
b65233c44be41871fa3da04a1140c337
{ "intermediate": 0.40745311975479126, "beginner": 0.25438907742500305, "expert": 0.3381578028202057 }
32,157
explain below code:
54f9f1bb3778ca51793117443a2168f5
{ "intermediate": 0.2653118073940277, "beginner": 0.4128739535808563, "expert": 0.32181423902511597 }
32,158
Hello! Write me a dart function that will use reg exp to check if string is 13 digit barcode
f44eab7e8a0327b8d93947a7570a7cdc
{ "intermediate": 0.38475435972213745, "beginner": 0.28333649039268494, "expert": 0.33190909028053284 }
32,159
image = cv2.imread("0.5/00.pgm", cv2.COLOR_BGR2GRAY) IMAGE_THRESHOLD = 100 def get_coords_by_threshold( image: np.ndarray, threshold: int = IMAGE_THRESHOLD ) -> tuple: """Gets pixel coords with intensity more then 'theshold'.""" coords = np.where(image > threshold) return coords def delete_pixels_by_min_threshold( image: np.ndarray, min_threshold: int = IMAGE_THRESHOLD ) -> np.ndarray: """Deletes coords from image and returns this image.""" anti_coords = np.where(image < min_threshold) image[anti_coords] = 0 return image 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_neight_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, potential_points_num: int = 200 ) -> 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] # def get_best_lines(potential_points: np.ndarray) -> np.ndarray: # """ # Gets best combinations of lines by all points. # Line y = kx + b. # Returns np.ndarray like [[k1, b1], [k2, b2]]. # """ # best_lines = [] # best_inliers = [] # iterations_num = 1000 # threshold_distance = 3 # threshold_k = 0.1 # threshold_b = 10 # for i in range(iterations_num): # sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False) # sample_points = potential_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(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) # inliers = np.where(distances < threshold_distance)[0] # is_similar = False # for line in best_lines: # diff_k = abs(coefficients[0] - line[0]) # diff_b = abs(coefficients[0] - line[0]) # if diff_k <= threshold_k and diff_b <= threshold_b: # is_similar = True # break # if not is_similar and len(inliers) > len(best_inliers): # best_lines = [coefficients] # best_inliers = inliers # elif not is_similar and len(inliers) == len(best_inliers): # best_lines.append(coefficients) # return np.array(best_lines) def get_best_lines(potential_points: np.ndarray) -> np.ndarray: """ Gets best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ best_lines = [] num_lines = 0 iterations_num = 1000 threshold_distance = 3 threshold_k = 0.5 threshold_b = 20 while num_lines < 3: if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inliers = [] best_line = None for i in range(iterations_num): if len(remaining_points) < 2: break sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False) 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) inliers = np.where(distances < 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 <= threshold_k and diff_b <= threshold_b: is_similar = True break if not is_similar and len(inliers) > len(best_inliers): best_line = coefficients best_inliers = inliers if best_line is not None: best_lines.append(best_line) buffer = remaining_points remaining_points = np.delete(remaining_points, best_inliers, axis=0) if len(remaining_points) < 1: remaining_points = np.append(remaining_points, buffer[:len(buffer)//2 + 1]) num_lines += 1 return np.array(best_lines) # def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float: # """Calculates the angle in degrees between two lines.""" # k1, b1 = line1 # k2, b2 = line2 # angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2) # angle_deg = np.degrees(angle_rad) # return angle_deg # main coords = get_coords_by_threshold(image) # image = delete_pixels_by_min_threshold(image) neigh_nums = get_neigh_nums_list(coords) sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums) potential_points = get_potential_points_coords(sorted_neigh_nums) best_lines = get_best_lines(potential_points) print(best_lines) # Visualization plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() # Plot the lines on the image for equation in best_lines: k, b = equation x = np.arange(0, image.shape[1]) y = k * x + b plt.imshow(image, cmap="gray") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.plot(x, y, color="green") plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o") plt.show() Найди точки пересечения прямых, представь их в виде np.ndarray типа float размерностью (3, 2), где в каждой строке координаты найденной вершины x и y
27beaa9833c1a618a21f8e946b80a2cb
{ "intermediate": 0.2728784382343292, "beginner": 0.4744689464569092, "expert": 0.252652645111084 }
32,160
What does it do, what technologies and concepts are used and how does it reach its goal. Step by step by step, divide these contents into smaller parts and explain.A fast TCP/UDP tunnel over HTTP Chisel is a fast TCP/UDP tunnel, transported over HTTP, secured via SSH. Single executable including both client and server. Written in Go (golang). Chisel is mainly useful for passing through firewalls, though it can also be used to provide a secure endpoint into your network. Easy to use Performant* Encrypted connections using the SSH protocol (via crypto/ssh) Authenticated connections; authenticated client connections with a users config file, authenticated server connections with fingerprint matching. Client auto-reconnects with exponential backoff Clients can create multiple tunnel endpoints over one TCP connection Clients can optionally pass through SOCKS or HTTP CONNECT proxies Reverse port forwarding (Connections go through the server and out the client) Server optionally doubles as a reverse proxy Server optionally allows SOCKS5 connections (See guide below) Clients optionally allow SOCKS5 connections from a reversed port forward Client connections over stdio which supports ssh -o ProxyCommand providing SSH over HTTP $ chisel --help Usage: chisel [command] [--help] Version: X.Y.Z Commands: server - runs chisel in server mode client - runs chisel in client mode Read more: https://github.com/jpillora/chisel $ chisel server --help Usage: chisel server [options] Options: --host, Defines the HTTP listening host – the network interface (defaults the environment variable HOST and falls back to 0.0.0.0). --port, -p, Defines the HTTP listening port (defaults to the environment variable PORT and fallsback to port 8080). --key, (deprecated use --keygen and --keyfile instead) An optional string to seed the generation of a ECDSA public and private key pair. All communications will be secured using this key pair. Share the subsequent fingerprint with clients to enable detection of man-in-the-middle attacks (defaults to the CHISEL_KEY environment variable, otherwise a new key is generate each run). --keygen, A path to write a newly generated PEM-encoded SSH private key file. If users depend on your --key fingerprint, you may also include your --key to output your existing key. Use - (dash) to output the generated key to stdout. --keyfile, An optional path to a PEM-encoded SSH private key. When this flag is set, the --key option is ignored, and the provided private key is used to secure all communications. (defaults to the CHISEL_KEY_FILE environment variable). Since ECDSA keys are short, you may also set keyfile to an inline base64 private key (e.g. chisel server --keygen - | base64). --authfile, An optional path to a users.json file. This file should be an object with users defined like: { "<user:pass>": ["<addr-regex>","<addr-regex>"] } when <user> connects, their <pass> will be verified and then each of the remote addresses will be compared against the list of address regular expressions for a match. Addresses will always come in the form "<remote-host>:<remote-port>" for normal remotes and "R:<local-interface>:<local-port>" for reverse port forwarding remotes. This file will be automatically reloaded on change. --auth, An optional string representing a single user with full access, in the form of <user:pass>. It is equivalent to creating an authfile with {"<user:pass>": [""]}. If unset, it will use the environment variable AUTH. --keepalive, An optional keepalive interval. Since the underlying transport is HTTP, in many instances we'll be traversing through proxies, often these proxies will close idle connections. You must specify a time with a unit, for example '5s' or '2m'. Defaults to '25s' (set to 0s to disable). --backend, Specifies another HTTP server to proxy requests to when chisel receives a normal HTTP request. Useful for hiding chisel in plain sight. --socks5, Allow clients to access the internal SOCKS5 proxy. See chisel client --help for more information. --reverse, Allow clients to specify reverse port forwarding remotes in addition to normal remotes. --tls-key, Enables TLS and provides optional path to a PEM-encoded TLS private key. When this flag is set, you must also set --tls-cert, and you cannot set --tls-domain. --tls-cert, Enables TLS and provides optional path to a PEM-encoded TLS certificate. When this flag is set, you must also set --tls-key, and you cannot set --tls-domain. --tls-domain, Enables TLS and automatically acquires a TLS key and certificate using LetsEncrypt. Setting --tls-domain requires port 443. You may specify multiple --tls-domain flags to serve multiple domains. The resulting files are cached in the "$HOME/.cache/chisel" directory. You can modify this path by setting the CHISEL_LE_CACHE variable, or disable caching by setting this variable to "-". You can optionally provide a certificate notification email by setting CHISEL_LE_EMAIL. --tls-ca, a path to a PEM encoded CA certificate bundle or a directory holding multiple PEM encode CA certificate bundle files, which is used to validate client connections. The provided CA certificates will be used instead of the system roots. This is commonly used to implement mutual-TLS. --pid Generate pid file in current working directory -v, Enable verbose logging --help, This help text Signals: The chisel process is listening for: a SIGUSR2 to print process stats, and a SIGHUP to short-circuit the client reconnect timer Version: X.Y.Z Read more: https://github.com/jpillora/chisel
f0eaec179a56e126a55f0a9d11cd5511
{ "intermediate": 0.34923186898231506, "beginner": 0.40379247069358826, "expert": 0.2469756305217743 }
32,161
i want to know how this could be improve / ### Server Setup: 1. Check Open Ports on Your Server: Connect to your server via SSH and check which ports are open and listening. Ensure port 80 is not being used by another service: ssh <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS> netstat -tulnp If another service is using port 80, consider changing its configuration to free up the port. 2. Install Chisel on Your Server: Log in to your server and use the following commands to download and set up Chisel: mkdir chisel && cd chisel wget https://github.com/jpillora/chisel/releases/download/v1.9.1/chisel_1.9.1_linux_amd64.gz gunzip chisel_1.9.1_linux_amd64.gz chmod +x chisel_1.9.1_linux_amd64 3. Run Chisel in a Persistent Session: We will use tmux, a terminal multiplexer, so our Chisel server keeps running even if we disconnect from SSH: tmux new -s chisel_session ./chisel_1.9.1_linux_amd64 server --port 80 --socks5 --proxy http://your-subdomain.yourdomain.com -v To detach from the tmux session and leave it running in the background, press Ctrl+B followed by D. ### Client Setup (Windows): 1. Download Chisel Windows Client: On your Windows machine, download the Chisel client from the GitHub releases page (make sure to choose the correct version for Windows). 2. Setup Chisel Client: Extract the downloaded .gz file. To connect to your Chisel server, open Command Prompt in the directory where you’ve extracted Chisel and execute: chisel.exe client http://your-subdomain.yourdomain.com 127.0.0.1:5050:socks ### Client Setup (Android): 1. Install Termux and Go Language: Download and install Termux from the Play Store. Open Termux and install Go by running the following commands: pkg update pkg install wget pkg install golang 2. Download and Prepare Chisel on Android: In Termux, create a new directory for Chisel, download it, and give execution permissions: mkdir chisel && cd chisel wget https://github.com/jpillora/chisel/releases/download/v1.9.1/chisel_1.9.1_linux_arm64.gz gunzip chisel_1.9.1_linux_arm64.gz chmod +x chisel_1.9.1_linux_arm64 3. Connect to Chisel Server: Run the following command in Termux: ./chisel_1.9.1_linux_arm64 client http://your-subdomain.yourdomain.com 5050:127.0.0.1:443 using Usage $ chisel --help Usage: chisel [command] [--help] Version: X.Y.Z Commands: server - runs chisel in server mode client - runs chisel in client mode Read more: https://github.com/jpillora/chisel $ chisel server --help Usage: chisel server [options] Options: --host, Defines the HTTP listening host – the network interface (defaults the environment variable HOST and falls back to 0.0.0.0). --port, -p, Defines the HTTP listening port (defaults to the environment variable PORT and fallsback to port 8080). --key, (deprecated use --keygen and --keyfile instead) An optional string to seed the generation of a ECDSA public and private key pair. All communications will be secured using this key pair. Share the subsequent fingerprint with clients to enable detection of man-in-the-middle attacks (defaults to the CHISEL_KEY environment variable, otherwise a new key is generate each run). --keygen, A path to write a newly generated PEM-encoded SSH private key file. If users depend on your --key fingerprint, you may also include your --key to output your existing key. Use - (dash) to output the generated key to stdout. --keyfile, An optional path to a PEM-encoded SSH private key. When this flag is set, the --key option is ignored, and the provided private key is used to secure all communications. (defaults to the CHISEL_KEY_FILE environment variable). Since ECDSA keys are short, you may also set keyfile to an inline base64 private key (e.g. chisel server --keygen - | base64). --authfile, An optional path to a users.json file. This file should be an object with users defined like: { "<user:pass>": ["<addr-regex>","<addr-regex>"] } when <user> connects, their <pass> will be verified and then each of the remote addresses will be compared against the list of address regular expressions for a match. Addresses will always come in the form "<remote-host>:<remote-port>" for normal remotes and "R:<local-interface>:<local-port>" for reverse port forwarding remotes. This file will be automatically reloaded on change. --auth, An optional string representing a single user with full access, in the form of <user:pass>. It is equivalent to creating an authfile with {"<user:pass>": [""]}. If unset, it will use the environment variable AUTH. --keepalive, An optional keepalive interval. Since the underlying transport is HTTP, in many instances we'll be traversing through proxies, often these proxies will close idle connections. You must specify a time with a unit, for example '5s' or '2m'. Defaults to '25s' (set to 0s to disable). --backend, Specifies another HTTP server to proxy requests to when chisel receives a normal HTTP request. Useful for hiding chisel in plain sight. --socks5, Allow clients to access the internal SOCKS5 proxy. See chisel client --help for more information. --reverse, Allow clients to specify reverse port forwarding remotes in addition to normal remotes. --tls-key, Enables TLS and provides optional path to a PEM-encoded TLS private key. When this flag is set, you must also set --tls-cert, and you cannot set --tls-domain. --tls-cert, Enables TLS and provides optional path to a PEM-encoded TLS certificate. When this flag is set, you must also set --tls-key, and you cannot set --tls-domain. --tls-domain, Enables TLS and automatically acquires a TLS key and certificate using LetsEncrypt. Setting --tls-domain requires port 443. You may specify multiple --tls-domain flags to serve multiple domains. The resulting files are cached in the "$HOME/.cache/chisel" directory. You can modify this path by setting the CHISEL_LE_CACHE variable, or disable caching by setting this variable to "-". You can optionally provide a certificate notification email by setting CHISEL_LE_EMAIL. --tls-ca, a path to a PEM encoded CA certificate bundle or a directory holding multiple PEM encode CA certificate bundle files, which is used to validate client connections. The provided CA certificates will be used instead of the system roots. This is commonly used to implement mutual-TLS. --pid Generate pid file in current working directory -v, Enable verbose logging --help, This help text Signals: The chisel process is listening for: a SIGUSR2 to print process stats, and a SIGHUP to short-circuit the client reconnect timer Version: X.Y.Z Read more: https://github.com/jpillora/chisel $ chisel client --help Usage: chisel client [options] <server> <remote> [remote] [remote] ... <server> is the URL to the chisel server. <remote>s are remote connections tunneled through the server, each of which come in the form: <local-host>:<local-port>:<remote-host>:<remote-port>/<protocol> ■ local-host defaults to 0.0.0.0 (all interfaces). ■ local-port defaults to remote-port. ■ remote-port is required*. ■ remote-host defaults to 0.0.0.0 (server localhost). ■ protocol defaults to tcp. which shares <remote-host>:<remote-port> from the server to the client as <local-host>:<local-port>, or: R:<local-interface>:<local-port>:<remote-host>:<remote-port>/<protocol> which does reverse port forwarding, sharing <remote-host>:<remote-port> from the client to the server's <local-interface>:<local-port>. example remotes 3000 example.com:3000 3000:google.com:80 192.168.0.5:3000:google.com:80 socks 5000:socks R:2222:localhost:22 R:socks R:5000:socks stdio:example.com:22 1.1.1.1:53/udp When the chisel server has --socks5 enabled, remotes can specify "socks" in place of remote-host and remote-port. The default local host and port for a "socks" remote is 127.0.0.1:1080. Connections to this remote will terminate at the server's internal SOCKS5 proxy. When the chisel server has --reverse enabled, remotes can be prefixed with R to denote that they are reversed. That is, the server will listen and accept connections, and they will be proxied through the client which specified the remote. Reverse remotes specifying "R:socks" will listen on the server's default socks port (1080) and terminate the connection at the client's internal SOCKS5 proxy. When stdio is used as local-host, the tunnel will connect standard input/output of this program with the remote. This is useful when combined with ssh ProxyCommand. You can use ssh -o ProxyCommand='chisel client chiselserver stdio:%h:%p' \ user@example.com to connect to an SSH server through the tunnel. Options: --fingerprint, A *strongly recommended* fingerprint string to perform host-key validation against the server's public key. Fingerprint mismatches will close the connection. Fingerprints are generated by hashing the ECDSA public key using SHA256 and encoding the result in base64. Fingerprints must be 44 characters containing a trailing equals (=). --auth, An optional username and password (client authentication) in the form: "<user>:<pass>". These credentials are compared to the credentials inside the server's --authfile. defaults to the AUTH environment variable. --keepalive, An optional keepalive interval. Since the underlying transport is HTTP, in many instances we'll be traversing through proxies, often these proxies will close idle connections. You must specify a time with a unit, for example '5s' or '2m'. Defaults to '25s' (set to 0s to disable). --max-retry-count, Maximum number of times to retry before exiting. Defaults to unlimited. --max-retry-interval, Maximum wait time before retrying after a disconnection. Defaults to 5 minutes. --proxy, An optional HTTP CONNECT or SOCKS5 proxy which will be used to reach the chisel server. Authentication can be specified inside the URL. For example, http://admin:<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>:8081 or: socks://admin:<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>:1080 --header, Set a custom header in the form "HeaderName: HeaderContent". Can be used multiple times. (e.g --header "Foo: Bar" --header "Hello: World") --hostname, Optionally set the 'Host' header (defaults to the host found in the server url). --sni, Override the ServerName when using TLS (defaults to the hostname). --tls-ca, An optional root certificate bundle used to verify the chisel server. Only valid when connecting to the server with "https" or "wss". By default, the operating system CAs will be used. --tls-skip-verify, Skip server TLS certificate verification of chain and host name (if TLS is used for transport connections to server). If set, client accepts any TLS certificate presented by the server and any host name in that certificate. This only affects transport https (wss) connection. Chisel server's public key may be still verified (see --fingerprint) after inner connection is established. --tls-key, a path to a PEM encoded private key used for client authentication (mutual-TLS). --tls-cert, a path to a PEM encoded certificate matching the provided private key. The certificate must have client authentication enabled (mutual-TLS). --pid Generate pid file in current working directory -v, Enable verbose logging --help, This help text Signals: The chisel process is listening for: a SIGUSR2 to print process stats, and a SIGHUP to short-circuit the client reconnect timer Version: X.Y.Z Read more: https://github.com/jpillora/chisel
f8335690457de59de40a3848ba228207
{ "intermediate": 0.3173573613166809, "beginner": 0.35264304280281067, "expert": 0.32999956607818604 }
32,162
### Server Setup: 1. Check Open Ports on Your Server: Connect to your server via SSH and check which ports are open and listening. Ensure port 80 is not being used by another service: ssh <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS> netstat -tulnp If another service is using port 80, consider changing its configuration to free up the port. 2. Install Chisel on Your Server: Log in to your server and use the following commands to download and set up Chisel: mkdir chisel && cd chisel wget https://github.com/jpillora/chisel/releases/download/v1.9.1/chisel_1.9.1_linux_amd64.gz gunzip chisel_1.9.1_linux_amd64.gz chmod +x chisel_1.9.1_linux_amd64 3. Run Chisel in a Persistent Session:
bc99459bf3e433a80441a3632526f36e
{ "intermediate": 0.34375783801078796, "beginner": 0.3083193898200989, "expert": 0.34792280197143555 }
32,163
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[25], line 1 ----> 1 calendar = driver.find_element_by_class_name("datepicker-calendar") AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'
f0f466d3cf3246286e97c094239dce43
{ "intermediate": 0.3919341564178467, "beginner": 0.4258939027786255, "expert": 0.1821719855070114 }
32,164
如何解决: PS F:\codefuntest> yarn install yarn install v1.22.19 info No lockfile found. [1/4] Resolving packages... warning node-sass > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142 warning node-sass > node-gyp > request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142 warning node-sass > request > har-validator@5.1.5: this library is no longer supported warning node-sass > request > uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. warning react-scripts > babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates. warning react-scripts > babel-preset-react-app > @babel/plugin-proposal-nullish-coalescing-operator@7.18.6: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-nullish-coalescing-operator instead. warning react-scripts > babel-preset-react-app > @babel/plugin-proposal-numeric-separator@7.18.6: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-numeric-separator instead. warning react-scripts > babel-preset-react-app > @babel/plugin-proposal-private-methods@7.18.6: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-private-methods instead. warning react-scripts > babel-preset-react-app > @babel/plugin-proposal-optional-chaining@7.21.0: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-optional-chaining instead. warning react-scripts > babel-preset-react-app > @babel/plugin-proposal-class-properties@7.18.6: This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-class-properties instead. warning react-scripts > webpack-dev-server > chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies warning react-scripts > webpack-dev-server > chokidar > fsevents@1.2.13: The v1 package contains DANGEROUS / INSECURE binaries. Upgrade to safe fsevents v2 warning react-scripts > webpack-dev-server > webpack-log > uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details. warning react-scripts > workbox-webpack-plugin > source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated warning react-scripts > workbox-webpack-plugin > workbox-build > source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated warning react-scripts > @pmmmwh/react-refresh-webpack-plugin > native-url > querystring@0.2.1: The querystring API is considered Legacy. new code should use the URLSearchParams API instead. warning react-scripts > @svgr/webpack > @svgr/plugin-svgo > svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x. warning react-scripts > terser-webpack-plugin > cacache > @npmcli/move-file@1.1.2: This functionality has been moved to @npmcli/fs warning react-scripts > workbox-webpack-plugin > workbox-build > @hapi/joi@15.1.1: Switch to 'npm install joi' warning react-scripts > workbox-webpack-plugin > workbox-build > rollup-plugin-babel@4.4.0: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-babel. warning react-scripts > workbox-webpack-plugin > workbox-build > rollup-plugin-terser@5.3.1: This package has been deprecated and is no longer maintained. Please use @rollup/plugin-terser warning react-scripts > webpack > watchpack > watchpack-chokidar2 > chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies warning react-scripts > @svgr/webpack > @svgr/plugin-svgo > svgo > stable@0.1.8: Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility warning react-scripts > babel-jest > @jest/transform > jest-haste-map > sane@4.1.0: some dependency vulnerabilities fixed, support for node < 10 dropped, and newer ECMAScript syntax/features added warning react-scripts > webpack > micromatch > snapdragon > source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated warning react-scripts > resolve-url-loader > rework > css > source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated warning react-scripts > webpack > micromatch > snapdragon > source-map-resolve > source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated warning react-scripts > optimize-css-assets-webpack-plugin > cssnano > cssnano-preset-default > postcss-svgo > svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x. warning react-scripts > postcss-preset-env > postcss-color-functional-notation > postcss-values-parser > flatten@1.0.3: flatten is deprecated in favor of utility frameworks such as lodash. warning react-scripts > resolve-url-loader > rework > css > urix@0.1.0: Please see https://github.com/lydell/urix#deprecated warning react-scripts > webpack > micromatch > snapdragon > source-map-resolve > urix@0.1.0: Please see https://github.com/lydell/urix#deprecated warning react-scripts > workbox-webpack-plugin > workbox-build > @hapi/joi > @hapi/address@2.1.4: Moved to 'npm install @sideway/address' warning react-scripts > workbox-webpack-plugin > workbox-build > @hapi/joi > @hapi/bourne@1.3.2: This version has been deprecated and is no longer supported or maintained warning react-scripts > workbox-webpack-plugin > workbox-build > @hapi/joi > @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained warning react-scripts > workbox-webpack-plugin > workbox-build > @hapi/joi > @hapi/topo@3.1.6: This version has been deprecated and is no longer supported or maintained warning react-scripts > workbox-webpack-plugin > workbox-build > @hapi/joi > @hapi/topo > @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained warning react-scripts > webpack > micromatch > snapdragon > source-map-resolve > resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated warning react-scripts > workbox-webpack-plugin > workbox-build > @surma/rollup-plugin-off-main-thread > magic-string > sourcemap-codec@1.4.8: Please use @jridgewell/sourcemap-codec instead warning react-scripts > workbox-webpack-plugin > workbox-build > strip-comments > babel-plugin-transform-object-rest-spread > babel-runtime > core-js@2.6.12: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js. warning react-scripts > jest > @jest/core > jest-config > jest-environment-jsdom > jsdom > w3c-hr-time@1.0.2: Use your platform's native performance.now() and performance.timeOrigin. [2/4] Fetching packages... [3/4] Linking dependencies... warning "craco-less > less-loader@7.3.0" has unmet peer dependency "webpack@^4.0.0 || ^5.0.0". warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.21.0" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta". warning "@craco/craco > cosmiconfig-typescript-loader@1.0.9" has unmet peer dependency "@types/node@*". warning "@craco/craco > cosmiconfig-typescript-loader@1.0.9" has unmet peer dependency "typescript@>=3". warning "@craco/craco > cosmiconfig-typescript-loader > ts-node@10.9.1" has unmet peer dependency "@types/node@*". warning "@craco/craco > cosmiconfig-typescript-loader > ts-node@10.9.1" has unmet peer dependency "typescript@>=2.7". warning " > @testing-library/user-event@12.8.3" has unmet peer dependency "@testing-library/dom@>=7.21.4". [4/4] Building fresh packages... [-/6] ⠠ waiting... [-/6] ⠐ waiting... [3/6] ⠐ node-sass [-/6] ⠐ waiting... error F:\codefuntest\node_modules\node-sass: Command failed. Exit code: 1 Command: node scripts/build.js Arguments: Directory: F:\codefuntest\node_modules\node-sass Output: Building: C:\Program Files\nodejs\node.exe F:\codefuntest\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library= gyp info it worked if it ends with ok gyp verb cli [ gyp verb cli 'C:\\Program Files\\nodejs\\node.exe', gyp verb cli 'F:\\codefuntest\\node_modules\\node-gyp\\bin\\node-gyp.js', gyp verb cli 'rebuild', gyp verb cli '--verbose', gyp verb cli '--libsass_ext=', gyp verb cli '--libsass_cflags=', gyp verb cli '--libsass_ldflags=', gyp verb cli '--libsass_library=' gyp verb cli ] gyp info using node-gyp@7.1.2 gyp info using node@18.12.1 | win32 | x64 gyp verb command rebuild [] gyp verb command clean [] gyp verb clean removing "build" directory gyp verb command configure [] gyp verb find Python Python is not set from command line or npm configuration gyp verb find Python Python is not set from environment variable PYTHON gyp verb find Python checking if "python3" can be used gyp verb find Python - executing "python3" to get executable path gyp verb find Python - "python3" is not in PATH or produced an error gyp verb find Python checking if "python" can be used gyp verb find Python - executing "python" to get executable path gyp verb find Python - executable path is "D:\python\python.exe" gyp verb find Python - executing "D:\python\python.exe" to get version gyp verb find Python - version is "3.10.9" gyp info find Python using Python version 3.10.9 found at "D:\python\python.exe" gyp verb get node dir no --target version specified, falling back to host node version: 18.12.1 gyp verb command install [ '18.12.1' ] gyp verb install input version string "18.12.1" gyp verb install installing version: 18.12.1 gyp verb install --ensure was passed, so won't reinstall if already installed gyp verb install version is already installed, need to check "installVersion" gyp verb got "installVersion" 9 gyp verb needs "installVersion" 9 gyp verb install version is good gyp verb get node dir target node version installed: 18.12.1 gyp verb build dir attempting to create "build" dir: F:\codefuntest\node_modules\node-sass\build gyp verb build dir "build" dir needed to be created? F:\codefuntest\node_modules\node-sass\build gyp verb find VS msvs_version not set from command line or npm config gyp verb find VS VCINSTALLDIR not set, not running in VS Command Prompt gyp verb find VS unknown version "undefined" found at "C:\Program Files\Microsoft Visual Studio\2022\Community" gyp verb find VS unknown version "undefined" found at "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools" gyp verb find VS could not find a version of Visual Studio 2017 or newer to use gyp verb find VS looking for Visual Studio 2015 gyp verb find VS - not found gyp verb find VS not looking for VS2013 as it is only supported up to Node.js 8 gyp ERR! find VS gyp ERR! find VS msvs_version not set from command line or npm config gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt gyp ERR! find VS unknown version "undefined" found at "C:\Program Files\Microsoft Visual Studio\2022\Community" gyp ERR! find VS unknown version "undefined" found at "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools" gyp ERR! find VS could not find a version of Visual Studio 2017 or newer to use gyp ERR! find VS looking for Visual Studio 2015 gyp ERR! find VS - not found gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8 gyp ERR! find VS gyp ERR! find VS ************************************************************** gyp ERR! find VS You need to install the latest version of Visual Studio gyp ERR! find VS including the "Desktop development with C++" workload. gyp ERR! find VS For more information consult the documentation at: gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows gyp ERR! find VS ************************************************************** gyp ERR! find VS gyp ERR! configure error gyp ERR! stack Error: Could not find any Visual Studio installation to use gyp ERR! stack at VisualStudioFinder.fail (F:\codefuntest\node_modules\node-gyp\lib\find-visualstudio.js:121:47) gyp ERR! stack at F:\codefuntest\node_modules\node-gyp\lib\find-visualstudio.js:74:16 gyp ERR! stack at VisualStudioFinder.findVisualStudio2013 (F:\codefuntest\node_modules\node-gyp\lib\find-visualstudio.js:351:14) gyp ERR! stack at F:\codefuntest\node_modules\node-gyp\lib\find-visualstudio.js:70:14 gyp ERR! stack at F:\codefuntest\node_modules\node-gyp\lib\find-visualstudio.js:372:16 gyp ERR! stack at F:\codefuntest\node_modules\node-gyp\lib\util.js:54:7 gyp ERR! stack at F:\codefuntest\node_modules\node-gyp\lib\util.js:33:16 gyp ERR! stack at ChildProcess.exithandler (node:child_process:420:5) gyp ERR! stack at ChildProcess.emit (node:events:513:28) gyp ERR! stack at maybeClose (node:internal/child_process:1091:16) gyp ERR! System Windows_NT 10.0.22621 gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "F:\\codefuntest\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library=" gyp ERR! cwd F:\codefuntest\node_modules\node-sass gyp ERR! node -v v18.12.1
d388cded875d8815f378ef2f8adda216
{ "intermediate": 0.5780405402183533, "beginner": 0.289740651845932, "expert": 0.1322188526391983 }
32,165
In X11, how do I present a pixel array to the window?
564b5d598673e6c263b3f0dcba896f54
{ "intermediate": 0.5757284760475159, "beginner": 0.12863263487815857, "expert": 0.2956388294696808 }
32,166
generate latex code using below resume content GET IN CONTACT Mobile: <PRESIDIO_ANONYMIZED_PHONE_NUMBER> Email: <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS> PERSONAL DETAILS Total Experience 3 Years 0 Month Current Location Kolkata SKILLS Java Core Java Programming Spring Data JPA Spring Boot Spring MVC Spring Security Mockito JUnit Multithreading Hibernate JDBC Log4j Performance Optimization Debugging Kafka MySQL Azure Dashboard Kubernetes Swagger Postman LANGUAGES KNOWN English Hindi Bengali PROFILE SUMMARY Ambitious Java developer versed in following established procedures and working under little or no supervision. Offering technical expertise in programming analysis, application analysis and design. Excellent team player with in-depth knowledge of development tools and languages. EDUCATION HISTORY Graduation Course B.Tech/B.E.( Computers ) College Techno India Group, Kolkata Year of Passing 2020 Grade 8.1/10 WORK EXPERIENCE Mar 2021 to Present Java Developer at Tata Consultancy Services (TCS) As a Java developer, I played a key role in the development of system from scratch and contributed to its successful release into production. PROJECTS CRM App(Azure Function App), 92 Days Working on the CRM function as a Java developer within an Azure Function has been an enriching experience. My main responsibility was to handle password encryption and decryption operations. In this role, I wrote Java code to implement the encryption and decryption logic, ensuring the security of sensitive password information. I also collaborated with the team to design and implement unit tests to ensure the functionality and robustness of the CRM function. Asset Manager , 365 Days Worked as a support executive for an Asset Manager Application, a software tool used by ASDA colleagues to effectively maintain and track asset details. As a support Shalini Kumari Java Developer COURSES & CERTIFICATIONS Software Architect(Microservices), Edureka Azure Fundamental AZ-900 executive, I provided assistance in both the functional and technical aspects of the application, leveraging my expertise in Java programming for backend support ensuring smooth operations and optimal functionality for the users. Reporting Dashboard , 151 Days As a backend developer, I worked individually on the backend and database part of the Application Dashboard for the freeze period and golden quarter at Asda. This dashboard allows clients to track the progress of all projects and monitor the number of incidents, including major incidents. To You Parcel Management Services (TPMS), 549 Da ys The TPMS System is a software application designed to streamline and automate the process of managing parcels. It handles various aspects of parcel management, such as tracking, delivery, and inventory management. As a Java developer, I played a key role in the development of this system from scratch and contributed to its successful release into production.
bf2a2a5ea82dbc07ead3d5cf2109fdbf
{ "intermediate": 0.5442609190940857, "beginner": 0.2319788783788681, "expert": 0.22376015782356262 }
32,167
I hace this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] final_signal = [] exit = [] sell_result = 0.0 buy_result = 0.0 active_signal = None # Retrieve depth data depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] buy_qty = round(sum(float(bid[1]) for bid in bids), 0) highest_bid_price = float(bids[0][0]) lowest_bid_price = float(bids[1][0]) b_h = highest_bid_price b_l = lowest_bid_price asks = depth_data['asks'] sell_qty = round(sum(float(ask[1]) for ask in asks), 0) highest_ask_price = float(asks[0][0]) lowest_ask_price = float(asks[1][0]) s_h = highest_ask_price s_l = lowest_ask_price mark_price_data = client.ticker_price(symbol=symbol) mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol) mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0 print(f"Low {lowest_ask_price}") print(f"High {highest_ask_price}") print(asks) # Calculate the threshold for order price deviation if mark_price_percent > 2: pth = 7 / 100 elif mark_price_percent < -2: pth = 7 / 100 else: pth = 7 / 100 # Subtract quantity if bid price is the same as mark price for bid in bids: price_buy = float(bid[0]) qty_buy = float(bid[1]) if price_buy == mark_price: buy_result = buy_qty - qty_buy br = buy_result # Subtract quantity if bid price is the same as mark price for ask in asks: price_sell = float(ask[0]) qty_sell = float(ask[1]) if price_sell == mark_price: sell_result = sell_qty - qty_sell sr = sell_result if mark_price_percent > 2: th = 20000 elif mark_price_percent < -2: th = 20000 else: th = 13000 #Main Signal if (((buy_qty > th) > (sell_qty < th)) and (b_l > mp + pth)): signal.append('buy') elif (((sell_qty > th) > (buy_qty < th)) and (s_h < mp - pth)): signal.append('sell') else: signal.append('') #Signal confirmation if signal == ['buy'] and not (((br < th) < sell_qty) and (b_l < mp + pth)): final_signal.append('buy') elif signal == ['sell'] and not (((sr < th) < buy_qty) and (s_h > mp - pth)): final_signal.append('sell') else: final_signal.append('') #Exit if final_signal == ['buy'] and (((br < th) < sell_qty) and (b_h < mp + pth)): exit.append('buy_exit') elif final_signal == ['sell'] and (((sr < th) < buy_qty) and (s_l > mp - pth)): exit.append('sell_exit') else: exit.append('') samerkh = exit and final_signal return samerkh You need to change constants highest_ask_price and lowest_ask_price , they need to get lowest price of all order book
b95e9a4b790cdbac8690fd40f74fd00e
{ "intermediate": 0.3169669210910797, "beginner": 0.4309491813182831, "expert": 0.2520838677883148 }
32,168
如何解决: Compiled successfully! You can now view deep-chat-example-ui in the browser. Local: http://localhost:3000 On Your Network: http://192.168.73.1:3000 Note that the development build is not optimized. To create a production build, use yarn build. webpack compiled successfully ERROR in src/App.tsx:51:11 TS2322: Type '(_?: string, files?: File[]) => boolean | undefined' is not assignable to type 'ValidateInput'. Type 'boolean | undefined' is not assignable to type 'boolean'. Type 'undefined' is not assignable to type 'boolean'. 49 | mixedFiles={true} 50 | textInput={{placeholder: {text: 'Send a file!'}}} > 51 | validateInput={(_?: string, files?: File[]) => { | ^^^^^^^^^^^^^ 52 | return files && files.length > 0; 53 | }} 54 | /> ERROR in src/App.tsx:178:11 TS2322: Type '(text?: string, files?: File[]) => boolean | undefined' is not assignable to type 'ValidateInput'. Type 'boolean | undefined' is not assignable to type 'boolean'. 176 | textInput={{placeholder: {text: 'Describe the desired changes'}}} 177 | errorMessages={{displayServiceErrorMessages: true}} > 178 | validateInput={(text?: string, files?: File[]) => { | ^^^^^^^^^^^^^ 179 | return !!text && text?.trim() !== '' && files && files.length > 0; 180 | }} 181 | />
13ed120b12d29daefb7fbbd5383446e9
{ "intermediate": 0.3499695062637329, "beginner": 0.34870287775993347, "expert": 0.3013276159763336 }
32,169
Compiled with problems: × ERROR in src/App.tsx:51:11 TS2322: Type '(_?: string, files?: File[]) => boolean | undefined' is not assignable to type 'ValidateInput'. Type 'boolean | undefined' is not assignable to type 'boolean'. Type 'undefined' is not assignable to type 'boolean'. 49 | mixedFiles={true} 50 | textInput={{placeholder: {text: 'Send a file!'}}} > 51 | validateInput={(_?: string, files?: File[]) => { | ^^^^^^^^^^^^^ 52 | return files && files.length > 0; 53 | }} 54 | /> ERROR in src/App.tsx:178:11 TS2322: Type '(text?: string, files?: File[]) => boolean | undefined' is not assignable to type 'ValidateInput'. Type 'boolean | undefined' is not assignable to type 'boolean'. 176 | textInput={{placeholder: {text: 'Describe the desired changes'}}} 177 | errorMessages={{displayServiceErrorMessages: true}} > 178 | validateInput={(text?: string, files?: File[]) => { | ^^^^^^^^^^^^^ 179 | return !!text && text?.trim() !== '' && files && files.length > 0; 180 | }} 181 | />
4e3dd1444052bb88fc8202abc5e184d7
{ "intermediate": 0.32752469182014465, "beginner": 0.3273657560348511, "expert": 0.34510958194732666 }
32,170
I used this code: asks = depth_data['asks'] sell_qty = round(sum(float(ask[1]) for ask in asks), 0) highest_ask_price = float(asks[0][0]) lowest_ask_price = float(asks[1][0]) s_h = highest_ask_price s_l = lowest_ask_price mark_price_data = client.ticker_price(symbol=symbol) mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol) mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0 print(f"Low {lowest_ask_price}") print(f"High {highest_ask_price}") I need code wihch will count highest and lowest price in all order book
2a00bef4f59e0ce2ac90d3da5d7dc0c8
{ "intermediate": 0.3997327387332916, "beginner": 0.31989607214927673, "expert": 0.28037112951278687 }
32,171
write me a java script for a button with the title roll
28fca53baa697b609348dbe68ba9b393
{ "intermediate": 0.3309478163719177, "beginner": 0.39125552773475647, "expert": 0.2777966260910034 }
32,172
Need to install VNC Server in Solaris 5.10. Any help?
190769c7fa8f9f69a9cb0f6472796f9e
{ "intermediate": 0.44972971081733704, "beginner": 0.2636379301548004, "expert": 0.2866324186325073 }
32,173
chatgpt 3 free
0c14e4996620a2ea5b44241fa7e4f90d
{ "intermediate": 0.33855050802230835, "beginner": 0.25471755862236023, "expert": 0.40673190355300903 }
32,174
I have this code: depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] buy_qty = round(sum(float(bid[1]) for bid in bids), 0) bid_prices = [float(bid[0]) for bid in bids] highest_bid_price = max(bid_prices) lowest_bid_price = min(bid_prices) b_h = highest_bid_price b_l = lowest_bid_price You need to give me system which will subtract bid qty of every order which price is higher than mark_price
2731122c4f9a54cb2e37c5dff6235b58
{ "intermediate": 0.45378226041793823, "beginner": 0.26336053013801575, "expert": 0.282857209444046 }
32,175
improve the readability + the performance of this and also refractor things that should be classbased: from fastapi import FastAPI, Request, BackgroundTasks import uvicorn from fastapi.templating import Jinja2Templates import numpy as np import cv2 import random import pygame from pydub import AudioSegment import logging import os import requests from datetime import datetime, timedelta import csv from pynput import keyboard import concurrent.futures import asyncio import threading from roboflow import Roboflow from transribe import Transcriber api_key = "IhgRWRgaHqkb_dz2UrK_NyTN1IQLwXHMQtfMBZZPzwA" base_url = "https://api.naga.ac/v1/audio/transcriptions" language = "en" first_boot = True transcriber = Transcriber(api_key, base_url) rf = Roboflow(api_key="xq0chu47g4AXAFzn4VDl") project = rf.workspace().project("digital-number-ocr") model = project.version(1).model stop_recording = threading.Event() weekdays_name = ["Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"] templates = Jinja2Templates(directory="templates") logging.basicConfig( filename="app.log", level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", ) check_weight = "None" TASK_STATUS = "Not started" console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") console_handler.setFormatter(formatter) logging.getLogger().addHandler(console_handler) app = FastAPI() # Paddleocr supports Chinese, English, French, German, Korean and Japanese. # You can set the parameter `lang` as `ch`, `en`, `fr`, `german`, `korean`, `japan` # to switch the language model in order. # ocr = PaddleOCR( # use_angle_cls=False, # lang="en", # ) # need to run only once to download and load model into memory x, y, w, h = 100, 100, 200, 200 threshold = 400 SERVER_RESPONSE = None long_time_no_seen = False #async def capture_frame_async(cap): # loop = asyncio.get_running_loop() # # Run in a separate thread because VideoCapture.read() is a blocking operation # with concurrent.futures.ThreadPoolExecutor() as pool: # ret, frame = await loop.run_in_executor(pool, cap.read) # return ret, frame async def conditional_sleep(target_interval, last_frame_change_time): elapsed = (datetime.now() - last_frame_change_time).total_seconds() sleep_time = target_interval - elapsed if sleep_time > 0: await asyncio.sleep(sleep_time) def play_audio_file(filepath): pygame.mixer.init() pygame.mixer.music.load(filepath) pygame.mixer.music.play() while pygame.mixer.music.get_busy(): # Wait for audio to finish playing continue pygame.mixer.music.unload() return "played" async def play_audio_file_async(file_path): loop = asyncio.get_running_loop() with concurrent.futures.ThreadPoolExecutor() as pool: await loop.run_in_executor(pool, lambda: play_audio_file(file_path)) def check_green_spectrum(image): green_threshold = 0.02 # Convert to HSV color space hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # Define range of green color in HSV lower_green = np.array([45, 100, 100]) upper_green = np.array([100, 255, 200]) # Create a binary mask where green colors are white and the rest are black green_mask = cv2.inRange(hsv_image, lower_green, upper_green) # Calculate the proportion of the image that is green green_ratio = np.sum(green_mask > 0) / ( image.size / 3 ) # image.size / 3 gives the total number of pixels in the image # Return True if there is a significant amount of green, indicating the display might be on return green_ratio > green_threshold # Image processing function async def process_images(): global SERVER_RESPONSE, TASK_STATUS, check_weight, long_time_no_seen last_frame_change_time = datetime.now() last_active = datetime.now() combined_result = [] failed_frames = 0 support = 0 try: TASK_STATUS = "In progress" logging.info("The process started") print("started") url = "http://10.30.227.93:8088/shot.jpg" # frame = cv2.imread("shot(3).jpg") # url = "http://192.168.127.124:8080/video" cap = cv2.VideoCapture(url) # url = "http://10.30.225.127:8080/shot.jpg" while check_weight != "None": # ret, frame = await capture_frame_async(cap) img_resp = requests.get(url) img_arr = np.frombuffer(img_resp.content, np.uint8) frame = cv2.imdecode(img_arr, -1) current_pic = frame combined_result = [] # cv2.imshow("Video Feed", frame) # Apply background subtraction # cropped_img = current_pic[580 : 580 + 75, 960 : 960 + 180] cropped_img = current_pic[555 : 555 + 75, 995 : 995 + 180] if datetime.now() - last_active >= timedelta(minutes=30): long_time_no_seen = False last_active = datetime.now() if not long_time_no_seen: await play_audio_file_async("Audio/redo.mp3") long_time_no_seen = True last_frame_change_time = datetime.now() cropped_img_gray = cv2.cvtColor(cropped_img, cv2.COLOR_BGR2GRAY) image_center = tuple(np.array(cropped_img_gray.shape[1::-1]) / 2) ## Get the rotation matrix using the center and the angle rot_mat = cv2.getRotationMatrix2D(image_center, -3.5, 1.0) # Rotate the cropped_img_gray using the rotation matrix rotated_image = cv2.warpAffine( cropped_img_gray, rot_mat, cropped_img_gray.shape[1::-1], flags=cv2.INTER_LINEAR, ) cv2.imwrite("combined_area.png", cropped_img) # kg_result = await check_picture(kg_area) # hg_result = await check_picture(hg_area) await play_audio_file_async("Audio/reading.mp3") combined_result = await check_picture() if combined_result == [] or combined_result.strip() == "": print(combined_result) if support > 2: await play_audio_file_async("Audio/support.mp3") support = 0 elif failed_frames > 5: random_number = random.randint(1, 2) await play_audio_file_async(f"Audio/waiting{random_number}.mp3") failed_frames = 0 support += 1 last_frame_change_time = datetime.now() print("Frame has changed significantly. Updating stable frame.") failed_frames += 1 continue if combined_result != []: if "-" in combined_result: combined_result = combined_result.replace("-", ".") hey_there = await generate_audio(combined_result) print(f"{hey_there}") await play_audio_file_async("audio.mp3") print(f"combined: {combined_result}") await update_csv(combined_result, check_weight) # # # Reset stable frame and timestamp after running OCR failed_frames = 0 support = 0 check_weight = "None" await conditional_sleep(0.1, last_frame_change_time) except Exception as e: TASK_STATUS = "Failed" SERVER_RESPONSE = str(e) logging.error( "An error occurred during image processing: {0}".format(e), exc_info=True ) def record_audio(): print("Starting recording…") url = "http://10.30.227.93:8088/audio.wav" with requests.get(url, stream=True) as r, open("audio.wav", "wb") as fd: for chunk in r.iter_content(1024): fd.write(chunk) # Check if the stop condition is set if stop_recording.is_set(): print("Recording stopped by user.") break audio_text = transcriber.transcribe_audio("audio.wav") print(audio_text) def start_recording(): stop_recording.clear() # Start a thread that records audio record_thread = threading.Thread(target=record_audio) record_thread.start() # Start a timer for 7 seconds timer_thread = threading.Timer(7, stop_recording.set) timer_thread.start() # If the recording is still going after 7 seconds, stop it record_thread.join() if record_thread.is_alive(): print("7 seconds passed. Stopping recording.") stop_recording.set() # Clean up timer_thread.join() def on_press(key): global check_weight, first_boot try: # pynput.keyboard.KeyCode print("hey") print(key) if key == keyboard.Key.media_next: print("heys") check_weight = "In" asyncio.run(process_images()) print("Media play/pause key pressed") if key == keyboard.Key.media_previous: print("heys") check_weight = "Out" asyncio.run(process_images()) print("Media play/pause key pressed") if key == keyboard.Key.media_play_pause: if ( not stop_recording.is_set() or first_boot ): # If recording has not been stopped yet print("Stopping recording early…") stop_recording.set() first_boot = False else: print("Starting new recording…") start_recording() print("Alphanumeric key {0} pressed".format(key.char)) # pynput.keyboard.Key (you can find volume keys here) print("Special Key {0} pressed".format(key)) # set sound up only after 1 key press... except AttributeError: print("special key {0} pressed".format(key)) @app.post("/start_processing") async def start_processing(background_tasks: BackgroundTasks): logging.info("Received start_processing request") # Run process_images as a background task inside an event loop background_tasks.add_task(process_images) return {"message": "Image processing started"} @app.get("/get_response") async def get_response(): return {"response": SERVER_RESPONSE} @app.get("/task_status") def get_task_status(): return {"status": TASK_STATUS} async def generate_audio(clenedUpResponse): global TASK_STATUS print(clenedUpResponse) if clenedUpResponse.startswith("00"): clenedUpResponse = clenedUpResponse.replace("00", "0.0") while float(clenedUpResponse) > 30.0: clenedUpResponse = float(clenedUpResponse) / 10 clenedUpResponse = round(float(clenedUpResponse), 2) print(clenedUpResponse) if "." in str(clenedUpResponse): clenedUpResponse = clenedUpResponse.replace(".", " komma ") combined_audio_seg = AudioSegment.empty() # Generate and concatenate audio for each word audio_seg = AudioSegment.from_mp3(f"Audio/{check_weight}.mp3") combined_audio_seg += audio_seg for text in clenedUpResponse.split(): if text != "komma" and len(text) > 2: # making sure that text can never be 3 digits so formats it to 2 digits text = text[:2] if text.startswith("0") and len(text) > 1 and text[1:].isdigit(): # Loop through each character in ‘text’ for extra in text: audio_filename = f"Audio/{extra}.mp3" audio_seg = AudioSegment.from_mp3(audio_filename) combined_audio_seg += audio_seg else: audio_filename = f"Audio/{text}.mp3" audio_seg = AudioSegment.from_mp3(audio_filename) combined_audio_seg += audio_seg # Export the combined audio file audio_seg = AudioSegment.from_mp3("Audio/kilo.mp3") combined_audio_seg += audio_seg combined_audio_filename = "audio.mp3" combined_audio_seg.export(combined_audio_filename, format="mp3") return combined_audio_filename @app.get("/audio") async def play_audio(): await play_audio_file_async("audio.mp3") return {"message": "Audio playback started on server"} @app.get("/video") async def video_endpoint(request: Request): with keyboard.Listener(on_press=on_press) as listener: listener.join() return templates.TemplateResponse("video.html", {"request": request}) async def check_picture(): # Convert the Numpy array to an image file-like object try: result = model.predict("combined_area.png", confidence=40, overlap=30).json() # Sort the predictions by the ‘x’ value sorted_predictions = sorted(result["predictions"], key=lambda k: k["x"]) # Update the original result with the sorted predictions result["predictions"] = sorted_predictions classes = [] # Loop through each sorted prediction and add the "class" to the classes list for prediction in sorted_predictions: classes.append(prediction["class"]) # Join the classes into a single string classes_string = "".join(classes) print(classes_string) except: print("no visable numbers") new_result = [] return classes_string async def update_csv(result, in_or_out): global weekdays_name if in_or_out == "None": await play_audio_file_async("Audio/support.mp3") print("Kan icke vara None") return if result is None: print("No result to update CSV.") return week = datetime.now().isocalendar().week weekday = datetime.now().isocalendar().weekday weekday = weekdays_name[weekday - 1] file_name = f"{in_or_out}/{in_or_out}_Elektronik_{week}.csv" file_exists = os.path.isfile(f"WeeklyUpdates/{file_name}") # If the file doesn't exist, create a new one with the header row if not file_exists: with open(f"WeeklyUpdates/{file_name}", "w", newline="") as csvfile: writer = csv.writer(csvfile, delimiter=",", quotechar='"') writer.writerow(["Vikt", "Datum", "Total Vikt"]) csvfile.close() # Read the existing CSV file with open(f"WeeklyUpdates/{file_name}", "r") as csvfile: reader = csv.reader(csvfile, delimiter=",", quotechar='"') rows = list(reader) # Check if the date already exists # Add the weights for the current date total_weight = 0 for row in rows: if row[1] == weekday: total_weight += float(row[0]) try: while float(result) > 30.0: result = float(result) / 10 except ValueError as ve: print(f"Error converting result to float: {ve}") # Handle the error or return from the function # Round the result to 2 decimal places result = round(float(result), 2) total_weight += float(result) rows.append([str(result), weekday, round(total_weight, 2)]) # Write the updated rows to the CSV file with open(f"WeeklyUpdates/{file_name}", "w", newline="") as csvfile: writer = csv.writer(csvfile, delimiter=",", quotechar='"') writer.writerows(rows) return "Done" if __name__ == "__main__": uvicorn.run(app, host="localhost", port=3333)
03ad460feb19e83c7f059782e53e1b83
{ "intermediate": 0.3585488200187683, "beginner": 0.434363454580307, "expert": 0.2070877104997635 }
32,176
Please make these attributes into a style for me (android:layout_width=“match_parent” android:layout_height=“wrap_content” android:layout_gravity=“center” android:layout_weight=“1” android:backgroundTint=“@color/white” android:gravity=“center”)
dca90a1972aca4b22535b7aba5e18a1c
{ "intermediate": 0.45872488617897034, "beginner": 0.22906285524368286, "expert": 0.3122122883796692 }
32,177
In a redis db I gotta save two things, 2. the hash of a question image, then a list of hashes of answer images to those questions. How should i implement this in python so i can search for a question, then get a list of answers. The whole system works only on hashes so the code does not need any example questions or images just placeholder phash hashes. Make functions for adding a new question hash without any answers, the make one to add a answer has to a specified question hash
5dd67c77f349663c767dee66e4d5b3e9
{ "intermediate": 0.5028850436210632, "beginner": 0.16912147402763367, "expert": 0.3279934525489807 }
32,178
I used this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] final_signal = [] exit = [] sell_result = 0.0 buy_result = 0.0 active_signal = None sell_qty = 0.0 buy_qty = 0.0 # Retrieve depth data depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] bid_prices = [float(bid[0]) for bid in bids] highest_bid_price = max(bid_prices) lowest_bid_price = min(bid_prices) b_h = highest_bid_price b_l = lowest_bid_price asks = depth_data['asks'] ask_prices = [float(ask[0]) for ask in asks] highest_ask_price = max(ask_prices) lowest_ask_price = min(ask_prices) s_h = highest_ask_price s_l = lowest_ask_price for bid in bids: price_buy = float(bid[0]) qty_buy = float(bid[1]) if price_buy < mark_price: buy_qty = buy_qty - qty_buy for ask in asks: price_sell = float(ask[0]) qty_sell = float(ask[1]) if price_sell > mark_price: sell_qty = sell_qty - qty_sell mark_price_data = client.ticker_price(symbol=symbol) mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol) mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0 # Calculate the threshold for order price deviation if mark_price_percent > 2: pth = 7 / 100 elif mark_price_percent < -2: pth = 7 / 100 else: pth = 7 / 100 # Subtract quantity if bid price is the same as mark price for bid in bids: price_buy = float(bid[0]) qty_buy = float(bid[1]) if price_buy == mark_price: buy_result = buy_qty - qty_buy br = buy_result # Subtract quantity if bid price is the same as mark price for ask in asks: price_sell = float(ask[0]) qty_sell = float(ask[1]) if price_sell == mark_price: sell_result = sell_qty - qty_sell sr = sell_result if mark_price_percent > 2: th = 20000 elif mark_price_percent < -2: th = 20000 else: th = 13000 print(buy_qty) print(sell_qty) #Main Signal if (((buy_qty > th) > (sell_qty < th)) and (b_l > mp + pth)): signal.append('buy') elif (((sell_qty > th) > (buy_qty < th)) and (s_h < mp - pth)): signal.append('sell') else: signal.append('') #Signal confirmation if signal == ['buy'] and not (((br < th) < sell_qty) and (b_l < mp + pth)): final_signal.append('buy') elif signal == ['sell'] and not (((sr < th) < buy_qty) and (s_h > mp - pth)): final_signal.append('sell') else: final_signal.append('') #Exit if final_signal == ['buy'] and (((br < th) < sell_qty) and (b_h < mp + pth)): exit.append('buy_exit') elif final_signal == ['sell'] and (((sr < th) < buy_qty) and (s_l > mp - pth)): exit.append('sell_exit') else: exit.append('') samerkh = exit and final_signal return samerkh But buy_qty and sell_qty are equal : -14222.251999999982 -14360.349999999999 It wrong , they need to be positive numbers
e3e38b1f2f10fbe026c60733a2269b5f
{ "intermediate": 0.3402327597141266, "beginner": 0.4183388352394104, "expert": 0.2414284497499466 }
32,179
In a redis db I gotta save two things, 2. the hash of a question image, then a list of hashes of answer images to those questions. How should i implement this in python so i can search for a question, then get a list of answers. The whole system works only on hashes so the code does not need any example questions or images just placeholder phash hashes. Make functions for adding a new question hash without any answers, the make one to append an answer has to a specified question hash, and one to return the list of answer hashes for a specific question hash, or a 80 hamming distance only if the specific hash isnt found.
ba1ff3d3bcc6fca8553b6681246a0f29
{ "intermediate": 0.49413183331489563, "beginner": 0.13319101929664612, "expert": 0.37267711758613586 }
32,180
Мне нужно, чтобы когда я нажимаю кнопку добавить в корзину (js_buy), в форме которая открывать, чтобы сначала вылез само изображение товара, ниже информация о товаре на php ( Nazvanie, Brend, Razmer, Color, Price), ниже поле выбора количества товара и уже кнопка добавить в корзину (js_send).Код: <?php /* Установка соединения с бд */ $link = mysqli_connect("localhost", "root", "", "интернет магазин одежды"); /* Проверка соединения с бд */ if (mysqli_connect_errno()) { printf("Не удалось подключиться: %s\n", mysqli_connect_error()); exit(); } /* SQL запрос на выборку данных из таблицы zriteli*/ $result = mysqli_query($link, "SELECT * FROM catalog LIMIT 100"); $products = mysqli_fetch_all($result, MYSQLI_ASSOC); // Преобразование результата запроса в ассоциативный массив /* Завершение соединения с БД */ mysqli_close($link); ?> <section class="product-box"> <h2>Каталог</h2> <div class="row"> <?php foreach ($products as $product): ?> <div class="col-xs-6 col-sm-4 col-md-3 col-lg-3 product-parent" data-id="<?= $product['N_tovar'] ?>"> <div class="product"> <div class="product-pic" style="background: url('data:image/jpeg;base64,<?= base64_encode($product['image']) ?>') no-repeat; background-size: auto 100%; background-position: center"></div> <span class="product-name"><?= $product['Nazvanie'] ?></span> <span class="product-brend"><?= $product['Brend'] ?></span> <span class="product_price"><?= $product['Price'] ?> руб.</span> <button class="js_buy">Добавить в корзину</button> </div> </div> <?php endforeach ?> </div> </section> <footer> 2023 © Clothes Store </footer> <div class="overlay js_overlay"></div> <div class="popup"> <h3>Добавление товара</h3><i class="fas fa-times close-popup js_close-popup"></i> <input type="text" name="quantity" id="quantity" placeholder="Выберите количество товаров"> <button class="js_send">Добавить в корзину</button> </div> <script> // Добавление товара в корзину const buyButtons = document.querySelectorAll('.js_buy'); buyButtons.forEach(button => { button.addEventListener('click', () => { const parentProduct = button.closest('.product-parent'); const productId = parentProduct.getAttribute('N_tovar'); const productName = parentProduct.querySelector('.Nazvanie').textContent; const productBrand = parentProduct.querySelector('.Brend').textContent; const productSize = parentProduct.querySelector('.Razmer').textContent; // Отправка данных о товаре на сервер // Для примера, вместо отправки на сервер, просто выводим информацию о товаре const quantity = document.getElementById('quantity').value; alert(`Добавлено в корзину: ${productName}, ${productBrand}, ${productSize}, количество: ${quantity}`); }); }); </script> </body> </html>
6f03bf845bedc39808081769c6fc59f1
{ "intermediate": 0.35952356457710266, "beginner": 0.37146177887916565, "expert": 0.2690146267414093 }
32,181
solidity how to override function
d971a450af3d75c69a891bde20588ea5
{ "intermediate": 0.5101662874221802, "beginner": 0.24628527462482452, "expert": 0.2435484379529953 }
32,182
using UnityEngine; using UnityEditor; using System.IO; public class FileExporter : MonoBehaviour { public string bundlePath; // Path to the .bundle file public string saveDirectory; // Directory to save the files void Start() { // Load the AssetBundle AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); // Check if the AssetBundle is loaded successfully if (bundle != null) { // Get all asset names in the AssetBundle string[] assetNames = bundle.GetAllAssetNames(); // Iterate over each asset name foreach (string assetName in assetNames) { // Load the file from the AssetBundle as an Object Object fileObject = bundle.LoadAsset(assetName); // Convert the Object to a byte array byte[] fileBytes = fileObject != null ? EditorUtilityExtensions.GetBytesFromObject(fileObject) : null; if (fileBytes != null) { // Create the save directory if it doesn’t exist Directory.CreateDirectory(saveDirectory); // Set the save path for the file string savePath = Path.Combine(saveDirectory, Path.GetFileName(assetName)); // Write the file to disk File.WriteAllBytes(savePath, fileBytes); Debug.Log("File saved: " + assetName); } else { Debug.LogError("Failed to load file from AssetBundle: " + assetName); } } bundle.Unload(false); // Unload the AssetBundle } else { Debug.LogError("Failed to load AssetBundle."); } } } public static class EditorUtilityExtensions { public static byte[] GetBytesFromObject(Object obj) { string tempPath = Path.GetTempFileName(); bool success = AssetDatabase.ExportPackage(AssetDatabase.GetAssetPath(obj), tempPath, ExportPackageOptions.ExportDependencies); if (success) { return File.ReadAllBytes(tempPath); } return null; } } Assets\Scripts\FileExporter.cs(65,116): error CS0117: 'ExportPackageOptions' does not contain a definition for 'ExportDependencies'
66e57a07ea48ac49a2e09d610292bfec
{ "intermediate": 0.38005268573760986, "beginner": 0.4886002540588379, "expert": 0.13134713470935822 }
32,183
can you write a python script that will open firefox browser go to google and type in a search bar twitter then login to twitter with user credentials after login find search bar then type twitch.tv/ and press enter wait for page to load complitlly then find latest tweets press on latest tweets wait for page to load then proceed to retweet 10 top tweets then scroll back up and retweet 10 more tweets then wait for 20 minutes then repeat from 'proceed'
fdc1a872a7dea9f9235dba96a9051de8
{ "intermediate": 0.4288962185382843, "beginner": 0.09834286570549011, "expert": 0.4727608561515808 }
32,184
using UnityEngine; using UnityEngine.UI; using System.IO; public class bundleunpack : MonoBehaviour { public string bundlePath; // Путь к .bundle файлу public string imageName; // Имя изображения в AssetBundle public GameObject imageHolder; // Ссылка на объект, содержащий компонент Image public string savePath; void Start() { Debug.Log("program started"); // Загрузка AssetBundle AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); // Проверка наличия AssetBundle if (bundle != null) { Debug.Log("Bundle loaded"); // Get all asset names in the AssetBundle string[] assetNames = bundle.GetAllAssetNames(); // Iterate over each asset name foreach (string assetName in assetNames) { // Check if the asset is an image Debug.Log("Image Name: " + assetName); } // Загрузка изображения из AssetBundle Sprite image = bundle.LoadAsset<Sprite>(imageName); // Получение компонента Image из объекта-держателя изображения Image targetImage = imageHolder.GetComponent<Image>(); // Установка загруженного изображения в компонент Image targetImage.sprite = image; bundle.Unload(false); // Выгрузка AssetBundle }else{Debug.Log("None of bundle");} } } Добавь в код foreach, чтобы каждый файл сохранялся на диск по пути savePath
25fba8914de8440c1b06536bf95f7fe1
{ "intermediate": 0.332602322101593, "beginner": 0.2807374894618988, "expert": 0.38666024804115295 }
32,185
using UnityEngine; using UnityEngine.UI; using System.IO; public class NewBehaviourScript1 : MonoBehaviour { public string bundlePath; public string imageName; public GameObject imageHolder; public string savePath; void Start() { Debug.Log("program started"); AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); if (bundle != null) { Debug.Log("Bundle loaded"); string[] assetNames = bundle.GetAllAssetNames(); foreach (string assetName in assetNames) { Debug.Log("Image Name: " + assetName); # Добавь здесь код с сохранением файла из bundle на диск в папку savePath } }else{Debug.Log("None of bundle");} } } Добавь здесь код с сохранением файла из bundle на диск в папку savePath. Учти, что файл в bundle может быть как изображение, так и префаб или звук и так далее.
e89161e1e26470d964877d4cdb0b4e91
{ "intermediate": 0.5453989505767822, "beginner": 0.3007907569408417, "expert": 0.1538103222846985 }
32,186
using UnityEngine; using UnityEngine.UI; using System.IO; public class NewBehaviourScript1 : MonoBehaviour { public string bundlePath; public GameObject imageHolder; public string savePath; void Start() { Debug.Log("program started"); AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); if (bundle != null) { Debug.Log("Bundle loaded"); string[] assetNames = bundle.GetAllAssetNames(); foreach (string assetName in assetNames) { Debug.Log("Image Name: " + assetName); # Добавь здесь код с сохранением файла из bundle на диск в папку savePath. Сохраняй все типы файлов, как изображение, так и префаб и все другие типы файлов } }else{Debug.Log("None of bundle");} } }
34646491cddf644b6858a605e2f40e64
{ "intermediate": 0.5026229619979858, "beginner": 0.32842209935188293, "expert": 0.16895486414432526 }
32,187
create html and css for tab header with icon from close.png on the right side and tab name text must be centered over the tab size not including close icon size
b9ed0dd0d208b0e40c19d65b0a702954
{ "intermediate": 0.3768391013145447, "beginner": 0.21316619217395782, "expert": 0.4099946916103363 }
32,188
I used thi scode: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] final_signal = [] exit = [] sell_result = 0.0 buy_result = 0.0 active_signal = None # Retrieve depth data depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] bid_prices = [float(bid[0]) for bid in bids] highest_bid_price = max(bid_prices) lowest_bid_price = min(bid_prices) b_h = highest_bid_price b_l = lowest_bid_price asks = depth_data['asks'] ask_prices = [float(ask[0]) for ask in asks] highest_ask_price = max(ask_prices) lowest_ask_price = min(ask_prices) s_h = highest_ask_price s_l = lowest_ask_price y_qty = round(sum(float(bid[1]) for bid in bids), 0) l_qty = round(sum(float(ask[1]) for ask in asks), 0) for bid in bids: price_buy = float(bid[0]) qty_buy = float(bid[1]) if price_buy < mark_price: buy_qty = y_qty - qty_buy for ask in asks: price_sell = float(ask[0]) qty_sell = float(ask[1]) if price_sell > mark_price: sell_qty = l_qty - qty_sell mark_price_data = client.ticker_price(symbol=symbol) mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol) mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0 # Calculate the threshold for order price deviation if mark_price_percent > 2: pth = 7 / 100 elif mark_price_percent < -2: pth = 7 / 100 else: pth = 7 / 100 # Subtract quantity if bid price is the same as mark price for bid in bids: price_buy = float(bid[0]) qty_buy = float(bid[1]) if price_buy == mark_price: buy_result = buy_qty - qty_buy br = buy_result # Subtract quantity if bid price is the same as mark price for ask in asks: price_sell = float(ask[0]) qty_sell = float(ask[1]) if price_sell == mark_price: sell_result = sell_qty - qty_sell sr = sell_result if mark_price_percent > 2: th = 20000 elif mark_price_percent < -2: th = 20000 else: th = 13000 #Main Signal if (((buy_qty > th) > (sell_qty < th)) and (b_l > mp + pth)): signal.append('buy') elif (((sell_qty > th) > (buy_qty < th)) and (s_h < mp - pth)): signal.append('sell') else: signal.append('') #Signal confirmation if signal == ['buy'] and not (((br < th) < sell_qty) and (b_l < mp + pth)): final_signal.append('buy') elif signal == ['sell'] and not (((sr < th) < buy_qty) and (s_h > mp - pth)): final_signal.append('sell') else: final_signal.append('') #Exit if final_signal == ['buy'] and (((br < th) < sell_qty) and (b_h < mp + pth)): exit.append('buy_exit') elif final_signal == ['sell'] and (((sr < th) < buy_qty) and (s_l > mp - pth)): exit.append('sell_exit') else: exit.append('') samerkh = exit and final_signal return samerkh You need to add system for every bid and for every ask that if price_buy = float(bid[0]) < mark_price + (mark_price / 100) don;t count this order and order qty
f3e418881a298148893854df9e03e58f
{ "intermediate": 0.4078904390335083, "beginner": 0.426741361618042, "expert": 0.1653681993484497 }
32,189
Problem Description Raj is running the busiest cafe in the city. It is also the most visited cafe by VIPs VIPs buys costly Beverages. It gives Raj's Cafe high profit. Raj asked his workers to prefer serving VIPs firat, because VIPs don't like to wait much time. Whenever a person orders something, Raj gives priority values to the orders and odds it to the queue. The greater the value more important the order is. The workers start to serve the orders with high priority in queue ensuring that the VIPs get theirs orders quickly. However, those orders having low priority have to wait for a long time in queue upsetting those people. This reduces the total number of people visiting the cafe and reducing the profit. But, making first come first serve basis reduces the VIPs visiting the Raj came up with a new idea to keep the profit high. He introduced a new concept called dynamic priority. The priority of orders changes while in the queue. Raj will maintain a queue of orders with assigned priority adding new orders at end. The order with high priority in the queue will new orders to the queue and started calculating after how many orders his friend will get served, considering only orders currently in the queue. Given the queue, can you find after how many orders will Raj's friend get served? cafe. This also reduces the profit be served first. When an order got served due to its high priority, the priority of orders in the queue before this will be increased by one if two orders having same priority then the order which was en-queued first will be served first. This strikes a balance between reducing the waiting time of VIPs and also serving other people without much delay. One day, his friend visited the cafe and ordered something. As usual his order got some priority and got added in the queue. After some time his friend lost his patience and asked when will his order be served. After that, Raj stopped adding Constraints 2 <= N <= 25 1<= Priority<=100 1<=K<=N Input First line contains a Integer 'N' denoting the total orders in cafe which are needed to served. Second line consist 'N' space separated Integers indicating the priority of orders present in the queue. the queue. Third line consist of integer 'K' indicating the position of his friend in - Output Single Integer denoting after how many orders will Raj's friend get served. - Time Limit (secs) 1 Examples Example 1 Input 6 135246 4
0256e388e0746764235a81723836af84
{ "intermediate": 0.3731019198894501, "beginner": 0.26979130506515503, "expert": 0.3571067750453949 }
32,190
please make a python snippet to load a bdas.txt file and save a list of strings, each string is a unique line in the file.
bc9c9d68a3035013a77d56d9282c4339
{ "intermediate": 0.4099074900150299, "beginner": 0.16423094272613525, "expert": 0.42586153745651245 }
32,191
using UnityEngine; using UnityEngine.UI; using System.IO; public class NewBehaviourScript2 : MonoBehaviour { public string bundlePath; void Start() { Debug.Log("program started"); AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); if (bundle != null) { Debug.Log("Bundle loaded"); string[] assetNames = bundle.GetAllAssetNames(); foreach (string assetName in assetNames) { Debug.Log("Image Name: " + assetName); } GameObject lastPrefab = bundle.LoadAsset<GameObject>(assetNames[assetNames.Length - 1]); GameObject instantiatedPrefab = Instantiate(lastPrefab, imageHolder.transform); // Код, который проходится по всем объектам префаба и из компонента Image брал изображение Source Image и сохранял в папку C:\dir }else{Debug.Log("None of bundle");} } } Добавь код, как указано в комментарии
3b2ddbb483d5c204f96db6a8cba3cdee
{ "intermediate": 0.6328762173652649, "beginner": 0.20947574079036713, "expert": 0.15764805674552917 }
32,192
Compound Balance Problem Description Amir was given an unbalanced chemical compound in his chemistry class, and he was asked to balance them based on their valency and present them. The chemical compound can have two distinct elements and he must balance them such that they reach the equivalent point. Here the compounds are in the form of upper-case alphabets Ex AB, CS, ZO etc., and their valency is the sum of their ascii reduced to one digit. These compounds are balanced by generating the multiple of each of their valences such that the summation of those multiples reaches to an equivalent point. If any compound cannot be balanced to the equivalent point, then print "Not Possible" else print all the combinations in descending order of the multiple of valency of the first element. See example section for better understanding. Constraints Compounds formed are between [A-Z]. 1<=Equivalent point<=10^5 Input The first line contains the non-balanced compound. The second line contains the equivalent point. Output Print all the combination of the combinations in descending order of the multiple of valency of the first element or "Not Possible". Time Limit (secs) 1 Examples Example 1 Input AZ 100 Output A41 Z2 A32 Z4 A23 Z6 A14 Z8 A5 Z10 Explanation First we need to compute the valency of A and Z. Ascii A = 65 and Z = 90. Hence valency of A = 6 + 5 = 11           1 + 1 = 2. Similarly, valency of Z = 9 + 0 = 9. Since, valency of A=2 and valency of Z=9 therefore the possible combination of the compounds is A41 Z2 that is 2*41 + 9*2 = 100. Similarly, A32 Z4 that is 2*32 + 9*4 = 100 and so on. Mathematically A50 Z0 is also possible but as A50 Z0 means 50 molecules of A and 0 molecules of Z it is not really a compound. Hence A50 Z0 is not an output. Example 2 Input HZ 100 Output Not Possible Explanation First we need to compute the valency of H and Z. Ascii H = 72 and Z = 90. Hence valency of H = 7 + 2 = 9. Similarly, valency of Z = 9 + 0 = 9. Since, valency of H = 9 and Z = 9, therefore the closest it can get to the equivalent point is by multiplying 9*5+9*6 = 99 therefore it's not possible to balance.
279527db70a671b914aa457cfa3485dc
{ "intermediate": 0.36643221974372864, "beginner": 0.2522585690021515, "expert": 0.3813092112541199 }
32,193
What are some ways to represent a large torch tensor in short way to get some meaningful understanding of its content?
4b26f2a121f0a3be2d60d9af8d12e2f3
{ "intermediate": 0.31276553869247437, "beginner": 0.14175854623317719, "expert": 0.545475959777832 }
32,194
I am doing a c++ project and I am getting many errors in the following function that orders an unordered_map based on its key values, can you help me do it correctly: void SortMap(std::unordered_map<wxString, int>* unorderedMap) { std::sort(unorderedMap->begin(), unorderedMap->end(), (const pair<string, int>& a, const pair<string, int>& b) { return a.second > b.second; }); }
da4a101ce91a8d0b7f9a7c4c83a8ed4f
{ "intermediate": 0.7263247966766357, "beginner": 0.1942337155342102, "expert": 0.07944151014089584 }
32,195
Online Shopping Problem Description An online shopping store announced an offer for the upcoming festive season. In order to avail that offer, we have to collect the tokens for n consecutive days and using those tokens, we can buy items in the sale. Mithra, a regular customer, wanted to claim those tokens and decided to buy something in the sale. When the tokens season began, she started claiming the tokens. Unfortunately, in between the days, she forgot claiming and missed few tokens. Now the token season is ended. Suddenly, the app gave bumper offer to all users i.e., for any k consecutive days, every user can claim the tokens if they were unclaimed in the token season. Given an array tokens of size n denoting the number of tokens offered for n consecutive days and another array claim denoting the tokens are claimed or not on those particular days. If claim[i] is 1 then Mithra had claimed otherwise not. Another integer k is given denoting the number of days the bumper offer can be used. A list of items and costs are given. The only rule is that we can buy only one item using those tokens. Help Mithra in selecting k consecutive days and finally print the item(s) which she can buy aiming for the minimal wastage of tokens. If there are more than one item of same cost, then print them in lexicographical (ascending) order. Constraints 1 <= n <= 10 ^ 4 0 <= k <= 10 ^ 4 0 <= tokens[i] <= 10 ^ 4 1 <= number of items <= 100 Claim[i] is either 0 or 1 Tokens and claim are arrays of same size Input First line contains an integer n denoting the size of the tokens array. Second line contains the array tokens denoting the number of tokens available for n consecutive days. Third line contain claim array denoting whether Mithra claimed tokens or not, on these n days. Fourth line contain the integer k denoting the number of consecutive days bumper offer can be applied. Last line contains items denoting the items and their costs separated by colon. Consider below Examples for better understanding. Output A single line of item(s) that Mithra can buy with the tokens. If there are more than one, print them in the lexicographical (ascending) order. Time Limit (secs) 1 Examples Example 1 Input 8 7 5 0 2 8 6 12 1 1 0 1 1 0 1 1 0 2 Bucket:8 Cot:32 Chair:27 Cooker:37 Gas:45 Fan:34 Mug:3 Ac:100 Output Fan Explanation Of the 8 days of token season, 5 days are already claimed. So, she has to claim from days where a claim is not yet made (wherever the value is 0 in the claim array). By virtue of this she already has 7+2+6+12 = 27 tokens. Suppose Mithra decided to use the bumper offer for the days 4,5 or 5,6 then the total number of tokens she gains will be 7+2+8+6+12=35. Among all the given items, she can buy a fan which will result in the wastage of only 1 token. Other than fan, buying any items will result in the wastage of a greater number of tokens. Example 2 Input 12 8 3 6 22 5 0 11 1 0 4 9 6 0 1 0 1 1 0 1 0 1 0 0 0 3 Bucket:8 Cot:32 Geyser:45 Chair:27 Cooker:38 Gas:45 Fan:34 Mug:3 Ac:100 Bulb:15 Output Gas Geyser Explanation Of the 12 days of token season, 5 days are already claimed. So, she has to claim from days where a claim is not yet made (wherever the value is 0 in the claim array). By virtue of this she already has 3+22+5+11 = 41 tokens. Suppose Mithra decided to use the bumper offer for the days 10,11,12 then the number of tokens she gains will be 3+22+5+11+4+9+6=60. Among all the given items, she can buy gas or geyser which will result in the wastage of only 15 tokens. Other than these, buying any items will result in the wastage of a greater number of tokens.
f7b5ff7951138a33a8953bfb1ee13465
{ "intermediate": 0.33498844504356384, "beginner": 0.4270341396331787, "expert": 0.23797748982906342 }
32,196
Online Shopping Problem Description An online shopping store announced an offer for the upcoming festive season. In order to avail that offer, we have to collect the tokens for n consecutive days and using those tokens, we can buy items in the sale. Mithra, a regular customer, wanted to claim those tokens and decided to buy something in the sale. When the tokens season began, she started claiming the tokens. Unfortunately, in between the days, she forgot claiming and missed few tokens. Now the token season is ended. Suddenly, the app gave bumper offer to all users i.e., for any k consecutive days, every user can claim the tokens if they were unclaimed in the token season. Given an array tokens of size n denoting the number of tokens offered for n consecutive days and another array claim denoting the tokens are claimed or not on those particular days. If claim[i] is 1 then Mithra had claimed otherwise not. Another integer k is given denoting the number of days the bumper offer can be used. A list of items and costs are given. The only rule is that we can buy only one item using those tokens. Help Mithra in selecting k consecutive days and finally print the item(s) which she can buy aiming for the minimal wastage of tokens. If there are more than one item of same cost, then print them in lexicographical (ascending) order. Constraints 1 <= n <= 10 ^ 4 0 <= k <= 10 ^ 4 0 <= tokens[i] <= 10 ^ 4 1 <= number of items <= 100 Claim[i] is either 0 or 1 Tokens and claim are arrays of same size Input First line contains an integer n denoting the size of the tokens array. Second line contains the array tokens denoting the number of tokens available for n consecutive days. Third line contain claim array denoting whether Mithra claimed tokens or not, on these n days. Fourth line contain the integer k denoting the number of consecutive days bumper offer can be applied. Last line contains items denoting the items and their costs separated by colon. Consider below Examples for better understanding. Output A single line of item(s) that Mithra can buy with the tokens. If there are more than one, print them in the lexicographical (ascending) order. Time Limit (secs) 1 Examples Example 1 Input 8 7 5 0 2 8 6 12 1 1 0 1 1 0 1 1 0 2 Bucket:8 Cot:32 Chair:27 Cooker:37 Gas:45 Fan:34 Mug:3 Ac:100 Output Fan Explanation Of the 8 days of token season, 5 days are already claimed. So, she has to claim from days where a claim is not yet made (wherever the value is 0 in the claim array). By virtue of this she already has 7+2+6+12 = 27 tokens. Suppose Mithra decided to use the bumper offer for the days 4,5 or 5,6 then the total number of tokens she gains will be 7+2+8+6+12=35. Among all the given items, she can buy a fan which will result in the wastage of only 1 token. Other than fan, buying any items will result in the wastage of a greater number of tokens. Example 2 Input 12 8 3 6 22 5 0 11 1 0 4 9 6 0 1 0 1 1 0 1 0 1 0 0 0 3 Bucket:8 Cot:32 Geyser:45 Chair:27 Cooker:38 Gas:45 Fan:34 Mug:3 Ac:100 Bulb:15 Output Gas Geyser Explanation Of the 12 days of token season, 5 days are already claimed. So, she has to claim from days where a claim is not yet made (wherever the value is 0 in the claim array). By virtue of this she already has 3+22+5+11 = 41 tokens. Suppose Mithra decided to use the bumper offer for the days 10,11,12 then the number of tokens she gains will be 3+22+5+11+4+9+6=60. Among all the given items, she can buy gas or geyser which will result in the wastage of only 15 tokens. Other than these, buying any items will result in the wastage of a greater number of tokens. give working python code
4d994a209fb5d5a12f95bd40f2792b17
{ "intermediate": 0.35876330733299255, "beginner": 0.44009023904800415, "expert": 0.2011464387178421 }
32,197
using UnityEngine; using UnityEngine.UI; using System.IO; public class NewBehaviourScript2 : MonoBehaviour { public string bundlePath; public Transform imageHolder; public string savePath = @"C:\dir"; void Start() { Debug.Log("program started"); AssetBundle bundle = AssetBundle.LoadFromFile(bundlePath); if (bundle != null) { Debug.Log("Bundle loaded"); string[] assetNames = bundle.GetAllAssetNames(); foreach (string assetName in assetNames) { Debug.Log("Image Name: " + assetName); } GameObject lastPrefab = bundle.LoadAsset<GameObject>(assetNames[assetNames.Length - 1]); GameObject instantiatedPrefab = Instantiate(lastPrefab, imageHolder.transform); Image[] images = instantiatedPrefab.GetComponentsInChildren<Image>(); foreach (Image image in images) { Texture2D sourceTexture = image.sprite.texture; Sprite sprite = image.sprite; if (sprite != null) { Texture2D texture = sprite.texture; byte[] bytes = texture.EncodeToPNG(); File.WriteAllBytes(savePath + image.name + ".png", bytes); } } }else{Debug.Log("None of bundle");} } } ArgumentException: Texture 'intro_bg' is not readable. For this reason, scripts cannot access the memory allocated to it. You can make this texture readable in the Texture Import Settings. NewBehaviourScript2.Start () (at Assets/Scripts/NewBehaviourScript2.cs:33) Как исправить ошибку, если возможности переупаковать bundle у меня нет?
8e47b5a07d022973c7da6d736acc5c71
{ "intermediate": 0.6043888926506042, "beginner": 0.21199281513690948, "expert": 0.18361833691596985 }
32,198
I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is pwd.
e5991f766753df333c0523d58e42fb46
{ "intermediate": 0.32150977849960327, "beginner": 0.2609173655509949, "expert": 0.41757282614707947 }
32,199
loop through ever image in a folder, crop t hem with the following code: from PIL import Image img = Image.open("../../challenge_images/3d_rollball_animals/ff80a07e00fa7879.png") w, h = img.size if (w % 200) != 0 and (h % 200) != 0: print("sumn wrong 1") exit() if (h / 200) != 2: print("sumn wrong 2") exit() hand = img.crop((0, 200, 130, 400)).show() animals = [] for i in range(int(w / 200)): animals.append(img.crop((i*200, 0, (i+1)*200, 200))) after cropping you img.show() the hand plus the animal, then you put a yes/no input asaking if it matches, if i put y (yes) it will create a folder named with the hand images hash that you get with this code: import img_utils.hash_algo as hash_algo hash_algo.hash_image(Image.open(BytesIO(blah blah blah))) and put the animal image in there. after that you move onto the next image and crop it, and loop
32ef45afe90f7a79ca840f0feea46072
{ "intermediate": 0.37392300367355347, "beginner": 0.3736051619052887, "expert": 0.2524718940258026 }
32,200
lscpu
fafcc3e4b2a2f689141f3683265b3ee2
{ "intermediate": 0.3270229995250702, "beginner": 0.33785420656204224, "expert": 0.3351227939128876 }
32,201
I used this code: mark_price_data = client.ticker_price(symbol=symbol) mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol) mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0 # Retrieve depth data depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] bid_prices = [float(bid[0]) for bid in bids] highest_bid_price = max(bid_prices) lowest_bid_price = min(bid_prices) b_h = highest_bid_price b_l = lowest_bid_price asks = depth_data['asks'] ask_prices = [float(ask[0]) for ask in asks] highest_ask_price = max(ask_prices) lowest_ask_price = min(ask_prices) s_h = highest_ask_price s_l = lowest_ask_price You need to give me code which will print me buy_lowest_price which not lower than mark_price + (mark_price / 100) and highest_sell_price which not higher than mark_price - (mark_price / 100)
cc052db75b63bf81f85af67c144c8f75
{ "intermediate": 0.4654114544391632, "beginner": 0.3037894070148468, "expert": 0.23079919815063477 }
32,202
make a fanf 2 text based game
182687b0118b0f56cfb51249d63cf275
{ "intermediate": 0.3590414226055145, "beginner": 0.37483373284339905, "expert": 0.2661248743534088 }
32,203
make a fanf 1 game phyton with gui
004f57195ac2d3834fcf85be1c0527c1
{ "intermediate": 0.3535096049308777, "beginner": 0.3344379663467407, "expert": 0.3120524287223816 }
32,204
Have a look at the following pseudo code. Please convert it to C to the best of your abilities. def gmlp_block(x, d_model, d_ffn): shortcut = x x = norm(x, axis="channel") x = proj(x, d_ffn, axis="channel") x = gelu(x) x = spatial_gating_unit(x) x = proj(x, d_model, axis="channel") return x + shortcut def spatial_gating_unit(x): u, v = split(x, axis="channel") v = norm(v, axis="channel") n = get_dim(v, axis="spatial") v = proj(v, n, axis="spatial", init_bias=1) return u * v
dc47dd2831ff60ec980ade2828b759fa
{ "intermediate": 0.27530741691589355, "beginner": 0.4350242018699646, "expert": 0.28966838121414185 }
32,205
I want you to simulate a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal . . Do not type commands unless I instruct you to do so. When I need to tell you something in English I will do so by putting text inside curly brackets {like this}. My first command is pwd.
5f9ca4962ae38de67e7d59dcf654828c
{ "intermediate": 0.3170722424983978, "beginner": 0.32523593306541443, "expert": 0.35769185423851013 }
32,206
can you create a CNN BiLSTM attention BiLSTM time series forecasting model with train test and validation sets. assume a random dataset
b06fb83277e148af52aa61d454452ae8
{ "intermediate": 0.24008053541183472, "beginner": 0.14789828658103943, "expert": 0.6120211482048035 }
32,207
In a wxwidgets c++ project, I have a wxArrayString with list of different categories, and I have another wxArrayString which contains elements of each category. I want to create a new wxArrayString with the category and its elements count, and this format of "[count] category", how can I achieve this?
c1b6e034b0c420cb1fdb1d8d8b46309b
{ "intermediate": 0.6808833479881287, "beginner": 0.12438804656267166, "expert": 0.19472858309745789 }
32,208
c sharp coding for quiz game
4e4f670f89e1ffe66fa59995c49c043f
{ "intermediate": 0.3079853057861328, "beginner": 0.502452552318573, "expert": 0.189562126994133 }
32,209
Please re-send the last message
42f2635126d75a328af072091af3a10e
{ "intermediate": 0.3108157813549042, "beginner": 0.27290207147598267, "expert": 0.41628211736679077 }
32,210
c sharp coding for finding picture name
b24aed77b7b98dc32a55d1ccdda5a95d
{ "intermediate": 0.19220207631587982, "beginner": 0.4121882915496826, "expert": 0.39560961723327637 }
32,211
Write a program that uses the X window system to display a pixel array of 'uint8_t's.
501a358ed1c7bed208392df902c9bba5
{ "intermediate": 0.38308024406433105, "beginner": 0.25262513756752014, "expert": 0.36429455876350403 }
32,212
write this for me to one file: 1. Setting Up the Project: - Open Godot 4 and create a new project. - Add a new 2D scene and save it (this will be the main scene for your automaton). 2. Creating the Script: - Attach a new script to the main node of your 2D scene. - Define the parameters of your cellular automaton such as the size of the grid and the rules for cell evolution. 3. Initialization: - Initialize a two-dimensional array to represent the grid of cells. Each cell will have a state (for example, alive or dead). var grid_size = Vector2(50, 50) # Change to desired grid size var cell_size = 10 # Change to the size of each cell in pixels var grid = [] func _ready(): initialize_grid() update_grid() func initialize_grid(): grid = [] for y in range(grid_size.y): var row = [] for x in range(grid_size.x): row.append(randi() % 2) # Randomly set initial state to 0 or 1 grid.append(row) func update_grid(): var new_grid = [] # Apply rules and update new grid… # This is where you’ll implement the logic based on cellular automata rules grid = new_grid draw_grid() 4. Drawing the Grid: - Use a draw function or a TileMap to visualize the grid. func draw_grid(): # Clear any previous drawing update() func _draw(): for y in range(grid_size.y): for x in range(grid_size.x): var color = grid[y][x] == 1 ? Color(1, 1, 1) : Color(0, 0, 0) draw_rect(Rect2(Vector2(x, y) * cell_size, Vector2(cell_size, cell_size)), color) 5. Implementing the Rules: - In the update_grid function, implement the automaton’s rule. For example, you might use Conway’s Game of Life rules. func get_cell(x, y): if x < 0 or x >= grid_size.x or y < 0 or y >= grid_size.y: return 0 return grid[y][x] func count_neighbors(x, y): var count = 0 for i in range(-1, 2): for j in range(-1, 2): if i == 0 and j == 0: continue count += get_cell(x + i, y + j) return count func update_grid(): # Copy the grid to avoid modifying it while reading var new_grid = [] for y in range(grid_size.y): new_grid.append(grid[y].duplicate()) for y in range(grid_size.y): for x in range(grid_size.x): var neighbors = count_neighbors(x, y) # Implement Conway’s Game of Life rules or similar if grid[y][x] == 1 and (neighbors < 2 or neighbors > 3): new_grid[y][x] = 0 # Cell dies elif grid[y][x] == 0 and neighbors == 3: new_grid[y][x] = 1 # Cell becomes alive grid = new_grid draw_grid() 6. Adding Interactivity: - To make the automaton evolve, use a timer or the _process function to periodically call the update_grid method. var update_rate = 0.5 # Seconds func _ready(): # Rest of the initialization code… var timer = Timer.new() timer.set_wait_time(update_rate) timer.set_one_shot(false) timer.connect(“timeout”, self, “update_grid”) add_child(timer) timer.start() 7. Testing: - Run the scene and observe the behavior of the cellular automaton. Keep in mind that this is a simple example and you may want to expand on it. You can create more complex rules, optimize the rendering by using a TileMap, or even use shaders for drawing. Remember to adjust grid_size, cell_
ea4b1ad063c5483911ad683f78a66267
{ "intermediate": 0.32750216126441956, "beginner": 0.4385395348072052, "expert": 0.23395833373069763 }
32,213
Сделай красивую навигацию в css: <div id="header"></div> <div class="mobile-menu-open-button js_mobile_menu_open_button"><i class="fas fa-bars"></i></div> <nav class="js_wide_menu"> <i class="fas fa-times close-mobile-menu js_close_mobile_menu"></i> <div class="wrapper-inside"> <div class="visible-elements"> <a class="links_nav" href="index.php">Главная</a> <a class="links_nav" href="index.php">Поиск</a> <a class="links_nav" href="index.php">Войти</a> <a class="links_nav" href="corzina.php">Корзина</a> </div> </div> </nav>
0a87a9778d2bfe3a5d053dabf1c8681b
{ "intermediate": 0.36878085136413574, "beginner": 0.296745628118515, "expert": 0.33447355031967163 }
32,214
сделай красиво навигационное меню в css <div id="header"></div> <div class="mobile-menu-open-button js_mobile_menu_open_button"><i class="fas fa-bars"></i></div> <nav class="js_wide_menu"> <i class="fas fa-times close-mobile-menu js_close_mobile_menu"></i> <div class="wrapper-inside"> <div class="visible-elements"> <a class="links_nav" href="index.php">Главная</a> <a class="links_nav" href="index.php">Поиск</a> <a class="links_nav" href="index.php">Войти</a> <a class="links_nav" href="corzina.php">Корзина</a> </div> </div> </nav>
3549dfd39d4126331a50c1e70d1eddf6
{ "intermediate": 0.39369770884513855, "beginner": 0.3046836853027344, "expert": 0.3016186058521271 }
32,215
I sued this code: # Retrieve depth data depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] bid_prices = [float(bid[0]) for bid in bids] highest_bid_price = max(bid_prices) lowest_bid_price = min(bid_prices) buy_lowest_price = 0 for bid_price in bid_prices: if bid_price > mp + (mp / 100): buy_lowest_price = bid_price break if buy_lowest_price == 0: buy_lowest_price = mp + (mp / 100) b_h = highest_bid_price b_l = buy_lowest_price asks = depth_data['asks'] ask_prices = [float(ask[0]) for ask in asks] highest_ask_price = max(ask_prices) lowest_ask_price = min(ask_prices) sell_highest_price = 0.0 for ask_price in ask_prices: if ask_price < mp - (mp / 100): sell_highest_price = ask_price break if sell_highest_price == 0: sell_highest_price = mp - (mp / 100) s_h = highest_ask_price s_l = lowest_ask_price Can you add in buy_lowest_price and in sell_highest_price that if buy_lowest_price < mp + (mp / 100 ) it need to subtract qty of this bid and same system for ask
3162ab267f5c55b786948d2a51f8bcc2
{ "intermediate": 0.4004254639148712, "beginner": 0.25442004203796387, "expert": 0.3451545238494873 }
32,216
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)) how to take output from this code and input in to the below code from transformers import BertTokenizer, TFBertModel import numpy as np import pandas as pd from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, Bidirectional, LSTM, Dense # Load BERT tokenizer and model tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') bert_model = TFBertModel.from_pretrained('bert-base-uncased') # Load Quora dataset quora_data = pd.read_csv('questions_test.csv',nrows=100) # Select a subset of the dataset for training train_data = quora_data.sample(n=80) # Adjust the number of samples based on your requirements # Convert the question pairs to list format question1_list = list(train_data['question1']) question2_list = list(train_data['question2']) # Tokenize and convert sentences to BERT inputs max_len = 25 # Define the maximum length for padding/truncating encoded_inputs = tokenizer(question1_list, question2_list, padding=True, truncation=True, max_length=max_len, return_tensors='tf' ) #attention_mask = encoded_inputs['attention_mask'] # Get BERT embeddings #outputs = bert_model(input_ids, attention_mask=attention_mask) #embeddings = outputs[0] # Shape: (num_samples, max_len, 768) #outputs = bert_model(encoded_inputs.input_ids, attention_mask=encoded_inputs.attention_mask) #embeddings = outputs.last_hidden_state # Shape: (num_samples, max_len, 768) inputs = { 'input_ids': encoded_inputs['input_ids'], 'attention_mask': encoded_inputs['attention_mask'] } outputs = bert_model(inputs) embeddings = outputs.last_hidden_state # Shape: (num_samples, max_len, 768) # Define Bi-LSTM model model = Sequential() model.add(Bidirectional(LSTM(64, return_sequences=True), input_shape=(max_len, 768))) model.add(Bidirectional(LSTM(64))) model.add(Dense(1, activation='sigmoid')) # Compile the model model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Prepare labels for training labels = np.array(train_data['is_duplicate']) # Assuming the dataset has a “is_duplicate” column indicating similarity/dissimilarity # Train the model model.fit(embeddings, labels, epochs=10) #question1_list = list(test_data['question1']) #question2_list = list(test_data['question2']) # Load test data and preprocess test_data = quora_data.sample(n=20) # Adjust the number of samples for testing encoded_test = tokenizer(list(test_data['question1']), list(test_data['question2']), padding=True, truncation=True, max_length=max_len, return_tensors='tf') test_input_ids = encoded_test['input_ids'] test_attention_mask = encoded_test['attention_mask'] # Get BERT embeddings for test data test_outputs = bert_model(test_input_ids, attention_mask=test_attention_mask) test_embeddings = test_outputs[0] # Shape: (num_samples, max_len, 768) # Make predictions on test data predictions = model.predict(test_embeddings) # Print test predictions for i, pred in enumerate(predictions): print(f"Question 1: {test_data.iloc[i]['question1']}") print(f"Question 2: {test_data.iloc[i]['question2']}") print(f"Similarity Prediction: {pred}") print()
61305cff1cb973298dfd0909001c8965
{ "intermediate": 0.4840421974658966, "beginner": 0.3515419363975525, "expert": 0.16441592574119568 }
32,217
I have this code: mark_price_data = client.ticker_price(symbol=symbol) mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol) mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0 # Retrieve depth data depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] bid_prices = [float(bid[0]) for bid in bids] highest_bid_price = max(bid_prices) lowest_bid_price = min(bid_prices) buy_lowest_price = 0 for bid_price in bid_prices: if bid_price > mp + (mp / 100): buy_lowest_price = bid_price break if buy_lowest_price == 0: buy_lowest_price = lowest_bid_price > mp + (mp / 100) b_h = highest_bid_price b_l = buy_lowest_price asks = depth_data['asks'] ask_prices = [float(ask[0]) for ask in asks] highest_ask_price = max(ask_prices) lowest_ask_price = min(ask_prices) sell_highest_price = 0.0 for ask_price in ask_prices: if ask_price < mp - (mp / 100): sell_highest_price = ask_price break if sell_highest_price == 0: sell_highest_price = mp - (mp / 100) s_h = highest_ask_price s_l = lowest_ask_price #Quantity for bid in bids: price_buy = float(bid[0]) qty_buy = float(bid[1]) if price_buy > mark_price: buy_qty = (price_buy, qty_buy) print(buy_qty) for ask in asks: price_sell = float(ask[0]) qty_sell = float(ask[1]) if price_sell < mark_price: sell_qty = (price_sell, qty_sell) print(sell_qty) print(mark_price) But it returning me:Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 252, in <module> signals = signal_generator(df) ^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 158, in signal_generator if price_buy == mark_price and buy_qty is not None: ^^^^^^^ UnboundLocalError: cannot access local variable 'buy_qty' where it is not associated with a value
fdb5c31f5f319147a37ba8192a1e7004
{ "intermediate": 0.38989531993865967, "beginner": 0.4627770483493805, "expert": 0.14732760190963745 }
32,218
in wxwidgets c++ project, how to pin rows in wxgrid? I know it can be done with freezeto but I want to be able to pin any number of rows in any position, for example, pinning the first and the third but not the second.
7367f9da8597bc9e3e2f2bf0528c53ae
{ "intermediate": 0.7761234641075134, "beginner": 0.07899416983127594, "expert": 0.14488238096237183 }
32,219
Got the same error: ValueError: With n_samples=0, test_size=0.2 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters. The error occurs because of that the Data file is not found. In case you are using jupyter notebook you cannot used the Dataframe for defining X and y. So, using the dataframe to define x and y the problem is solved. In other case, it occurs due to it can't find the data. So check in the given path the data is exist
23a1e600ad7f57678835fb5861b7e9fa
{ "intermediate": 0.5431904792785645, "beginner": 0.14216817915439606, "expert": 0.31464138627052307 }
32,220
str.maketrans how does it work
ad0434a1b5130215536c8f442279b9fa
{ "intermediate": 0.29793059825897217, "beginner": 0.27565789222717285, "expert": 0.426411509513855 }
32,221
what is green?
63e429dfe76a78fdc741cae3491ee53c
{ "intermediate": 0.39008629322052, "beginner": 0.3170086443424225, "expert": 0.2929050624370575 }