row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
2,407
I need an android app that can run a python script for me, that is capable of file creation and file system manipulation as well
9065c310dc29dc0df292b8859eb928e8
{ "intermediate": 0.7604069113731384, "beginner": 0.0795740932226181, "expert": 0.16001901030540466 }
2,408
flutter import function
2a22899ad553490f1019b20b01fcdbd9
{ "intermediate": 0.39437901973724365, "beginner": 0.3508596420288086, "expert": 0.254761278629303 }
2,409
I need you to create me a merging by transformation function which will merge images using the already calculated homography matrix. Do not use OpenCV or any other library other than NumPy. Make sure the function is runtime-friendly meaning provides a good (short) runtime while keeping memory usage low. Add comments to each line describing what you are doing. "Merging by Transformation: Merge sub-images into a single panorama by applying transformation operations to sub-images using the Homography Matrix. For this part, you cannot use OpenCV or any library other than NumPy."
a7a260dbc96a5d43519caf97be142cfa
{ "intermediate": 0.49806058406829834, "beginner": 0.12728121876716614, "expert": 0.3746581971645355 }
2,410
Introduction about spacy NLP library
955873b11ef50941b775e08fc079ffc6
{ "intermediate": 0.32015955448150635, "beginner": 0.3315314054489136, "expert": 0.3483090400695801 }
2,411
can you write matlab code that will use the intelligent driver model to simulate traffic flow on a single road lane with cars of different length and animate the results make sure that any array you use ./ operator with have the same size
1aea77067eec979529fa63a642b57004
{ "intermediate": 0.17521800100803375, "beginner": 0.056735169142484665, "expert": 0.7680468559265137 }
2,412
can you write matlab code that will use the intelligent driver model to simulate traffic flow on a single road lane with cars of different length and animate the results make sure that any array you use ./ operator with have the same size
0201906048dc8ae95f21a9c253857605
{ "intermediate": 0.17521800100803375, "beginner": 0.056735169142484665, "expert": 0.7680468559265137 }
2,413
do you know how to write a nodejs script to check if two typescript interface are compatible?
928bde2e442e46ada322166851816b40
{ "intermediate": 0.556293785572052, "beginner": 0.27808740735054016, "expert": 0.16561882197856903 }
2,414
how to disable alert bo after filling the fieldss in form in jquwry
77d01aa55b60bdc72f74b16c356ca02d
{ "intermediate": 0.40142694115638733, "beginner": 0.22783413529396057, "expert": 0.3707389235496521 }
2,415
can you write matlab code that will use the intelligent driver model to simulate traffic flow on a single road lane with cars of different length and width in such a way that they do not collide and animate the results
f2058e0ce2b89357003f78307534de6c
{ "intermediate": 0.10933841019868851, "beginner": 0.04707745462656021, "expert": 0.8435841202735901 }
2,416
how can we detect bounce of ball when we have ball and racket object detection model
7f61da7ec24e1e953c2f3fb9a0449fa6
{ "intermediate": 0.2659565210342407, "beginner": 0.1491871327161789, "expert": 0.5848562717437744 }
2,417
can you write matlab code that will use the intelligent driver model to simulate traffic flow on a single road lane with cars of different length and width in such a way that they do not collide and animate the results make sure that the code is free from syntax errors also no logical error can appear
9728bc1beb0722db3122a5f514c967e1
{ "intermediate": 0.06533578783273697, "beginner": 0.10050435364246368, "expert": 0.8341599106788635 }
2,418
how to diable alert box after filling fileds in jqueery unbind() is nt working'
a237552078d8a46c89e3e0e7d5472728
{ "intermediate": 0.5158791542053223, "beginner": 0.18484948575496674, "expert": 0.2992713749408722 }
2,419
Will you please write a c# .net function to embed primitives from drawing (given List<EntityGeometry> entityGeometry) using Multicad .NET API in nanoCAD application and draw it into McTable's cell specified by row and column index.
17d7cb454c5dc9f6317e2246a647504f
{ "intermediate": 0.8272944688796997, "beginner": 0.09046447277069092, "expert": 0.08224102109670639 }
2,420
error: use of undeclared identifier 'AudioContext'
6cf59460d19e560c354d7540c118ff95
{ "intermediate": 0.3802863359451294, "beginner": 0.29088184237480164, "expert": 0.3288317918777466 }
2,421
Hi, write me please a c# method for reading path from a file, the move directory with a file and save new path to file
5041e4c9c107c63f1c57075bea88b955
{ "intermediate": 0.63698410987854, "beginner": 0.1582646518945694, "expert": 0.20475123822689056 }
2,422
how to detect bounce of ball using optimisation
7fba65d6f1e616bbb7cdd322d81952e5
{ "intermediate": 0.10663171112537384, "beginner": 0.1067020520567894, "expert": 0.786666214466095 }
2,423
scan local drive c and store directory structure metadata into sqlite using c++ under windows,column include id name parent_id level is_dir size etc,and support add file,remove file,add directory,remove directory,get file’s size, get directory’s size,delete directory recursively from database
25bf418fd0b77e77c4de597e1e631497
{ "intermediate": 0.5973146557807922, "beginner": 0.15857388079166412, "expert": 0.24411147832870483 }
2,424
first i don everthing models views and templates adn done migrations and later all after i craeted supr user admin but if i go into admin i did not see my model tables what to do now
0a4cc530c7f82b21a7e1e8b59d2b749c
{ "intermediate": 0.3496339023113251, "beginner": 0.32341623306274414, "expert": 0.3269498646259308 }
2,425
write matlab code that will use the intelligent driver model to simulate traffic flow on a single road lane with cars of different length and width in such a way that they do not collide and animate the results make sure that the code is free from syntax errors and there are no indices that exceed the number of array elements
f27b2bb8ddae7fea59039694d49c743a
{ "intermediate": 0.059390708804130554, "beginner": 0.1015811339020729, "expert": 0.8390281200408936 }
2,426
Hello, I'm making a final year project titled KAKEIBO - A PERSONAL SELF-HOSTED FINANCE MANAGEMENT APP Here are my modules User Authentication Income and Expense Tracking Budgets Debts Goals Group Budgeting and Shared Goals Report Statistics Bill Reminder Data Export Here are the description for income and expense tracking with crud functionality This module allows users to track their income and expenses by adding and categorising transactions. Create: Adding new income and expense transactions Read: Viewing the list of income and expenses transactions Update: Editing existing transactions Delete: Deleting transactions is there golang and htmx example of the modules
0f73b4c06511d8374a8760219ecf1a1e
{ "intermediate": 0.3915620744228363, "beginner": 0.32945895195007324, "expert": 0.2789789140224457 }
2,427
scan local drive c and store only file and directory inherit structure metadata into sqlite using c++17 under windows,database table column include id name parent_id level is_dir size etc,and support add file,remove file,add directory,remove directory,get file’s size, get directory’s size,delete directory recursively from database
8ab5027bcca5a2d3e57570d101e9004e
{ "intermediate": 0.47155120968818665, "beginner": 0.1789768934249878, "expert": 0.3494718670845032 }
2,428
File "/Users/surabhi/Documents/kalman/parabola.py", line 57, in <module> predicted, _ = kf.predict() ^^^^^^^^^^^^ TypeError: cannot unpack non-iterable NoneType object
ad12c10e9e37b88de832ceccc9ea6fb5
{ "intermediate": 0.3778766989707947, "beginner": 0.36646798253059387, "expert": 0.2556552588939667 }
2,429
how to do stratified COX regression in R software. Please provide examples with simulated data. thank you
d964fb5ab429feccc5954e484aa8dd4b
{ "intermediate": 0.19242948293685913, "beginner": 0.09187163412570953, "expert": 0.7156988382339478 }
2,430
code: import cv2 from filterpy.kalman import KalmanFilter from ultralytics import YOLO import numpy as np import pandas as pd from sktime.datatypes._panel._convert import from_2d_array_to_nested from pickle import load #import sktime.datatypes.check_raise #from sktime.datatypes._panel._concat import concat model = YOLO('/Users/surabhi/Documents/kalman/best.pt') kf = KalmanFilter(dim_x=4, dim_z=2) kf.x = np.array([0, 0, 0, 0]) # initial state estimate kf.P = np.eye(4) * 1000 # initial error covariance matrix kf.F = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]]) # state transition matrix kf.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) # measurement matrix kf.R = np.diag([0.1, 0.1]) # measurement noise covariance matrix kf.Q= np.diag([0.1, 0.1, 0.1, 0.1]) dt = 1.0 u = np.zeros((4, 1)) cap = cv2.VideoCapture("1_1.mp4") frame_num = 0 predicted_points = [] bounce_detected = False last_bounce_frame = -5 test_df = pd.DataFrame(columns=[ 'x', 'y', 'V']) while True: ret, frame = cap.read() if ret is False: break bbox = model(frame, show=True) frame_num += 1 for boxes_1 in bbox: result = boxes_1.boxes.xyxy if len(result) == 0: print("not detected") else: cx = int((result[0][0] + result[0][2]) / 2) cy = int((result[0][1] + result[0][3]) / 2) centroid = np.array([cx, cy]) kf.predict() kf.update(centroid) next_point = (kf.x).tolist() predicted_points.append((int(next_point[0]), int(next_point[1]))) V=np.sqrt(kf.x[2]**2 + kf.x[3]**2) test_df =test_df.append({'x': next_point[0], 'y': next_point[1],'V': V},ignore_index=True) print("test_df_final",test_df) if len(test_df['x'])>=20: for i in range(20, 0, -1): test_df[f'lagX_{i}'] = test_df['x'].shift(i, fill_value=0) for i in range(20, 0, -1): test_df[f'lagY_{i}'] = test_df['y'].shift(i, fill_value=0) for i in range(20, 0, -1): test_df[f'lagV_{i}'] = test_df['V'].shift(i, fill_value=0) print(test_df) test_df.drop(['x', 'y', 'V'], 1, inplace=True) Xs = test_df[['lagX_20', 'lagX_19', 'lagX_18', 'lagX_17', 'lagX_16', 'lagX_15', 'lagX_14', 'lagX_13', 'lagX_12', 'lagX_11', 'lagX_10', 'lagX_9', 'lagX_8', 'lagX_7', 'lagX_6', 'lagX_5', 'lagX_4', 'lagX_3', 'lagX_2', 'lagX_1']] Xs = from_2d_array_to_nested(Xs.to_numpy()) Ys = test_df[['lagY_20', 'lagY_19', 'lagY_18', 'lagY_17', 'lagY_16', 'lagY_15', 'lagY_14', 'lagY_13', 'lagY_12', 'lagY_11', 'lagY_10', 'lagY_9', 'lagY_8', 'lagY_7', 'lagY_6', 'lagY_5', 'lagY_4', 'lagY_3', 'lagY_2', 'lagY_1']] Ys = from_2d_array_to_nested(Ys.to_numpy()) Vs = test_df[['lagV_20', 'lagV_19', 'lagV_18', 'lagV_17', 'lagV_16', 'lagV_15', 'lagV_14', 'lagV_13', 'lagV_12', 'lagV_11', 'lagV_10', 'lagV_9', 'lagV_8', 'lagV_7', 'lagV_6', 'lagV_5', 'lagV_4', 'lagV_3', 'lagV_2', 'lagV_1']] Vs = from_2d_array_to_nested(Vs.to_numpy()) X = pd.concat([Xs, Ys, Vs], 0) print(X) print(X.columns.is_unique) #print(check_raise(df_train, mtype="pd-multiindex')) #print(sktime.datatypes.check_raise(X, mtype)) # load the pre-trained classifier clf = load(open('clf.pkl', 'rb')) predcted = clf.predict(X) idx = list(np.where(predcted == 1)[0]) idx = np.array(idx) - 10 test_df = pd.DataFrame(columns=[ 'x', 'y', 'V']) else: if len(predicted_points) > 10: predicted_points.pop(0) print("next_point", next_point) print("frame_number", frame_num) cv2.putText(frame, f'Frame: {frame_num}', (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) cv2.circle(frame, (cx, cy), 5, (0,0,255), 5) cv2.circle(frame, (int(next_point[0]), int(next_point[1])), 5, (255, 0, 0), 10) for i, p in enumerate(predicted_points): color = (255,255,255) cv2.circle(frame, p, 5, color, 2) if bounce_detected: cv2.putText(frame, 'Bounce Detected', (10, 350), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) if kf.x[3] > 0: # After a bounce is detected, wait until acceleration is above the threshold, say -5, to detect the bounce again bounce_detected = False # test_df_1=pd.DataFrame({'frame': frame_num , 'x': next_point[0], 'y':next_point[1], 'vx':vx,'vy':vy ,'V': V}, index=[0]) #test_df.concat(test_df_1) #test_df=pd.concat([test_df,test_df_1], ignore_index=True) #test_df.to_csv('file.csv') cv2.imshow('raw', frame) #test_df=pd.DataFrame() # test_df=pd.concat([test_df,test_df_1], ignore_index=True) # print(trajectory_df) #test_df.to_csv('file.csv') #test_df_1=pd.DataFrame({'frame': frame_num , 'x': next_point[0], 'y':next_point[1], 'vx':vx,'vy':vy ,'V': V}, index=[0]) # Uncomment the following lines to save the output video # out.write(frame) # if cv2.waitKey(1) & 0xFF == ord('q'): # break cap.release() cv2.destroyAllWindows() erroR: TypeError: X must be in an sktime compatible format, of scitype Series, Panel or Hierarchical, for instance a pandas.DataFrame with sktime compatible time indices, or with MultiIndex and last(-1) level an sktime compatible time index. Allowed compatible mtype format specifications are: ['pd.Series', 'pd.DataFrame', 'np.ndarray', 'nested_univ', 'numpy3D', 'pd-multiindex', 'df-list', 'pd_multiindex_hier'] . See the data format tutorial examples/AA_datatypes_and_datasets.ipynb. If you think the data is already in an sktime supported input format, run sktime.datatypes.check_raise(data, mtype) to diagnose the error, where mtype is the string of the type specification you want. Error message for checked mtypes, in format [mtype: message], as follows: [pd.DataFrame: X should not have column of 'object' dtype] [pd.Series: X must be a pandas.Series, found <class 'pandas.core.frame.DataFrame'>] [np.ndarray: X must be a numpy.ndarray, found <class 'pandas.core.frame.DataFrame'>] [df-list: X must be list of pd.DataFrame, found <class 'pandas.core.frame.DataFrame'>] [numpy3D: X must be a numpy.ndarray, found <class 'pandas.core.frame.DataFrame'>] [pd-multiindex: X must have a MultiIndex, found <class 'pandas.core.indexes.numeric.Int64Index'>] [nested_univ: The instance index of X must be unique, but found duplicates: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]] [pd_multiindex_hier: X must have a MultiIndex, found <class 'pandas.core.indexes.numeric.Int64Index'>]
a077c69b00805b04ae03f993cafe21d4
{ "intermediate": 0.33112531900405884, "beginner": 0.4800052344799042, "expert": 0.1888694167137146 }
2,431
so this script monitor the clipboard for any changes and automatically translate copied japanese text to english using gpt and then show the translation on a created window. can you make this script to not run shell and only the window instead? also make it to print any error on a new window import time import pyperclip import openai import json import tkinter as tk import threading import os from tkinter import font, Menu from tkinter import font # Set your OpenAI API key and base openai.api_base = "" openai.api_key = "" # Global variables pause_monitoring = False dark_mode = False # Storing prompt text prompt_logfile = "prompt_eiyuuou.txt" try: with open(prompt_logfile, "r", encoding="utf-8") as f: prompt_text = f.read() except FileNotFoundError: # If the log file doesn’t exist, use the default prompt text prompt_text = "Translate the following text: {text_to_translate}" # Keeping translation logs KEEP_LOGS = False translated_dict = {} jsonfile = "eiyuuou_translation.json" try: with open(jsonfile, "r", encoding="utf-8") as f: translated_dict = json.load(f) except FileNotFoundError: pass def translate_text(text_to_translate, prompt_template): prompt = prompt_template.format(text_to_translate=text_to_translate) completion = openai.ChatCompletion.create( model="gpt-3.5-turbo-0301", temperature=1, messages=[ { "role": "user", "content": f"{prompt}", } ], ) translated_text = ( completion["choices"][0] .get("message") .get("content") .encode("utf8") .decode() ) return translated_text def update_display(display, text): display.delete(1.0, tk.END) display.insert(tk.END, text) def retranslate(): untranslated_text = untranslated_textbox.get(1.0, tk.END).strip() if untranslated_text: pyperclip.copy(untranslated_text) def toggle_pause_monitoring(): global pause_monitoring pause_monitoring = not pause_monitoring pause_button.config( text="Resume" if pause_monitoring else "Pause", relief=tk.SUNKEN if pause_monitoring else tk.RAISED ) def clipboard_monitor(): global prompt_text old_clipboard = "" while True: if not pause_monitoring: new_clipboard = pyperclip.paste() # Remove line breaks from new_clipboard new_clipboard = new_clipboard.replace('\n', '').replace('\r', '') # Compare new_clipboard with old_clipboard to detect changes if new_clipboard != old_clipboard: old_clipboard = new_clipboard if new_clipboard in translated_dict: translated_text = translated_dict[new_clipboard] else: try: prompt_text = prompt_textbox.get(1.0, tk.END).strip() translated_text = translate_text(new_clipboard, prompt_text) except Exception as e: print(e, "Connection Error") continue translated_dict[new_clipboard] = translated_text if KEEP_LOGS: with open(jsonfile, "w", encoding="utf-8") as f: json.dump(translated_dict, f, ensure_ascii=False, indent=4) update_display(untranslated_textbox, new_clipboard) update_display(translated_textbox, translated_text) time.sleep(1) def toggle_translated(): current_bg = translated_textbox.cget("background") if current_bg == "black": translated_textbox.configure(background="white") translated_textbox.delete(1.0, tk.END) try: translated_textbox.insert(tk.END, translated_dict[untranslated_textbox.get(1.0, tk.END).strip()]) except Exception as e: pass toggle_button.config(text="Hide", relief=tk.RAISED) else: translated_textbox.configure(background="black") translated_textbox.delete(1.0, tk.END) toggle_button.config(text="Show", relief=tk.SUNKEN) def save_prompt(): global prompt_text current_prompt_text = prompt_textbox.get(1.0, tk.END).strip() if current_prompt_text != prompt_text: # Save any prompt_text changes to the log file prompt_text = current_prompt_text with open(prompt_logfile, "w", encoding="utf-8") as f: f.write(prompt_text) def set_always_on_top(): root.attributes("-topmost", always_on_top_var.get()) def increase_opacity(): opacity = root.attributes("-alpha") opacity = min(opacity + 0.1, 1.0) root.attributes("-alpha", opacity) def decrease_opacity(): opacity = root.attributes("-alpha") opacity = max(opacity - 0.1, 0.1) root.attributes("-alpha", opacity) def toggle_dark_mode(): global dark_mode dark_mode = not dark_mode bg_color = "black" if dark_mode else "white" fg_color = "white" if dark_mode else "black" untranslated_textbox.configure(bg=bg_color, fg=fg_color) translated_textbox.configure(bg=bg_color, fg=fg_color) prompt_textbox.configure(bg=bg_color, fg=fg_color) root.configure(bg=bg_color) options_menu.configure(bg=bg_color, fg=fg_color) menu_bar.configure(bg=bg_color, fg=fg_color) def font_window(): global current_font current_font = { "family": font.Font(font=untranslated_textbox["font"]).actual("family"), "size": font.Font(font=untranslated_textbox["font"]).actual("size"), "color": untranslated_textbox.cget("foreground") } font_window = tk.Toplevel() font_window.title("Font Settings") font_window.geometry("150x150") font_family = tk.StringVar() font_family_label = tk.Label(font_window, text="Font Family") font_family_label.pack() font_family_entry = tk.Entry(font_window, textvariable=font_family) font_family_entry.insert(0, current_font["family"]) font_family_entry.pack() font_size = tk.StringVar() font_size_label = tk.Label(font_window, text="Font Size") font_size_label.pack() font_size_entry = tk.Entry(font_window, textvariable=font_size) font_size_entry.insert(0, current_font["size"]) font_size_entry.pack() font_color = tk.StringVar() font_color_label = tk.Label(font_window, text="Font Color") font_color_label.pack() font_color_entry = tk.Entry(font_window, textvariable=font_color) font_color_entry.insert(0, current_font["color"]) font_color_entry.pack() def apply_changes(): new_font_family = font_family.get() or current_font["family"] new_font_size = font_size.get() or current_font["size"] new_font_color = font_color.get() or current_font["color"] current_font = {"family": new_font_family, "size": new_font_size, "color": new_font_color} untranslated_textbox.configure(font=(current_font["family"], current_font["size"]), fg=current_font["color"]) translated_textbox.configure(font=(current_font["family"], current_font["size"]), fg=current_font["color"]) font_window.destroy() apply_button = tk.Button(font_window, text="Apply", command=apply_changes) apply_button.pack() cancel_button = tk.Button(font_window, text="Cancel", command=font_window.destroy) cancel_button.pack() root = tk.Tk() root.title("Clipboard Translator") root.geometry("400x200") menu_bar = Menu(root) # Add Options menu options_menu = Menu(menu_bar, tearoff=0) menu_bar.add_cascade(label="Options", menu=options_menu) options_menu.add_command(label="Save Prompt", command=save_prompt) always_on_top_var = tk.BooleanVar(value=False) options_menu.add_checkbutton(label="Always on top", variable=always_on_top_var, command=set_always_on_top) dark_mode_var = tk.BooleanVar(value=False) options_menu.add_checkbutton(label="Dark Mode", variable=dark_mode_var, command=toggle_dark_mode) options_menu.add_command(label="Increase opacity", command=increase_opacity) options_menu.add_command(label="Decrease opacity", command=decrease_opacity) options_menu.add_command(label="Font", command=font_window) root.config(menu=menu_bar) paned_window = tk.PanedWindow(root, sashrelief="groove", sashwidth=5, orient="horizontal") paned_window.pack(expand=True, fill="both") untranslated_textbox = tk.Text(paned_window, wrap="word") paned_window.add(untranslated_textbox) translated_textbox = tk.Text(paned_window, wrap="word") paned_window.add(translated_textbox) prompt_textbox = tk.Text(paned_window, wrap="word") paned_window.add(prompt_textbox) update_display(prompt_textbox, prompt_text) retranslate_button = tk.Button(root, text="Copy", command=retranslate) retranslate_button.place(relx=0, rely=1, anchor="sw") toggle_button = tk.Button(root, text="Hide", command=toggle_translated, relief=tk.RAISED) toggle_button.place(relx=0.5, rely=1, anchor="s") pause_button = tk.Button(root, text="Pause", command=toggle_pause_monitoring, relief=tk.RAISED) pause_button.place(relx=1, rely=1, anchor="se") if __name__ == "__main__": print("Starting Clipboard Translator…\n") clipboard_monitor_thread = threading.Thread(target=clipboard_monitor) clipboard_monitor_thread.start() root.mainloop()
bb514fcaba008e98d0e4724caaf18b82
{ "intermediate": 0.39191606640815735, "beginner": 0.3631168305873871, "expert": 0.24496717751026154 }
2,432
c++ get all folders in a directory
4216352708a74270251995f9bb4707f4
{ "intermediate": 0.36295264959335327, "beginner": 0.2787165641784668, "expert": 0.3583308160305023 }
2,433
I'm using the android app, dcoder. I need help finding where I can use pip to install beautifulsoup so my script will function
ff870c3f3a69fcd93d164f417524baee
{ "intermediate": 0.6688749194145203, "beginner": 0.11335539817810059, "expert": 0.21776963770389557 }
2,434
write me a function to find all folders in a directory. this function should be cross platform and do not depend on third party lib
561a94817d0ac28c71f4d0cdfc8d4900
{ "intermediate": 0.6755535006523132, "beginner": 0.1549360454082489, "expert": 0.16951048374176025 }
2,435
In pytorch how do i declare layers in a loop in the init of a model?
ba36fbb640d39f6d8cf2c1ba1bdb144e
{ "intermediate": 0.23026813566684723, "beginner": 0.38746699690818787, "expert": 0.3822648823261261 }
2,436
I have 5 variables, each with 1000 numeric records. I want to draw the density plot of each variable and put these 5 density plot in one plot, how to do that in R software? Please provide example with simulated data.
c4144bdcfa1b73e99ffc034a0aeeada2
{ "intermediate": 0.4723561108112335, "beginner": 0.16436919569969177, "expert": 0.3632747530937195 }
2,437
I'm using AutoCad 2022 .net api. Write a program that gets a dynamic block name from user then creates a new layout and zooms veiwport to that block.
52fc6e489efe8559704f2e75f3d7c973
{ "intermediate": 0.7110759019851685, "beginner": 0.08298299461603165, "expert": 0.2059410810470581 }
2,438
in ggplot2, how to add a title to the plot and make the text of the title bigger and bold, and centralize it in the top middle of the plot?
033a1c51b62171aeadb37026a20f803f
{ "intermediate": 0.40576452016830444, "beginner": 0.2616223692893982, "expert": 0.3326130509376526 }
2,439
In pytorch how do I remove the leftmost dimension off a tensor such that the values are averaged instead of being concatenated?
9c1b7fcf5ee829d2b7851b855508a7bc
{ "intermediate": 0.37552568316459656, "beginner": 0.10214909166097641, "expert": 0.5223252773284912 }
2,440
What happens if I do this: sum([torch.rand(2,3,4) for _ in range(5)])
80c783c8aa935006bd5f176b2650689f
{ "intermediate": 0.2525365948677063, "beginner": 0.4802463948726654, "expert": 0.2672170102596283 }
2,441
python在子进程中使用multiprocessing.Manager().dict() 时会报错FileNotFoundError: [Errno 2] No such file or directory 怎么解决
f3de82fdc6176401c5fddef2c431447c
{ "intermediate": 0.39472338557243347, "beginner": 0.3542572259902954, "expert": 0.2510194182395935 }
2,442
import {useCallback, useEffect, useReducer, useState} from "react"; import {useDispatch} from "react-redux"; import {setFuturesBinancePriceState, setSpotBinancePriceState} from "../store/binancePriceSlice"; export enum ReadyState { UNINSTANTIATED = -1, CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3, } export function useBinancePrice() { const stream = "@ticker"; const dispatch = useDispatch(); const [futuresWs, setFuturesWs] = useState<WebSocket|null>(null); const [futuresReadyState, setFuturesReadyState] = useState(ReadyState.UNINSTANTIATED); const [spotWs, setSpotWs] = useState<WebSocket|null>(null); const [spotReadyState, setSpotReadyState] = useState(0); console.log(spotWs); const connectToWs = () => { if ("undefined" === typeof window) { setTimeout("connectToWs", 1000); return; } setFuturesWs(new WebSocket("wss://fstream.binance.com/stream")); setSpotWs(new WebSocket("wss://stream.binance.com:9443/stream")); }; const futuresSubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "SUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [futuresReadyState]); const futuresUnsubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "UNSUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [futuresReadyState]); useEffect(() => { if (null === futuresWs) return; futuresWs.onmessage = (message: MessageEvent) => { if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; // console.log(data.stream); dispatch(setFuturesBinancePriceState({symbol: data.stream.replace(stream, ""), price: data.data.c})); }; futuresWs.onopen = () => { setFuturesReadyState(ReadyState.OPEN); }; futuresWs.onclose = () => { setFuturesReadyState(ReadyState.CLOSED); }; }, [futuresWs, futuresWs, stream]); const spotSubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "SUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [spotReadyState]); const spotUnsubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "UNSUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [spotReadyState]); useEffect(() => { if (null === spotWs) return; spotWs.onmessage = (message: MessageEvent) => { console.log(message); if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setSpotBinancePriceState({symbol: data.stream.replace(stream, ""), price: data.data.c})); }; spotWs.onopen = () => { setSpotReadyState(ReadyState.OPEN); }; spotWs.onclose = () => { setSpotReadyState(ReadyState.CLOSED); }; }, [spotWs]); useEffect(() => { connectToWs(); }, []); return { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, }; } import {createSlice} from "@reduxjs/toolkit"; import {HYDRATE} from "next-redux-wrapper"; export interface BinancePriceSlice { futures: {[key: string]: number}; spot: {[key: string]: number}; } const initialState: BinancePriceSlice = { futures: {}, spot: {}, }; export const binancePriceSlice = createSlice({ name: "binancePrice", initialState, reducers: { setFuturesBinancePriceState(state, action) { state.futures[action.payload.symbol] = action.payload.price; }, setSpotBinancePriceState(state, action) { console.log(action); state.spot[action.payload.symbol] = action.payload.price; }, }, extraReducers: { [HYDRATE]: (state, action) => { return { ...state, ...action.payload, }; }, }, }); export const { setFuturesBinancePriceState, setSpotBinancePriceState, } = binancePriceSlice.actions; export default binancePriceSlice.reducer; import {BinanceWsProviderProps} from "./BinanceWsProvider.props"; import {ReadyState, useBinancePrice} from "../../hooks/binancePrices"; import {createContext, useContext, useEffect, useState} from "react"; interface BinanceWsProviderContext { futuresSubscribe: (symbol: string) => void; futuresUnsubscribe: (symbol: string) => void; futuresReadyState: number; spotSubscribe: (symbol: string) => void; spotUnsubscribe: (symbol: string) => void; spotReadyState: number; } const defaultContextValue: BinanceWsProviderContext = { futuresSubscribe: (symbol: string) => {}, futuresUnsubscribe: (symbol: string) => {}, futuresReadyState: 0, spotSubscribe: (symbol: string) => {}, spotUnsubscribe: (symbol: string) => {}, spotReadyState: 0, }; const Context = createContext(defaultContextValue); export function useBinanceWsProvider() { return useContext(Context); } const BinanceWsProvider = ({children}: BinanceWsProviderProps) => { const [futuresSymbols, setFuturesSymbols] = useState<Array<string>>([]); const [futuresQueue, setFuturesQueue] = useState<Array<string>>([]); const [spotSymbols, setSpotSymbols] = useState<Array<string>>([]); const [spotQueue, setSpotQueue] = useState<Array<string>>([]); const { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, } = useBinancePrice(); const futuresSymbolSubscribe = (symbol: string) => { if (futuresSymbols.includes(symbol) || futuresQueue.includes(symbol)) return; setFuturesQueue(prev => [...prev, symbol]); }; const futuresSymbolUnsubscribe = (symbol: string) => { if (!futuresSymbols.includes(symbol) && !futuresQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // futuresUnsubscribe(symbol); setFuturesQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromFuturesQueue = () => { futuresQueue.forEach(symbol => { futuresSubscribe(symbol); }); setFuturesSymbols([...futuresSymbols, ...futuresQueue]); setFuturesQueue([]); }; useEffect(() => { if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresQueue]); useEffect(() => { if (futuresReadyState === ReadyState.CLOSED) { setFuturesQueue([...futuresSymbols, ...futuresQueue]); setFuturesSymbols([]); } if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresReadyState]); const spotSymbolSubscribe = (symbol: string) => { if (spotSymbols.includes(symbol) || spotQueue.includes(symbol)) return; setSpotQueue(prev => [...prev, symbol]); }; const spotSymbolUnsubscribe = (symbol: string) => { if (!spotSymbols.includes(symbol) && !spotQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // spotUnsubscribe(symbol); setSpotQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromSpotQueue = () => { spotQueue.forEach(symbol => { spotSubscribe(symbol); }); setSpotSymbols([...spotSymbols, ...spotQueue]); setSpotQueue([]); }; useEffect(() => { if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotQueue]); useEffect(() => { if (spotReadyState === ReadyState.CLOSED) { setSpotQueue([...spotSymbols, ...spotQueue]); setSpotSymbols([]); } if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotReadyState]); return <Context.Provider value={{ futuresSubscribe: futuresSymbolSubscribe, futuresUnsubscribe: futuresSymbolUnsubscribe, futuresReadyState: futuresReadyState, spotSubscribe: spotSymbolSubscribe, spotUnsubscribe: spotSymbolUnsubscribe, spotReadyState: spotReadyState, }} > {children} </Context.Provider>; }; export default BinanceWsProvider; Надо разобраться с подключением к вебсокетам бинанса на фронте. Они через раз срабатывают
6a56338b7483a1b1dee319868ed1c443
{ "intermediate": 0.2588977813720703, "beginner": 0.5742343068122864, "expert": 0.1668679267168045 }
2,443
import {BinanceWsProviderProps} from "./BinanceWsProvider.props"; import {ReadyState, useBinancePrice} from "../../hooks/binancePrices"; import {createContext, useContext, useEffect, useState} from "react"; interface BinanceWsProviderContext { futuresSubscribe: (symbol: string) => void; futuresUnsubscribe: (symbol: string) => void; futuresReadyState: number; spotSubscribe: (symbol: string) => void; spotUnsubscribe: (symbol: string) => void; spotReadyState: number; } const defaultContextValue: BinanceWsProviderContext = { futuresSubscribe: (symbol: string) => {}, futuresUnsubscribe: (symbol: string) => {}, futuresReadyState: 0, spotSubscribe: (symbol: string) => {}, spotUnsubscribe: (symbol: string) => {}, spotReadyState: 0, }; const Context = createContext(defaultContextValue); export function useBinanceWsProvider() { return useContext(Context); } const BinanceWsProvider = ({children}: BinanceWsProviderProps) => { const [futuresSymbols, setFuturesSymbols] = useState<Array<string>>([]); const [futuresQueue, setFuturesQueue] = useState<Array<string>>([]); const [spotSymbols, setSpotSymbols] = useState<Array<string>>([]); const [spotQueue, setSpotQueue] = useState<Array<string>>([]); const { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, } = useBinancePrice(); const futuresSymbolSubscribe = (symbol: string) => { if (futuresSymbols.includes(symbol) || futuresQueue.includes(symbol)) return; setFuturesQueue(prev => [...prev, symbol]); }; const futuresSymbolUnsubscribe = (symbol: string) => { if (!futuresSymbols.includes(symbol) && !futuresQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // futuresUnsubscribe(symbol); setFuturesQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromFuturesQueue = () => { futuresQueue.forEach(symbol => { futuresSubscribe(symbol); }); setFuturesSymbols([...futuresSymbols, ...futuresQueue]); setFuturesQueue([]); }; useEffect(() => { if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresQueue]); useEffect(() => { if (futuresReadyState === ReadyState.CLOSED) { setFuturesQueue([...futuresSymbols, ...futuresQueue]); setFuturesSymbols([]); } if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresReadyState]); const spotSymbolSubscribe = (symbol: string) => { if (spotSymbols.includes(symbol) || spotQueue.includes(symbol)) return; setSpotQueue(prev => [...prev, symbol]); }; const spotSymbolUnsubscribe = (symbol: string) => { if (!spotSymbols.includes(symbol) && !spotQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // spotUnsubscribe(symbol); setSpotQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromSpotQueue = () => { spotQueue.forEach(symbol => { spotSubscribe(symbol); }); setSpotSymbols([...spotSymbols, ...spotQueue]); setSpotQueue([]); }; useEffect(() => { if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotQueue]); useEffect(() => { if (spotReadyState === ReadyState.CLOSED) { setSpotQueue([...spotSymbols, ...spotQueue]); setSpotSymbols([]); } if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotReadyState]); return <Context.Provider value={{ futuresSubscribe: futuresSymbolSubscribe, futuresUnsubscribe: futuresSymbolUnsubscribe, futuresReadyState: futuresReadyState, spotSubscribe: spotSymbolSubscribe, spotUnsubscribe: spotSymbolUnsubscribe, spotReadyState: spotReadyState, }} > {children} </Context.Provider>; }; export default BinanceWsProvider; import {useCallback, useEffect, useReducer, useState} from "react"; import {useDispatch} from "react-redux"; import {setFuturesBinancePriceState, setSpotBinancePriceState} from "../store/binancePriceSlice"; export enum ReadyState { UNINSTANTIATED = -1, CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3, } export function useBinancePrice() { const stream = "@ticker"; const dispatch = useDispatch(); const [futuresWs, setFuturesWs] = useState<WebSocket|null>(null); const [futuresReadyState, setFuturesReadyState] = useState(ReadyState.UNINSTANTIATED); const [spotWs, setSpotWs] = useState<WebSocket|null>(null); const [spotReadyState, setSpotReadyState] = useState(0); console.log(spotWs); const connectToWs = () => { if ("undefined" === typeof window) { setTimeout("connectToWs", 1000); return; } setFuturesWs(new WebSocket("wss://fstream.binance.com/stream")); setSpotWs(new WebSocket("wss://stream.binance.com:9443/stream")); }; const futuresSubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "SUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [futuresReadyState]); const futuresUnsubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "UNSUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [futuresReadyState]); useEffect(() => { if (null === futuresWs) return; futuresWs.onmessage = (message: MessageEvent) => { if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; // console.log(data.stream); dispatch(setFuturesBinancePriceState({symbol: data.stream.replace(stream, ""), price: data.data.c})); }; futuresWs.onopen = () => { setFuturesReadyState(ReadyState.OPEN); }; futuresWs.onclose = () => { setFuturesReadyState(ReadyState.CLOSED); }; }, [futuresWs, futuresWs, stream]); const spotSubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "SUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [spotReadyState]); const spotUnsubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "UNSUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [spotReadyState]); useEffect(() => { if (null === spotWs) return; spotWs.onmessage = (message: MessageEvent) => { console.log(message); if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setSpotBinancePriceState({symbol: data.stream.replace(stream, ""), price: data.data.c})); }; spotWs.onopen = () => { setSpotReadyState(ReadyState.OPEN); }; spotWs.onclose = () => { setSpotReadyState(ReadyState.CLOSED); }; }, [spotWs]); useEffect(() => { connectToWs(); }, []); return { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, }; } import {createSlice} from "@reduxjs/toolkit"; import {HYDRATE} from "next-redux-wrapper"; export interface BinancePriceSlice { futures: {[key: string]: number}; spot: {[key: string]: number}; } const initialState: BinancePriceSlice = { futures: {}, spot: {}, }; export const binancePriceSlice = createSlice({ name: "binancePrice", initialState, reducers: { setFuturesBinancePriceState(state, action) { state.futures[action.payload.symbol] = action.payload.price; }, setSpotBinancePriceState(state, action) { console.log(action); state.spot[action.payload.symbol] = action.payload.price; }, }, extraReducers: { [HYDRATE]: (state, action) => { return { ...state, ...action.payload, }; }, }, }); export const { setFuturesBinancePriceState, setSpotBinancePriceState, } = binancePriceSlice.actions; export default binancePriceSlice.reducer; Надо разобраться с подключением к вебсокетам бинанса на фронте. Они через раз срабатывают проанализируй код и выяви ошибку
3980f3896fc2db767943b90a4c3b2ab6
{ "intermediate": 0.32290148735046387, "beginner": 0.5325527191162109, "expert": 0.1445457637310028 }
2,444
Can you give me matlab code of an uncertain nonlinear system in the presence of actuator and sensor faults and the presence of a DoS attack with a high dynamic observer for the tracking problem?
788a909e0dc5b66ae9c7eec13e105240
{ "intermediate": 0.14332076907157898, "beginner": 0.1566646546125412, "expert": 0.700014591217041 }
2,445
how to download the full ethereum node data so I can run a node?
e2ece0ac403ca8bc17ea0cfcb1db8957
{ "intermediate": 0.5077051520347595, "beginner": 0.17242999374866486, "expert": 0.3198648691177368 }
2,446
Write a Python program to take a .MOV file (60-second long .MOV file) and split it into twenty 3-second long .MOV files. Then, the code should put these twenty 3-second long .MOV files in the same folder that the 60-second .MOV file is currently in.
aa1eee57a1db478a0651e5d7a364efdd
{ "intermediate": 0.4309092164039612, "beginner": 0.13832643628120422, "expert": 0.430764377117157 }
2,447
court line detection and minimap
a012ad1a8c2f91cac95a6affd7781bf1
{ "intermediate": 0.28550484776496887, "beginner": 0.2905679941177368, "expert": 0.4239271879196167 }
2,448
Consider a Scheme representation of Roman numerals where, for example, the number XI is represented as the list of symbols '(X I). Let r1 and r2 be two Roman numerals in that form. Write the function (roman-add r1 r2) which implements addition of those two Roman numerals *without* converting them to an internal numeric type.
f3bd7a0048f29934b3f0e54b3998637e
{ "intermediate": 0.311664879322052, "beginner": 0.32908886671066284, "expert": 0.35924628376960754 }
2,449
Enter current password for root (enter for none): ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
e2cbf3c6650cfff61aceaae299261df2
{ "intermediate": 0.4367699921131134, "beginner": 0.19930864870548248, "expert": 0.3639213740825653 }
2,450
в swift есть массив [MKPolyline]. Иногда на карте они пересекаются, как убрать эти перечеркивания? Т.е линия идет вниз, направо, вверх, налево, получается квадратное пересечение
77cd40ff0ca9876dd6cb15a23b271865
{ "intermediate": 0.327477365732193, "beginner": 0.34177830815315247, "expert": 0.33074435591697693 }
2,451
I'm trying to use termex on android to install python
e2d349534ceae777867e9aff92be01b2
{ "intermediate": 0.5058373808860779, "beginner": 0.19548757374286652, "expert": 0.2986750304698944 }
2,452
import { Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, Divider, FormControlLabel, Stack, Typography, } from "@mui/material"; import FormatPrice from "../../Common/FormatPrice"; import {FormattedNumber} from "react-intl"; import React, {useEffect, useState} from "react"; import {useSnackbar} from "notistack"; import {useAuthContext} from "../../AuthProvider/AuthProvider"; import {useApiKeyProvider} from "../../../providers/ApiKeyProvider/ApiKeyProvider"; import {SpotBalanceProps} from "./SpotBalance.props"; import {useBinanceWsProvider} from "../../../providers/BinanceWsProvider/BinanceWsProvider"; import {useSelector} from "react-redux"; import {AppState} from "../../../store/store"; import {selectSpotBinanceSymbolState} from "../../../store/binanceSymbol"; import {convertAssets} from "../../../actions/cicap-diary-account"; const skipAssets = ["BNB", "DNT", "DON", "ETHW"]; const SpotBalance = ({spotBalances}: SpotBalanceProps) => { const [spotFinResult] = useState(0); const [convertBalances, setConvertBalances] = useState<SpotBalanceElementPriceChecked[]>([]); const [showConvertSpotBalanceModal, setShowConvertSpotBalanceModal] = useState(false); const {diaryToken} = useAuthContext(); const {selectedSingleApiKey} = useApiKeyProvider(); const {enqueueSnackbar} = useSnackbar(); const {spotSubscribe} = useBinanceWsProvider(); const symbols = useSelector(selectSpotBinanceSymbolState); const handleChangeModal = (asset: string, event: boolean) => { setConvertBalances(prevState => prevState?.map(b => b.asset === asset ? ({...b, checked: event}) : b)); }; const convertAssetsHandler = () => { const assets = convertBalances?.filter(a => a.checked === true).map(a => a.asset); if (assets.length === 0) { enqueueSnackbar("Выберите монеты для конвертации.", {variant: "error"}); return; } if (!diaryToken || null === selectedSingleApiKey) return; convertAssets(selectedSingleApiKey, diaryToken, assets) .then(data => { if (!data) return; if (data.result) { enqueueSnackbar("Конвертация завершена успешно.", {variant: "success"}); } setShowConvertSpotBalanceModal(false); }); }; useEffect(() => { if (symbols.length === 0) return; convertBalances .filter(symbol => symbols.includes(`${symbol.asset}USDT`.toUpperCase())) .forEach((symbol: SpotBalanceElementPriceChecked) => { spotSubscribe(`${symbol.asset}usdt`.toLowerCase()); }); }, [convertBalances, symbols]); useEffect(() => { setConvertBalances( spotBalances .filter(b => !skipAssets.includes(b.asset)) .map(a => ({...a, checked: false})), ); }, [spotBalances]); return <> <Box sx={{backgroundColor: "#f5f5f5", borderRadius: "8px", p: 2, mb: 2}}> <Typography fontWeight="bold">Спотовый счет</Typography> <Typography color={spotFinResult >= 0 ? theme => theme.palette.green.main : "red"} fontSize="xx-large" fontWeight="bold"> {spotFinResult > 0 ? "+" : ""}{FormatPrice({amount: spotFinResult, currency_iso_code: "USD"})} </Typography> <Divider sx={{mb: 2}} /> { spotBalances?.map((balance) => { return <Stack direction="row" justifyContent="space-between" alignItems="center" key={balance.asset}> <Typography>{balance.asset}</Typography> <Typography> <FormattedNumber value={balance.free} minimumFractionDigits={2} maximumFractionDigits={10} /> </Typography> </Stack>; }) } <Divider sx={{my: 2}} /> <Box sx={{display: "flex", justifyContent: "center", fontSize: "small"}} > <Button variant="contained" sx={{fontSize: "small"}} onClick={() => { setShowConvertSpotBalanceModal(true); }} > Конвертировать в BNB </Button> </Box> </Box> <Dialog open={showConvertSpotBalanceModal} onClose={() => { setShowConvertSpotBalanceModal(false); }} fullWidth maxWidth="xs" > <DialogTitle>Конвертировать в BNB</DialogTitle> <DialogContent dividers sx={{px: 0}}> { convertBalances.length > 0 ? ( convertBalances?.map((balance, index) => <SpotBalanceComponent handleChangeModal={handleChangeModal} key={balance.asset} balance={balance} index={index} /> ) ) : ( <Typography>Нет монет для конвертации</Typography> ) } </DialogContent> <DialogActions> <Button variant="contained" onClick={convertAssetsHandler} > Конвертировать </Button> </DialogActions> </Dialog> </>; }; export default SpotBalance; type SpotBalanceElementPriceChecked = { asset: string; free: number; locked: number; checked?: boolean; lastPrice?: string; } type SpotBalanceComponentType = { balance: SpotBalanceElementPriceChecked; handleChangeModal: (asset: string, event: boolean) => void; index: number; } const SpotBalanceComponent = ({balance, handleChangeModal, index}:SpotBalanceComponentType) => { const price = useSelector((state: AppState) => state.binancePrice.spot[`${balance.asset}usdt`.toLowerCase()]); console.log(price); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { handleChangeModal(balance.asset, event.target.checked); }; return <Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ backgroundColor: (index - 1) % 2 ? "#f5f5f5" : "#ffffff", px: 2, }} > <FormControlLabel control={ <Checkbox name="spot-balance-element-checkbox" disabled={balance.free === 0} checked={balance.checked} onChange={handleChange} /> } label={balance.asset} /> <Stack direction="column" alignItems="flex-end" justifyContent="center" spacing={0} py={1}> <Typography fontSize="small" fontWeight="bold" sx={{lineHeight: 1.2}}> <FormattedNumber value={balance.free} minimumFractionDigits={2} maximumFractionDigits={10} /> </Typography> <Typography fontSize="small" sx={{lineHeight: 1.2}}> { price && +price !== 0 ? <FormatPrice amount={+price * balance.free} currency_iso_code="USD" /> : <></> } </Typography> </Stack> </Stack>; }; import {BinanceWsProviderProps} from "./BinanceWsProvider.props"; import {ReadyState, useBinancePrice} from "../../hooks/binancePrices"; import {createContext, useContext, useEffect, useState} from "react"; interface BinanceWsProviderContext { futuresSubscribe: (symbol: string) => void; futuresUnsubscribe: (symbol: string) => void; futuresReadyState: number; spotSubscribe: (symbol: string) => void; spotUnsubscribe: (symbol: string) => void; spotReadyState: number; } const defaultContextValue: BinanceWsProviderContext = { futuresSubscribe: (symbol: string) => {}, futuresUnsubscribe: (symbol: string) => {}, futuresReadyState: 0, spotSubscribe: (symbol: string) => {}, spotUnsubscribe: (symbol: string) => {}, spotReadyState: 0, }; const Context = createContext(defaultContextValue); export function useBinanceWsProvider() { return useContext(Context); } const BinanceWsProvider = ({children}: BinanceWsProviderProps) => { const [futuresSymbols, setFuturesSymbols] = useState<Array<string>>([]); const [futuresQueue, setFuturesQueue] = useState<Array<string>>([]); const [spotSymbols, setSpotSymbols] = useState<Array<string>>([]); const [spotQueue, setSpotQueue] = useState<Array<string>>([]); const { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, } = useBinancePrice(); const futuresSymbolSubscribe = (symbol: string) => { if (futuresSymbols.includes(symbol) || futuresQueue.includes(symbol)) return; setFuturesQueue(prev => [...prev, symbol]); }; const futuresSymbolUnsubscribe = (symbol: string) => { if (!futuresSymbols.includes(symbol) && !futuresQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // futuresUnsubscribe(symbol); setFuturesQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromFuturesQueue = () => { futuresQueue.forEach(symbol => { futuresSubscribe(symbol); }); setFuturesSymbols([...futuresSymbols, ...futuresQueue]); setFuturesQueue([]); }; useEffect(() => { if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresQueue]); useEffect(() => { if (futuresReadyState === ReadyState.CLOSED) { setFuturesQueue([...futuresSymbols, ...futuresQueue]); setFuturesSymbols([]); } if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresReadyState]); const spotSymbolSubscribe = (symbol: string) => { if (spotSymbols.includes(symbol) || spotQueue.includes(symbol)) return; setSpotQueue(prev => [...prev, symbol]); }; const spotSymbolUnsubscribe = (symbol: string) => { if (!spotSymbols.includes(symbol) && !spotQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // spotUnsubscribe(symbol); setSpotQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromSpotQueue = () => { spotQueue.forEach(symbol => { spotSubscribe(symbol); }); setSpotSymbols([...spotSymbols, ...spotQueue]); setSpotQueue([]); }; useEffect(() => { if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotQueue]); useEffect(() => { if (spotReadyState === ReadyState.CLOSED) { setSpotQueue([...spotSymbols, ...spotQueue]); setSpotSymbols([]); } if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotReadyState]); return <Context.Provider value={{ futuresSubscribe: futuresSymbolSubscribe, futuresUnsubscribe: futuresSymbolUnsubscribe, futuresReadyState: futuresReadyState, spotSubscribe: spotSymbolSubscribe, spotUnsubscribe: spotSymbolUnsubscribe, spotReadyState: spotReadyState, }} > {children} </Context.Provider>; }; export default BinanceWsProvider; import {useCallback, useEffect, useReducer, useState} from "react"; import {useDispatch} from "react-redux"; import {setFuturesBinancePriceState, setSpotBinancePriceState} from "../store/binancePriceSlice"; export enum ReadyState { UNINSTANTIATED = -1, CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3, } export function useBinancePrice() { const stream = "@ticker"; const dispatch = useDispatch(); const [futuresWs, setFuturesWs] = useState<WebSocket|null>(null); const [futuresReadyState, setFuturesReadyState] = useState(0); const [spotWs, setSpotWs] = useState<WebSocket|null>(null); const [spotReadyState, setSpotReadyState] = useState(0); const connectToWs = () => { if ("undefined" === typeof window) { setTimeout("connectToWs", 1000); return; } setFuturesWs(new WebSocket("wss://fstream.binance.com/stream")); setSpotWs(new WebSocket("wss://stream.binance.com:9443/stream")); }; const futuresSubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "SUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [futuresReadyState]); const futuresUnsubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "UNSUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [futuresReadyState]); useEffect(() => { if (null === futuresWs) return; futuresWs.onmessage = (message: MessageEvent) => { if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setFuturesBinancePriceState({symbol: data.stream.replace(stream, ""), price: data.data.c})); }; futuresWs.onopen = () => { setFuturesReadyState(ReadyState.OPEN); }; futuresWs.onclose = () => { setFuturesReadyState(ReadyState.CLOSED); }; }, [futuresWs]); const spotSubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "SUBSCRIBE", params: [ `${symbol}${stream}`, ], })); // console.log(spotWs); }, [spotReadyState]); const spotUnsubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "UNSUBSCRIBE", params: [ `${symbol}${stream}`, ], })); // console.log(spotWs); }, [spotReadyState]); useEffect(() => { if (null === spotWs) return; spotWs.onmessage = (message: MessageEvent) => { // console.log("message", message); if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setSpotBinancePriceState({symbol: data.stream.replace(stream, ""), price: data.data.c})); }; spotWs.onopen = () => { setSpotReadyState(ReadyState.OPEN); }; spotWs.onclose = () => { setSpotReadyState(ReadyState.CLOSED); }; }, [spotWs]); useEffect(() => { connectToWs(); }, []); return { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, }; } import {createSlice} from "@reduxjs/toolkit"; import {HYDRATE} from "next-redux-wrapper"; export interface BinancePriceSlice { futures: {[key: string]: number}; spot: {[key: string]: number}; } const initialState: BinancePriceSlice = { futures: {}, spot: {}, }; export const binancePriceSlice = createSlice({ name: "binancePrice", initialState, reducers: { setFuturesBinancePriceState(state, action) { state.futures[action.payload.symbol] = action.payload.price; }, setSpotBinancePriceState(state, action) { state.spot[action.payload.symbol] = action.payload.price; }, }, extraReducers: { [HYDRATE]: (state, action) => { return { ...state, ...action.payload, }; }, }, }); export const { setFuturesBinancePriceState, setSpotBinancePriceState, } = binancePriceSlice.actions; export default binancePriceSlice.reducer; проанализируй код и функцию const SpotBalanceComponent = ({balance, handleChangeModal, index}:SpotBalanceComponentType) => { const price = useSelector((state: AppState) => state.binancePrice.spot[`${balance.asset}usdt`.toLowerCase()]); как работает const price и почему он всегда undefined?
b3a106bcf5d1265f4b308efa89accc01
{ "intermediate": 0.3697411119937897, "beginner": 0.49291250109672546, "expert": 0.13734637200832367 }
2,453
how to detect real time lines of tennis court in live match in python
3866cb662f9d02ad5b73a366f34f431c
{ "intermediate": 0.17107439041137695, "beginner": 0.11403129249811172, "expert": 0.7148943543434143 }
2,454
import { Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, Divider, FormControlLabel, Stack, Typography, } from "@mui/material"; import FormatPrice from "../../Common/FormatPrice"; import {FormattedNumber} from "react-intl"; import React, {useEffect, useState} from "react"; import {useSnackbar} from "notistack"; import {useAuthContext} from "../../AuthProvider/AuthProvider"; import {useApiKeyProvider} from "../../../providers/ApiKeyProvider/ApiKeyProvider"; import {SpotBalanceProps} from "./SpotBalance.props"; import {useBinanceWsProvider} from "../../../providers/BinanceWsProvider/BinanceWsProvider"; import {useSelector} from "react-redux"; import {AppState} from "../../../store/store"; import {selectSpotBinanceSymbolState} from "../../../store/binanceSymbol"; import {convertAssets} from "../../../actions/cicap-diary-account"; const skipAssets = ["BNB", "DNT", "DON", "ETHW"]; const SpotBalance = ({spotBalances}: SpotBalanceProps) => { const [spotFinResult] = useState(0); const [convertBalances, setConvertBalances] = useState<SpotBalanceElementPriceChecked[]>([]); const [showConvertSpotBalanceModal, setShowConvertSpotBalanceModal] = useState(false); const {diaryToken} = useAuthContext(); const {selectedSingleApiKey} = useApiKeyProvider(); const {enqueueSnackbar} = useSnackbar(); const {spotSubscribe} = useBinanceWsProvider(); const symbols = useSelector(selectSpotBinanceSymbolState); const handleChangeModal = (asset: string, event: boolean) => { setConvertBalances(prevState => prevState?.map(b => b.asset === asset ? ({...b, checked: event}) : b)); }; const convertAssetsHandler = () => { const assets = convertBalances?.filter(a => a.checked === true).map(a => a.asset); if (assets.length === 0) { enqueueSnackbar("Выберите монеты для конвертации.", {variant: "error"}); return; } if (!diaryToken || null === selectedSingleApiKey) return; convertAssets(selectedSingleApiKey, diaryToken, assets) .then(data => { if (!data) return; if (data.result) { enqueueSnackbar("Конвертация завершена успешно.", {variant: "success"}); } setShowConvertSpotBalanceModal(false); }); }; useEffect(() => { if (symbols.length === 0) return; convertBalances .filter(symbol => symbols.includes(`${symbol.asset}USDT`.toUpperCase())) .forEach((symbol: SpotBalanceElementPriceChecked) => { spotSubscribe(`${symbol.asset}usdt`.toLowerCase()); }); }, [convertBalances, symbols]); useEffect(() => { setConvertBalances( spotBalances .filter(b => !skipAssets.includes(b.asset)) .map(a => ({...a, checked: false})), ); }, [spotBalances]); return <> <Box sx={{backgroundColor: "#f5f5f5", borderRadius: "8px", p: 2, mb: 2}}> <Typography fontWeight="bold">Спотовый счет</Typography> <Typography color={spotFinResult >= 0 ? theme => theme.palette.green.main : "red"} fontSize="xx-large" fontWeight="bold"> {spotFinResult > 0 ? "+" : ""}{FormatPrice({amount: spotFinResult, currency_iso_code: "USD"})} </Typography> <Divider sx={{mb: 2}} /> { spotBalances?.map((balance) => { return <Stack direction="row" justifyContent="space-between" alignItems="center" key={balance.asset}> <Typography>{balance.asset}</Typography> <Typography> <FormattedNumber value={balance.free} minimumFractionDigits={2} maximumFractionDigits={10} /> </Typography> </Stack>; }) } <Divider sx={{my: 2}} /> <Box sx={{display: "flex", justifyContent: "center", fontSize: "small"}} > <Button variant="contained" sx={{fontSize: "small"}} onClick={() => { setShowConvertSpotBalanceModal(true); }} > Конвертировать в BNB </Button> </Box> </Box> <Dialog open={showConvertSpotBalanceModal} onClose={() => { setShowConvertSpotBalanceModal(false); }} fullWidth maxWidth="xs" > <DialogTitle>Конвертировать в BNB</DialogTitle> <DialogContent dividers sx={{px: 0}}> { convertBalances.length > 0 ? ( convertBalances?.map((balance, index) => <SpotBalanceComponent handleChangeModal={handleChangeModal} key={balance.asset} balance={balance} index={index} /> ) ) : ( <Typography>Нет монет для конвертации</Typography> ) } </DialogContent> <DialogActions> <Button variant="contained" onClick={convertAssetsHandler} > Конвертировать </Button> </DialogActions> </Dialog> </>; }; export default SpotBalance; type SpotBalanceElementPriceChecked = { asset: string; free: number; locked: number; checked?: boolean; lastPrice?: string; } type SpotBalanceComponentType = { balance: SpotBalanceElementPriceChecked; handleChangeModal: (asset: string, event: boolean) => void; index: number; } const SpotBalanceComponent = ({balance, handleChangeModal, index}:SpotBalanceComponentType) => { const price = useSelector((state: AppState) => state.binancePrice.spot[`${balance.asset}usdt`.toLowerCase()]); console.log(price); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { handleChangeModal(balance.asset, event.target.checked); }; return <Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ backgroundColor: (index - 1) % 2 ? "#f5f5f5" : "#ffffff", px: 2, }} > <FormControlLabel control={ <Checkbox name="spot-balance-element-checkbox" disabled={balance.free === 0} checked={balance.checked} onChange={handleChange} /> } label={balance.asset} /> <Stack direction="column" alignItems="flex-end" justifyContent="center" spacing={0} py={1}> <Typography fontSize="small" fontWeight="bold" sx={{lineHeight: 1.2}}> <FormattedNumber value={balance.free} minimumFractionDigits={2} maximumFractionDigits={10} /> </Typography> <Typography fontSize="small" sx={{lineHeight: 1.2}}> { price && +price !== 0 ? <FormatPrice amount={+price * balance.free} currency_iso_code="USD" /> : <></> } </Typography> </Stack> </Stack>; }; import {BinanceWsProviderProps} from "./BinanceWsProvider.props"; import {ReadyState, useBinancePrice} from "../../hooks/binancePrices"; import {createContext, useContext, useEffect, useState} from "react"; interface BinanceWsProviderContext { futuresSubscribe: (symbol: string) => void; futuresUnsubscribe: (symbol: string) => void; futuresReadyState: number; spotSubscribe: (symbol: string) => void; spotUnsubscribe: (symbol: string) => void; spotReadyState: number; } const defaultContextValue: BinanceWsProviderContext = { futuresSubscribe: (symbol: string) => {}, futuresUnsubscribe: (symbol: string) => {}, futuresReadyState: 0, spotSubscribe: (symbol: string) => {}, spotUnsubscribe: (symbol: string) => {}, spotReadyState: 0, }; const Context = createContext(defaultContextValue); export function useBinanceWsProvider() { return useContext(Context); } const BinanceWsProvider = ({children}: BinanceWsProviderProps) => { const [futuresSymbols, setFuturesSymbols] = useState<Array<string>>([]); const [futuresQueue, setFuturesQueue] = useState<Array<string>>([]); const [spotSymbols, setSpotSymbols] = useState<Array<string>>([]); const [spotQueue, setSpotQueue] = useState<Array<string>>([]); const { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, } = useBinancePrice(); const futuresSymbolSubscribe = (symbol: string) => { if (futuresSymbols.includes(symbol) || futuresQueue.includes(symbol)) return; setFuturesQueue(prev => [...prev, symbol]); }; const futuresSymbolUnsubscribe = (symbol: string) => { if (!futuresSymbols.includes(symbol) && !futuresQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // futuresUnsubscribe(symbol); setFuturesQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromFuturesQueue = () => { futuresQueue.forEach(symbol => { futuresSubscribe(symbol); }); setFuturesSymbols([...futuresSymbols, ...futuresQueue]); setFuturesQueue([]); }; useEffect(() => { if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresQueue]); useEffect(() => { if (futuresReadyState === ReadyState.CLOSED) { setFuturesQueue([...futuresSymbols, ...futuresQueue]); setFuturesSymbols([]); } if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresReadyState]); const spotSymbolSubscribe = (symbol: string) => { if (spotSymbols.includes(symbol) || spotQueue.includes(symbol)) return; setSpotQueue(prev => [...prev, symbol]); }; const spotSymbolUnsubscribe = (symbol: string) => { if (!spotSymbols.includes(symbol) && !spotQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // spotUnsubscribe(symbol); setSpotQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromSpotQueue = () => { spotQueue.forEach(symbol => { spotSubscribe(symbol); }); setSpotSymbols([...spotSymbols, ...spotQueue]); setSpotQueue([]); }; useEffect(() => { if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotQueue]); useEffect(() => { if (spotReadyState === ReadyState.CLOSED) { setSpotQueue([...spotSymbols, ...spotQueue]); setSpotSymbols([]); } if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotReadyState]); return <Context.Provider value={{ futuresSubscribe: futuresSymbolSubscribe, futuresUnsubscribe: futuresSymbolUnsubscribe, futuresReadyState: futuresReadyState, spotSubscribe: spotSymbolSubscribe, spotUnsubscribe: spotSymbolUnsubscribe, spotReadyState: spotReadyState, }} > {children} </Context.Provider>; }; export default BinanceWsProvider; import {useCallback, useEffect, useReducer, useState} from "react"; import {useDispatch} from "react-redux"; import {setFuturesBinancePriceState, setSpotBinancePriceState} from "../store/binancePriceSlice"; export enum ReadyState { UNINSTANTIATED = -1, CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3, } export function useBinancePrice() { const stream = "@ticker"; const dispatch = useDispatch(); const [futuresWs, setFuturesWs] = useState<WebSocket|null>(null); const [futuresReadyState, setFuturesReadyState] = useState(0); const [spotWs, setSpotWs] = useState<WebSocket|null>(null); const [spotReadyState, setSpotReadyState] = useState(0); const connectToWs = () => { if ("undefined" === typeof window) { setTimeout("connectToWs", 1000); return; } setFuturesWs(new WebSocket("wss://fstream.binance.com/stream")); setSpotWs(new WebSocket("wss://stream.binance.com:9443/stream")); }; const futuresSubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "SUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [futuresReadyState]); const futuresUnsubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "UNSUBSCRIBE", params: [ `${symbol}${stream}`, ], })); }, [futuresReadyState]); useEffect(() => { if (null === futuresWs) return; futuresWs.onmessage = (message: MessageEvent) => { if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setFuturesBinancePriceState({symbol: data.stream.replace(stream, ""), price: data.data.c})); }; futuresWs.onopen = () => { setFuturesReadyState(ReadyState.OPEN); }; futuresWs.onclose = () => { setFuturesReadyState(ReadyState.CLOSED); }; }, [futuresWs]); const spotSubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "SUBSCRIBE", params: [ `${symbol}${stream}`, ], })); // console.log(spotWs); }, [spotReadyState]); const spotUnsubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: "UNSUBSCRIBE", params: [ `${symbol}${stream}`, ], })); // console.log(spotWs); }, [spotReadyState]); useEffect(() => { if (null === spotWs) return; spotWs.onmessage = (message: MessageEvent) => { // console.log("message", message); if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setSpotBinancePriceState({symbol: data.stream.replace(stream, ""), price: data.data.c})); }; spotWs.onopen = () => { setSpotReadyState(ReadyState.OPEN); }; spotWs.onclose = () => { setSpotReadyState(ReadyState.CLOSED); }; }, [spotWs]); useEffect(() => { connectToWs(); }, []); return { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, }; } import {createSlice} from "@reduxjs/toolkit"; import {HYDRATE} from "next-redux-wrapper"; export interface BinancePriceSlice { futures: {[key: string]: number}; spot: {[key: string]: number}; } const initialState: BinancePriceSlice = { futures: {}, spot: {}, }; export const binancePriceSlice = createSlice({ name: "binancePrice", initialState, reducers: { setFuturesBinancePriceState(state, action) { state.futures[action.payload.symbol] = action.payload.price; }, setSpotBinancePriceState(state, action) { state.spot[action.payload.symbol] = action.payload.price; }, }, extraReducers: { [HYDRATE]: (state, action) => { return { ...state, ...action.payload, }; }, }, }); export const { setFuturesBinancePriceState, setSpotBinancePriceState, } = binancePriceSlice.actions; export default binancePriceSlice.reducer; проанализируй код и функцию const SpotBalanceComponent = ({balance, handleChangeModal, index}:SpotBalanceComponentType) => { const price = useSelector((state: AppState) => state.binancePrice.spot[`${balance.asset}usdt`.toLowerCase()]); как работает const price и почему он всегда undefined?
24facbc947387ae6fe4cff2dd14dd870
{ "intermediate": 0.3697411119937897, "beginner": 0.49291250109672546, "expert": 0.13734637200832367 }
2,455
store local directory structure metadata into sqlite using c++,and support add file,remove file,add directory,remove directory,get file's size, get directory's size
d17c093aa9c874527d28124fc9155f56
{ "intermediate": 0.5410639643669128, "beginner": 0.16336789727210999, "expert": 0.2955680787563324 }
2,456
import { Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, Divider, FormControlLabel, Stack, Typography, } from “@mui/material”; import FormatPrice from “…/…/Common/FormatPrice”; import {FormattedNumber} from “react-intl”; import React, {useEffect, useState} from “react”; import {useSnackbar} from “notistack”; import {useAuthContext} from “…/…/AuthProvider/AuthProvider”; import {useApiKeyProvider} from “…/…/…/providers/ApiKeyProvider/ApiKeyProvider”; import {SpotBalanceProps} from “./SpotBalance.props”; import {useBinanceWsProvider} from “…/…/…/providers/BinanceWsProvider/BinanceWsProvider”; import {useSelector} from “react-redux”; import {AppState} from “…/…/…/store/store”; import {selectSpotBinanceSymbolState} from “…/…/…/store/binanceSymbol”; import {convertAssets} from “…/…/…/actions/cicap-diary-account”; const skipAssets = [“BNB”, “DNT”, “DON”, “ETHW”]; const SpotBalance = ({spotBalances}: SpotBalanceProps) => { const [spotFinResult] = useState(0); const [convertBalances, setConvertBalances] = useState<SpotBalanceElementPriceChecked[]>([]); const [showConvertSpotBalanceModal, setShowConvertSpotBalanceModal] = useState(false); const {diaryToken} = useAuthContext(); const {selectedSingleApiKey} = useApiKeyProvider(); const {enqueueSnackbar} = useSnackbar(); const {spotSubscribe} = useBinanceWsProvider(); const symbols = useSelector(selectSpotBinanceSymbolState); const handleChangeModal = (asset: string, event: boolean) => { setConvertBalances(prevState => prevState?.map(b => b.asset === asset ? ({…b, checked: event}) : b)); }; const convertAssetsHandler = () => { const assets = convertBalances?.filter(a => a.checked === true).map(a => a.asset); if (assets.length === 0) { enqueueSnackbar(“Выберите монеты для конвертации.”, {variant: “error”}); return; } if (!diaryToken || null === selectedSingleApiKey) return; convertAssets(selectedSingleApiKey, diaryToken, assets) .then(data => { if (!data) return; if (data.result) { enqueueSnackbar(“Конвертация завершена успешно.”, {variant: “success”}); } setShowConvertSpotBalanceModal(false); }); }; useEffect(() => { if (symbols.length === 0) return; convertBalances .filter(symbol => symbols.includes(${symbol.asset}USDT.toUpperCase())) .forEach((symbol: SpotBalanceElementPriceChecked) => { spotSubscribe(${symbol.asset}usdt.toLowerCase()); }); }, [convertBalances, symbols]); useEffect(() => { setConvertBalances( spotBalances .filter(b => !skipAssets.includes(b.asset)) .map(a => ({…a, checked: false})), ); }, [spotBalances]); return <> <Box sx={{backgroundColor: “#f5f5f5”, borderRadius: “8px”, p: 2, mb: 2}}> <Typography fontWeight=“bold”>Спотовый счет</Typography> <Typography color={spotFinResult >= 0 ? theme => theme.palette.green.main : “red”} fontSize=“xx-large” fontWeight=“bold”> {spotFinResult > 0 ? “+” : “”}{FormatPrice({amount: spotFinResult, currency_iso_code: “USD”})} </Typography> <Divider sx={{mb: 2}} /> { spotBalances?.map((balance) => { return <Stack direction=“row” justifyContent=“space-between” alignItems=“center” key={balance.asset}> <Typography>{balance.asset}</Typography> <Typography> <FormattedNumber value={balance.free} minimumFractionDigits={2} maximumFractionDigits={10} /> </Typography> </Stack>; }) } <Divider sx={{my: 2}} /> <Box sx={{display: “flex”, justifyContent: “center”, fontSize: “small”}} > <Button variant=“contained” sx={{fontSize: “small”}} onClick={() => { setShowConvertSpotBalanceModal(true); }} > Конвертировать в BNB </Button> </Box> </Box> <Dialog open={showConvertSpotBalanceModal} onClose={() => { setShowConvertSpotBalanceModal(false); }} fullWidth maxWidth=“xs” > <DialogTitle>Конвертировать в BNB</DialogTitle> <DialogContent dividers sx={{px: 0}}> { convertBalances.length > 0 ? ( convertBalances?.map((balance, index) => <SpotBalanceComponent handleChangeModal={handleChangeModal} key={balance.asset} balance={balance} index={index} /> ) ) : ( <Typography>Нет монет для конвертации</Typography> ) } </DialogContent> <DialogActions> <Button variant=“contained” onClick={convertAssetsHandler} > Конвертировать </Button> </DialogActions> </Dialog> </>; }; export default SpotBalance; type SpotBalanceElementPriceChecked = { asset: string; free: number; locked: number; checked?: boolean; lastPrice?: string; } type SpotBalanceComponentType = { balance: SpotBalanceElementPriceChecked; handleChangeModal: (asset: string, event: boolean) => void; index: number; } const SpotBalanceComponent = ({balance, handleChangeModal, index}:SpotBalanceComponentType) => { const price = useSelector((state: AppState) => state.binancePrice.spot[${balance.asset}usdt.toLowerCase()]); console.log(price); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { handleChangeModal(balance.asset, event.target.checked); }; return <Stack direction=“row” justifyContent=“space-between” alignItems=“center” sx={{ backgroundColor: (index - 1) % 2 ? “#f5f5f5” : “#ffffff”, px: 2, }} > <FormControlLabel control={ <Checkbox name=“spot-balance-element-checkbox” disabled={balance.free === 0} checked={balance.checked} onChange={handleChange} /> } label={balance.asset} /> <Stack direction=“column” alignItems=“flex-end” justifyContent=“center” spacing={0} py={1}> <Typography fontSize=“small” fontWeight=“bold” sx={{lineHeight: 1.2}}> <FormattedNumber value={balance.free} minimumFractionDigits={2} maximumFractionDigits={10} /> </Typography> <Typography fontSize=“small” sx={{lineHeight: 1.2}}> { price && +price !== 0 ? <FormatPrice amount={+price * balance.free} currency_iso_code=“USD” /> : <></> } </Typography> </Stack> </Stack>; }; import {BinanceWsProviderProps} from “./BinanceWsProvider.props”; import {ReadyState, useBinancePrice} from “…/…/hooks/binancePrices”; import {createContext, useContext, useEffect, useState} from “react”; interface BinanceWsProviderContext { futuresSubscribe: (symbol: string) => void; futuresUnsubscribe: (symbol: string) => void; futuresReadyState: number; spotSubscribe: (symbol: string) => void; spotUnsubscribe: (symbol: string) => void; spotReadyState: number; } const defaultContextValue: BinanceWsProviderContext = { futuresSubscribe: (symbol: string) => {}, futuresUnsubscribe: (symbol: string) => {}, futuresReadyState: 0, spotSubscribe: (symbol: string) => {}, spotUnsubscribe: (symbol: string) => {}, spotReadyState: 0, }; const Context = createContext(defaultContextValue); export function useBinanceWsProvider() { return useContext(Context); } const BinanceWsProvider = ({children}: BinanceWsProviderProps) => { const [futuresSymbols, setFuturesSymbols] = useState<Array<string>>([]); const [futuresQueue, setFuturesQueue] = useState<Array<string>>([]); const [spotSymbols, setSpotSymbols] = useState<Array<string>>([]); const [spotQueue, setSpotQueue] = useState<Array<string>>([]); const { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, } = useBinancePrice(); const futuresSymbolSubscribe = (symbol: string) => { if (futuresSymbols.includes(symbol) || futuresQueue.includes(symbol)) return; setFuturesQueue(prev => […prev, symbol]); }; const futuresSymbolUnsubscribe = (symbol: string) => { if (!futuresSymbols.includes(symbol) && !futuresQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // futuresUnsubscribe(symbol); setFuturesQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromFuturesQueue = () => { futuresQueue.forEach(symbol => { futuresSubscribe(symbol); }); setFuturesSymbols([…futuresSymbols, …futuresQueue]); setFuturesQueue([]); }; useEffect(() => { if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresQueue]); useEffect(() => { if (futuresReadyState === ReadyState.CLOSED) { setFuturesQueue([…futuresSymbols, …futuresQueue]); setFuturesSymbols([]); } if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresReadyState]); const spotSymbolSubscribe = (symbol: string) => { if (spotSymbols.includes(symbol) || spotQueue.includes(symbol)) return; setSpotQueue(prev => […prev, symbol]); }; const spotSymbolUnsubscribe = (symbol: string) => { if (!spotSymbols.includes(symbol) && !spotQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // spotUnsubscribe(symbol); setSpotQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromSpotQueue = () => { spotQueue.forEach(symbol => { spotSubscribe(symbol); }); setSpotSymbols([…spotSymbols, …spotQueue]); setSpotQueue([]); }; useEffect(() => { if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotQueue]); useEffect(() => { if (spotReadyState === ReadyState.CLOSED) { setSpotQueue([…spotSymbols, …spotQueue]); setSpotSymbols([]); } if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotReadyState]); return <Context.Provider value={{ futuresSubscribe: futuresSymbolSubscribe, futuresUnsubscribe: futuresSymbolUnsubscribe, futuresReadyState: futuresReadyState, spotSubscribe: spotSymbolSubscribe, spotUnsubscribe: spotSymbolUnsubscribe, spotReadyState: spotReadyState, }} > {children} </Context.Provider>; }; export default BinanceWsProvider; import {useCallback, useEffect, useReducer, useState} from “react”; import {useDispatch} from “react-redux”; import {setFuturesBinancePriceState, setSpotBinancePriceState} from “…/store/binancePriceSlice”; export enum ReadyState { UNINSTANTIATED = -1, CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3, } export function useBinancePrice() { const stream = “@ticker”; const dispatch = useDispatch(); const [futuresWs, setFuturesWs] = useState<WebSocket|null>(null); const [futuresReadyState, setFuturesReadyState] = useState(0); const [spotWs, setSpotWs] = useState<WebSocket|null>(null); const [spotReadyState, setSpotReadyState] = useState(0); const connectToWs = () => { if (“undefined” === typeof window) { setTimeout(“connectToWs”, 1000); return; } setFuturesWs(new WebSocket(“wss://fstream.binance.com/stream”)); setSpotWs(new WebSocket(“wss://stream.binance.com:9443/stream”)); }; const futuresSubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “SUBSCRIBE”, params: [ ${symbol}${stream}, ], })); }, [futuresReadyState]); const futuresUnsubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “UNSUBSCRIBE”, params: [ ${symbol}${stream}, ], })); }, [futuresReadyState]); useEffect(() => { if (null === futuresWs) return; futuresWs.onmessage = (message: MessageEvent) => { if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setFuturesBinancePriceState({symbol: data.stream.replace(stream, “”), price: data.data.c})); }; futuresWs.onopen = () => { setFuturesReadyState(ReadyState.OPEN); }; futuresWs.onclose = () => { setFuturesReadyState(ReadyState.CLOSED); }; }, [futuresWs]); const spotSubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “SUBSCRIBE”, params: [ ${symbol}${stream}, ], })); // console.log(spotWs); }, [spotReadyState]); const spotUnsubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “UNSUBSCRIBE”, params: [ ${symbol}${stream}, ], })); // console.log(spotWs); }, [spotReadyState]); useEffect(() => { if (null === spotWs) return; spotWs.onmessage = (message: MessageEvent) => { // console.log(“message”, message); if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setSpotBinancePriceState({symbol: data.stream.replace(stream, “”), price: data.data.c})); }; spotWs.onopen = () => { setSpotReadyState(ReadyState.OPEN); }; spotWs.onclose = () => { setSpotReadyState(ReadyState.CLOSED); }; }, [spotWs]); useEffect(() => { connectToWs(); }, []); return { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, }; } import {createSlice} from “@reduxjs/toolkit”; import {HYDRATE} from “next-redux-wrapper”; export interface BinancePriceSlice { futures: {[key: string]: number}; spot: {[key: string]: number}; } const initialState: BinancePriceSlice = { futures: {}, spot: {}, }; export const binancePriceSlice = createSlice({ name: “binancePrice”, initialState, reducers: { setFuturesBinancePriceState(state, action) { state.futures[action.payload.symbol] = action.payload.price; }, setSpotBinancePriceState(state, action) { state.spot[action.payload.symbol] = action.payload.price; }, }, extraReducers: { [HYDRATE]: (state, action) => { return { …state, …action.payload, }; }, }, }); export const { setFuturesBinancePriceState, setSpotBinancePriceState, } = binancePriceSlice.actions; export default binancePriceSlice.reducer; проанализируй код и функцию const SpotBalanceComponent = ({balance, handleChangeModal, index}:SpotBalanceComponentType) => { const price = useSelector((state: AppState) => state.binancePrice.spot[${balance.asset}usdt.toLowerCase()]); как работает const price и почему он всегда undefined? ошибка приходит в useEffect(() => { if (null === spotWs) return; spotWs.onmessage = (message: MessageEvent) => { console.log("message", message); error : code : 2 msg : "Invalid request: request ID must be an unsigned integer" [[Prototype]] : Object
3886206087f419d12081791ec01ddc01
{ "intermediate": 0.3387148976325989, "beginner": 0.4292478561401367, "expert": 0.2320372462272644 }
2,457
import { Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, Divider, FormControlLabel, Stack, Typography, } from “@mui/material”; import FormatPrice from “…/…/Common/FormatPrice”; import {FormattedNumber} from “react-intl”; import React, {useEffect, useState} from “react”; import {useSnackbar} from “notistack”; import {useAuthContext} from “…/…/AuthProvider/AuthProvider”; import {useApiKeyProvider} from “…/…/…/providers/ApiKeyProvider/ApiKeyProvider”; import {SpotBalanceProps} from “./SpotBalance.props”; import {useBinanceWsProvider} from “…/…/…/providers/BinanceWsProvider/BinanceWsProvider”; import {useSelector} from “react-redux”; import {AppState} from “…/…/…/store/store”; import {selectSpotBinanceSymbolState} from “…/…/…/store/binanceSymbol”; import {convertAssets} from “…/…/…/actions/cicap-diary-account”; const skipAssets = [“BNB”, “DNT”, “DON”, “ETHW”]; const SpotBalance = ({spotBalances}: SpotBalanceProps) => { const [spotFinResult] = useState(0); const [convertBalances, setConvertBalances] = useState<SpotBalanceElementPriceChecked[]>([]); const [showConvertSpotBalanceModal, setShowConvertSpotBalanceModal] = useState(false); const {diaryToken} = useAuthContext(); const {selectedSingleApiKey} = useApiKeyProvider(); const {enqueueSnackbar} = useSnackbar(); const {spotSubscribe} = useBinanceWsProvider(); const symbols = useSelector(selectSpotBinanceSymbolState); const handleChangeModal = (asset: string, event: boolean) => { setConvertBalances(prevState => prevState?.map(b => b.asset === asset ? ({…b, checked: event}) : b)); }; const convertAssetsHandler = () => { const assets = convertBalances?.filter(a => a.checked === true).map(a => a.asset); if (assets.length === 0) { enqueueSnackbar(“Выберите монеты для конвертации.”, {variant: “error”}); return; } if (!diaryToken || null === selectedSingleApiKey) return; convertAssets(selectedSingleApiKey, diaryToken, assets) .then(data => { if (!data) return; if (data.result) { enqueueSnackbar(“Конвертация завершена успешно.”, {variant: “success”}); } setShowConvertSpotBalanceModal(false); }); }; useEffect(() => { if (symbols.length === 0) return; convertBalances .filter(symbol => symbols.includes(${symbol.asset}USDT.toUpperCase())) .forEach((symbol: SpotBalanceElementPriceChecked) => { spotSubscribe(${symbol.asset}usdt.toLowerCase()); }); }, [convertBalances, symbols]); useEffect(() => { setConvertBalances( spotBalances .filter(b => !skipAssets.includes(b.asset)) .map(a => ({…a, checked: false})), ); }, [spotBalances]); return <> <Box sx={{backgroundColor: “#f5f5f5”, borderRadius: “8px”, p: 2, mb: 2}}> <Typography fontWeight=“bold”>Спотовый счет</Typography> <Typography color={spotFinResult >= 0 ? theme => theme.palette.green.main : “red”} fontSize=“xx-large” fontWeight=“bold”> {spotFinResult > 0 ? “+” : “”}{FormatPrice({amount: spotFinResult, currency_iso_code: “USD”})} </Typography> <Divider sx={{mb: 2}} /> { spotBalances?.map((balance) => { return <Stack direction=“row” justifyContent=“space-between” alignItems=“center” key={balance.asset}> <Typography>{balance.asset}</Typography> <Typography> <FormattedNumber value={balance.free} minimumFractionDigits={2} maximumFractionDigits={10} /> </Typography> </Stack>; }) } <Divider sx={{my: 2}} /> <Box sx={{display: “flex”, justifyContent: “center”, fontSize: “small”}} > <Button variant=“contained” sx={{fontSize: “small”}} onClick={() => { setShowConvertSpotBalanceModal(true); }} > Конвертировать в BNB </Button> </Box> </Box> <Dialog open={showConvertSpotBalanceModal} onClose={() => { setShowConvertSpotBalanceModal(false); }} fullWidth maxWidth=“xs” > <DialogTitle>Конвертировать в BNB</DialogTitle> <DialogContent dividers sx={{px: 0}}> { convertBalances.length > 0 ? ( convertBalances?.map((balance, index) => <SpotBalanceComponent handleChangeModal={handleChangeModal} key={balance.asset} balance={balance} index={index} /> ) ) : ( <Typography>Нет монет для конвертации</Typography> ) } </DialogContent> <DialogActions> <Button variant=“contained” onClick={convertAssetsHandler} > Конвертировать </Button> </DialogActions> </Dialog> </>; }; export default SpotBalance; type SpotBalanceElementPriceChecked = { asset: string; free: number; locked: number; checked?: boolean; lastPrice?: string; } type SpotBalanceComponentType = { balance: SpotBalanceElementPriceChecked; handleChangeModal: (asset: string, event: boolean) => void; index: number; } const SpotBalanceComponent = ({balance, handleChangeModal, index}:SpotBalanceComponentType) => { const price = useSelector((state: AppState) => state.binancePrice.spot[${balance.asset}usdt.toLowerCase()]); console.log(price); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { handleChangeModal(balance.asset, event.target.checked); }; return <Stack direction=“row” justifyContent=“space-between” alignItems=“center” sx={{ backgroundColor: (index - 1) % 2 ? “#f5f5f5” : “#ffffff”, px: 2, }} > <FormControlLabel control={ <Checkbox name=“spot-balance-element-checkbox” disabled={balance.free === 0} checked={balance.checked} onChange={handleChange} /> } label={balance.asset} /> <Stack direction=“column” alignItems=“flex-end” justifyContent=“center” spacing={0} py={1}> <Typography fontSize=“small” fontWeight=“bold” sx={{lineHeight: 1.2}}> <FormattedNumber value={balance.free} minimumFractionDigits={2} maximumFractionDigits={10} /> </Typography> <Typography fontSize=“small” sx={{lineHeight: 1.2}}> { price && +price !== 0 ? <FormatPrice amount={+price * balance.free} currency_iso_code=“USD” /> : <></> } </Typography> </Stack> </Stack>; }; import {BinanceWsProviderProps} from “./BinanceWsProvider.props”; import {ReadyState, useBinancePrice} from “…/…/hooks/binancePrices”; import {createContext, useContext, useEffect, useState} from “react”; interface BinanceWsProviderContext { futuresSubscribe: (symbol: string) => void; futuresUnsubscribe: (symbol: string) => void; futuresReadyState: number; spotSubscribe: (symbol: string) => void; spotUnsubscribe: (symbol: string) => void; spotReadyState: number; } const defaultContextValue: BinanceWsProviderContext = { futuresSubscribe: (symbol: string) => {}, futuresUnsubscribe: (symbol: string) => {}, futuresReadyState: 0, spotSubscribe: (symbol: string) => {}, spotUnsubscribe: (symbol: string) => {}, spotReadyState: 0, }; const Context = createContext(defaultContextValue); export function useBinanceWsProvider() { return useContext(Context); } const BinanceWsProvider = ({children}: BinanceWsProviderProps) => { const [futuresSymbols, setFuturesSymbols] = useState<Array<string>>([]); const [futuresQueue, setFuturesQueue] = useState<Array<string>>([]); const [spotSymbols, setSpotSymbols] = useState<Array<string>>([]); const [spotQueue, setSpotQueue] = useState<Array<string>>([]); const { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, } = useBinancePrice(); const futuresSymbolSubscribe = (symbol: string) => { if (futuresSymbols.includes(symbol) || futuresQueue.includes(symbol)) return; setFuturesQueue(prev => […prev, symbol]); }; const futuresSymbolUnsubscribe = (symbol: string) => { if (!futuresSymbols.includes(symbol) && !futuresQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // futuresUnsubscribe(symbol); setFuturesQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromFuturesQueue = () => { futuresQueue.forEach(symbol => { futuresSubscribe(symbol); }); setFuturesSymbols([…futuresSymbols, …futuresQueue]); setFuturesQueue([]); }; useEffect(() => { if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresQueue]); useEffect(() => { if (futuresReadyState === ReadyState.CLOSED) { setFuturesQueue([…futuresSymbols, …futuresQueue]); setFuturesSymbols([]); } if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresReadyState]); const spotSymbolSubscribe = (symbol: string) => { if (spotSymbols.includes(symbol) || spotQueue.includes(symbol)) return; setSpotQueue(prev => […prev, symbol]); }; const spotSymbolUnsubscribe = (symbol: string) => { if (!spotSymbols.includes(symbol) && !spotQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // spotUnsubscribe(symbol); setSpotQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromSpotQueue = () => { spotQueue.forEach(symbol => { spotSubscribe(symbol); }); setSpotSymbols([…spotSymbols, …spotQueue]); setSpotQueue([]); }; useEffect(() => { if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotQueue]); useEffect(() => { if (spotReadyState === ReadyState.CLOSED) { setSpotQueue([…spotSymbols, …spotQueue]); setSpotSymbols([]); } if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotReadyState]); return <Context.Provider value={{ futuresSubscribe: futuresSymbolSubscribe, futuresUnsubscribe: futuresSymbolUnsubscribe, futuresReadyState: futuresReadyState, spotSubscribe: spotSymbolSubscribe, spotUnsubscribe: spotSymbolUnsubscribe, spotReadyState: spotReadyState, }} > {children} </Context.Provider>; }; export default BinanceWsProvider; import {useCallback, useEffect, useReducer, useState} from “react”; import {useDispatch} from “react-redux”; import {setFuturesBinancePriceState, setSpotBinancePriceState} from “…/store/binancePriceSlice”; export enum ReadyState { UNINSTANTIATED = -1, CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3, } export function useBinancePrice() { const stream = “@ticker”; const dispatch = useDispatch(); const [futuresWs, setFuturesWs] = useState<WebSocket|null>(null); const [futuresReadyState, setFuturesReadyState] = useState(0); const [spotWs, setSpotWs] = useState<WebSocket|null>(null); const [spotReadyState, setSpotReadyState] = useState(0); const connectToWs = () => { if (“undefined” === typeof window) { setTimeout(“connectToWs”, 1000); return; } setFuturesWs(new WebSocket(“wss://fstream.binance.com/stream”)); setSpotWs(new WebSocket(“wss://stream.binance.com:9443/stream”)); }; const futuresSubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “SUBSCRIBE”, params: [ ${symbol}${stream}, ], })); }, [futuresReadyState]); const futuresUnsubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “UNSUBSCRIBE”, params: [ ${symbol}${stream}, ], })); }, [futuresReadyState]); useEffect(() => { if (null === futuresWs) return; futuresWs.onmessage = (message: MessageEvent) => { if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setFuturesBinancePriceState({symbol: data.stream.replace(stream, “”), price: data.data.c})); }; futuresWs.onopen = () => { setFuturesReadyState(ReadyState.OPEN); }; futuresWs.onclose = () => { setFuturesReadyState(ReadyState.CLOSED); }; }, [futuresWs]); const spotSubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “SUBSCRIBE”, params: [ ${symbol}${stream}, ], })); // console.log(spotWs); }, [spotReadyState]); const spotUnsubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “UNSUBSCRIBE”, params: [ ${symbol}${stream}, ], })); // console.log(spotWs); }, [spotReadyState]); useEffect(() => { if (null === spotWs) return; spotWs.onmessage = (message: MessageEvent) => { // console.log(“message”, message); if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setSpotBinancePriceState({symbol: data.stream.replace(stream, “”), price: data.data.c})); }; spotWs.onopen = () => { setSpotReadyState(ReadyState.OPEN); }; spotWs.onclose = () => { setSpotReadyState(ReadyState.CLOSED); }; }, [spotWs]); useEffect(() => { connectToWs(); }, []); return { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, }; } import {createSlice} from “@reduxjs/toolkit”; import {HYDRATE} from “next-redux-wrapper”; export interface BinancePriceSlice { futures: {[key: string]: number}; spot: {[key: string]: number}; } const initialState: BinancePriceSlice = { futures: {}, spot: {}, }; export const binancePriceSlice = createSlice({ name: “binancePrice”, initialState, reducers: { setFuturesBinancePriceState(state, action) { state.futures[action.payload.symbol] = action.payload.price; }, setSpotBinancePriceState(state, action) { state.spot[action.payload.symbol] = action.payload.price; }, }, extraReducers: { [HYDRATE]: (state, action) => { return { …state, …action.payload, }; }, }, }); export const { setFuturesBinancePriceState, setSpotBinancePriceState, } = binancePriceSlice.actions; export default binancePriceSlice.reducer; проанализируй код и функцию const SpotBalanceComponent = ({balance, handleChangeModal, index}:SpotBalanceComponentType) => { const price = useSelector((state: AppState) => state.binancePrice.spot[${balance.asset}usdt.toLowerCase()]); как работает const price и почему он всегда undefined? ошибка приходит в useEffect(() => { if (null === spotWs) return; spotWs.onmessage = (message: MessageEvent) => { console.log("message", message); error : code : 2 msg : "Invalid request: request ID must be an unsigned integer" [[Prototype]] : Object
41d0730898f7e9a4863d26ece51478e8
{ "intermediate": 0.3387148976325989, "beginner": 0.4292478561401367, "expert": 0.2320372462272644 }
2,458
so this script monitor the clipboard for any changes and automatically translate copied japanese text to english using gpt and then show the translation on a created window. i want you to make this script work without the shell running and only showing the created window. also make it to print any errors in a new window. import time import pyperclip import openai import json import tkinter as tk import threading import os from tkinter import font, Menu from tkinter import font # Set your OpenAI API key and base openai.api_base = "" openai.api_key = "" # Global variables pause_monitoring = False dark_mode = False # Storing prompt text prompt_logfile = "prompt.txt" try: with open(prompt_logfile, "r", encoding="utf-8") as f: prompt_text = f.read() except FileNotFoundError: # If the log file doesn’t exist, use the default prompt text prompt_text = "Translate the following text: {text_to_translate}" # Keeping translation logs KEEP_LOGS = False translated_dict = {} jsonfile = "translation.json" try: with open(jsonfile, "r", encoding="utf-8") as f: translated_dict = json.load(f) except FileNotFoundError: pass def translate_text(text_to_translate, prompt_template): prompt = prompt_template.format(text_to_translate=text_to_translate) completion = openai.ChatCompletion.create( model="gpt-3.5-turbo-0301", temperature=1, messages=[ { "role": "user", "content": f"{prompt}", } ], ) translated_text = ( completion["choices"][0] .get("message") .get("content") .encode("utf8") .decode() ) return translated_text def update_display(display, text): display.delete(1.0, tk.END) display.insert(tk.END, text) def retranslate(): untranslated_text = untranslated_textbox.get(1.0, tk.END).strip() if untranslated_text: pyperclip.copy(untranslated_text) def toggle_pause_monitoring(): global pause_monitoring pause_monitoring = not pause_monitoring pause_button.config( text="Resume" if pause_monitoring else "Pause", relief=tk.SUNKEN if pause_monitoring else tk.RAISED ) def clipboard_monitor(): global prompt_text old_clipboard = "" while True: if not pause_monitoring: new_clipboard = pyperclip.paste() # Remove line breaks from new_clipboard new_clipboard = new_clipboard.replace('\n', '').replace('\r', '') # Compare new_clipboard with old_clipboard to detect changes if new_clipboard != old_clipboard: old_clipboard = new_clipboard if new_clipboard in translated_dict: translated_text = translated_dict[new_clipboard] else: try: prompt_text = prompt_textbox.get(1.0, tk.END).strip() translated_text = translate_text(new_clipboard, prompt_text) except Exception as e: print(e, "Connection Error") continue translated_dict[new_clipboard] = translated_text if KEEP_LOGS: with open(jsonfile, "w", encoding="utf-8") as f: json.dump(translated_dict, f, ensure_ascii=False, indent=4) update_display(untranslated_textbox, new_clipboard) update_display(translated_textbox, translated_text) time.sleep(1) def toggle_translated(): current_bg = translated_textbox.cget("background") if current_bg == "black": translated_textbox.configure(background="white") translated_textbox.delete(1.0, tk.END) try: translated_textbox.insert(tk.END, translated_dict[untranslated_textbox.get(1.0, tk.END).strip()]) except Exception as e: pass toggle_button.config(text="Hide", relief=tk.RAISED) else: translated_textbox.configure(background="black") translated_textbox.delete(1.0, tk.END) toggle_button.config(text="Show", relief=tk.SUNKEN) def save_prompt(): global prompt_text current_prompt_text = prompt_textbox.get(1.0, tk.END).strip() if current_prompt_text != prompt_text: # Save any prompt_text changes to the log file prompt_text = current_prompt_text with open(prompt_logfile, "w", encoding="utf-8") as f: f.write(prompt_text) def set_always_on_top(): root.attributes("-topmost", always_on_top_var.get()) def increase_opacity(): opacity = root.attributes("-alpha") opacity = min(opacity + 0.1, 1.0) root.attributes("-alpha", opacity) def decrease_opacity(): opacity = root.attributes("-alpha") opacity = max(opacity - 0.1, 0.1) root.attributes("-alpha", opacity) def toggle_dark_mode(): global dark_mode dark_mode = not dark_mode bg_color = "black" if dark_mode else "white" fg_color = "white" if dark_mode else "black" untranslated_textbox.configure(bg=bg_color, fg=fg_color) translated_textbox.configure(bg=bg_color, fg=fg_color) prompt_textbox.configure(bg=bg_color, fg=fg_color) root.configure(bg=bg_color) options_menu.configure(bg=bg_color, fg=fg_color) menu_bar.configure(bg=bg_color, fg=fg_color) def font_window(): global current_font current_font = { "family": font.Font(font=untranslated_textbox["font"]).actual("family"), "size": font.Font(font=untranslated_textbox["font"]).actual("size"), "color": untranslated_textbox.cget("foreground") } font_window = tk.Toplevel() font_window.title("Font Settings") font_window.geometry("150x150") font_family = tk.StringVar() font_family_label = tk.Label(font_window, text="Font Family") font_family_label.pack() font_family_entry = tk.Entry(font_window, textvariable=font_family) font_family_entry.insert(0, current_font["family"]) font_family_entry.pack() font_size = tk.StringVar() font_size_label = tk.Label(font_window, text="Font Size") font_size_label.pack() font_size_entry = tk.Entry(font_window, textvariable=font_size) font_size_entry.insert(0, current_font["size"]) font_size_entry.pack() font_color = tk.StringVar() font_color_label = tk.Label(font_window, text="Font Color") font_color_label.pack() font_color_entry = tk.Entry(font_window, textvariable=font_color) font_color_entry.insert(0, current_font["color"]) font_color_entry.pack() def apply_changes(): new_font_family = font_family.get() or current_font["family"] new_font_size = font_size.get() or current_font["size"] new_font_color = font_color.get() or current_font["color"] current_font = {"family": new_font_family, "size": new_font_size, "color": new_font_color} untranslated_textbox.configure(font=(current_font["family"], current_font["size"]), fg=current_font["color"]) translated_textbox.configure(font=(current_font["family"], current_font["size"]), fg=current_font["color"]) font_window.destroy() apply_button = tk.Button(font_window, text="Apply", command=apply_changes) apply_button.pack() cancel_button = tk.Button(font_window, text="Cancel", command=font_window.destroy) cancel_button.pack() root = tk.Tk() root.title("Clipboard Translator") root.geometry("400x200") menu_bar = Menu(root) # Add Options menu options_menu = Menu(menu_bar, tearoff=0) menu_bar.add_cascade(label="Options", menu=options_menu) options_menu.add_command(label="Save Prompt", command=save_prompt) always_on_top_var = tk.BooleanVar(value=False) options_menu.add_checkbutton(label="Always on top", variable=always_on_top_var, command=set_always_on_top) dark_mode_var = tk.BooleanVar(value=False) options_menu.add_checkbutton(label="Dark Mode", variable=dark_mode_var, command=toggle_dark_mode) options_menu.add_command(label="Increase opacity", command=increase_opacity) options_menu.add_command(label="Decrease opacity", command=decrease_opacity) options_menu.add_command(label="Font", command=font_window) root.config(menu=menu_bar) paned_window = tk.PanedWindow(root, sashrelief="groove", sashwidth=5, orient="horizontal") paned_window.pack(expand=True, fill="both") untranslated_textbox = tk.Text(paned_window, wrap="word") paned_window.add(untranslated_textbox) translated_textbox = tk.Text(paned_window, wrap="word") paned_window.add(translated_textbox) prompt_textbox = tk.Text(paned_window, wrap="word") paned_window.add(prompt_textbox) update_display(prompt_textbox, prompt_text) retranslate_button = tk.Button(root, text="Copy", command=retranslate) retranslate_button.place(relx=0, rely=1, anchor="sw") toggle_button = tk.Button(root, text="Hide", command=toggle_translated, relief=tk.RAISED) toggle_button.place(relx=0.5, rely=1, anchor="s") pause_button = tk.Button(root, text="Pause", command=toggle_pause_monitoring, relief=tk.RAISED) pause_button.place(relx=1, rely=1, anchor="se") if __name__ == "__main__": print("Starting Clipboard Translator…\n") clipboard_monitor_thread = threading.Thread(target=clipboard_monitor) clipboard_monitor_thread.start() root.mainloop()
0decb2ec97c9826f0f83354d4147fae6
{ "intermediate": 0.3926880359649658, "beginner": 0.4322480857372284, "expert": 0.1750638335943222 }
2,459
import { Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, Divider, FormControlLabel, Stack, Typography, } from “@mui/material”; import FormatPrice from “…/…/Common/FormatPrice”; import {FormattedNumber} from “react-intl”; import React, {useEffect, useState} from “react”; import {useSnackbar} from “notistack”; import {useAuthContext} from “…/…/AuthProvider/AuthProvider”; import {useApiKeyProvider} from “…/…/…/providers/ApiKeyProvider/ApiKeyProvider”; import {SpotBalanceProps} from “./SpotBalance.props”; import {useBinanceWsProvider} from “…/…/…/providers/BinanceWsProvider/BinanceWsProvider”; import {useSelector} from “react-redux”; import {AppState} from “…/…/…/store/store”; import {selectSpotBinanceSymbolState} from “…/…/…/store/binanceSymbol”; import {convertAssets} from “…/…/…/actions/cicap-diary-account”; const skipAssets = [“BNB”, “DNT”, “DON”, “ETHW”]; const SpotBalance = ({spotBalances}: SpotBalanceProps) => { const [spotFinResult] = useState(0); const [convertBalances, setConvertBalances] = useState<SpotBalanceElementPriceChecked[]>([]); const [showConvertSpotBalanceModal, setShowConvertSpotBalanceModal] = useState(false); const {diaryToken} = useAuthContext(); const {selectedSingleApiKey} = useApiKeyProvider(); const {enqueueSnackbar} = useSnackbar(); const {spotSubscribe} = useBinanceWsProvider(); const symbols = useSelector(selectSpotBinanceSymbolState); const handleChangeModal = (asset: string, event: boolean) => { setConvertBalances(prevState => prevState?.map(b => b.asset === asset ? ({…b, checked: event}) : b)); }; const convertAssetsHandler = () => { const assets = convertBalances?.filter(a => a.checked === true).map(a => a.asset); if (assets.length === 0) { enqueueSnackbar(“Выберите монеты для конвертации.”, {variant: “error”}); return; } if (!diaryToken || null === selectedSingleApiKey) return; convertAssets(selectedSingleApiKey, diaryToken, assets) .then(data => { if (!data) return; if (data.result) { enqueueSnackbar(“Конвертация завершена успешно.”, {variant: “success”}); } setShowConvertSpotBalanceModal(false); }); }; useEffect(() => { if (symbols.length === 0) return; convertBalances .filter(symbol => symbols.includes(${symbol.asset}USDT.toUpperCase())) .forEach((symbol: SpotBalanceElementPriceChecked) => { spotSubscribe(${symbol.asset}usdt.toLowerCase()); }); }, [convertBalances, symbols]); useEffect(() => { setConvertBalances( spotBalances .filter(b => !skipAssets.includes(b.asset)) .map(a => ({…a, checked: false})), ); }, [spotBalances]); return <> <Box sx={{backgroundColor: “#f5f5f5”, borderRadius: “8px”, p: 2, mb: 2}}> <Typography fontWeight=“bold”>Спотовый счет</Typography> <Typography color={spotFinResult >= 0 ? theme => theme.palette.green.main : “red”} fontSize=“xx-large” fontWeight=“bold”> {spotFinResult > 0 ? “+” : “”}{FormatPrice({amount: spotFinResult, currency_iso_code: “USD”})} </Typography> <Divider sx={{mb: 2}} /> { spotBalances?.map((balance) => { return <Stack direction=“row” justifyContent=“space-between” alignItems=“center” key={balance.asset}> <Typography>{balance.asset}</Typography> <Typography> <FormattedNumber value={balance.free} minimumFractionDigits={2} maximumFractionDigits={10} /> </Typography> </Stack>; }) } <Divider sx={{my: 2}} /> <Box sx={{display: “flex”, justifyContent: “center”, fontSize: “small”}} > <Button variant=“contained” sx={{fontSize: “small”}} onClick={() => { setShowConvertSpotBalanceModal(true); }} > Конвертировать в BNB </Button> </Box> </Box> <Dialog open={showConvertSpotBalanceModal} onClose={() => { setShowConvertSpotBalanceModal(false); }} fullWidth maxWidth=“xs” > <DialogTitle>Конвертировать в BNB</DialogTitle> <DialogContent dividers sx={{px: 0}}> { convertBalances.length > 0 ? ( convertBalances?.map((balance, index) => <SpotBalanceComponent handleChangeModal={handleChangeModal} key={balance.asset} balance={balance} index={index} /> ) ) : ( <Typography>Нет монет для конвертации</Typography> ) } </DialogContent> <DialogActions> <Button variant=“contained” onClick={convertAssetsHandler} > Конвертировать </Button> </DialogActions> </Dialog> </>; }; export default SpotBalance; type SpotBalanceElementPriceChecked = { asset: string; free: number; locked: number; checked?: boolean; lastPrice?: string; } type SpotBalanceComponentType = { balance: SpotBalanceElementPriceChecked; handleChangeModal: (asset: string, event: boolean) => void; index: number; } const SpotBalanceComponent = ({balance, handleChangeModal, index}:SpotBalanceComponentType) => { const price = useSelector((state: AppState) => state.binancePrice.spot[${balance.asset}usdt.toLowerCase()]); console.log(price); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { handleChangeModal(balance.asset, event.target.checked); }; return <Stack direction=“row” justifyContent=“space-between” alignItems=“center” sx={{ backgroundColor: (index - 1) % 2 ? “#f5f5f5” : “#ffffff”, px: 2, }} > <FormControlLabel control={ <Checkbox name=“spot-balance-element-checkbox” disabled={balance.free === 0} checked={balance.checked} onChange={handleChange} /> } label={balance.asset} /> <Stack direction=“column” alignItems=“flex-end” justifyContent=“center” spacing={0} py={1}> <Typography fontSize=“small” fontWeight=“bold” sx={{lineHeight: 1.2}}> <FormattedNumber value={balance.free} minimumFractionDigits={2} maximumFractionDigits={10} /> </Typography> <Typography fontSize=“small” sx={{lineHeight: 1.2}}> { price && +price !== 0 ? <FormatPrice amount={+price * balance.free} currency_iso_code=“USD” /> : <></> } </Typography> </Stack> </Stack>; }; import {BinanceWsProviderProps} from “./BinanceWsProvider.props”; import {ReadyState, useBinancePrice} from “…/…/hooks/binancePrices”; import {createContext, useContext, useEffect, useState} from “react”; interface BinanceWsProviderContext { futuresSubscribe: (symbol: string) => void; futuresUnsubscribe: (symbol: string) => void; futuresReadyState: number; spotSubscribe: (symbol: string) => void; spotUnsubscribe: (symbol: string) => void; spotReadyState: number; } const defaultContextValue: BinanceWsProviderContext = { futuresSubscribe: (symbol: string) => {}, futuresUnsubscribe: (symbol: string) => {}, futuresReadyState: 0, spotSubscribe: (symbol: string) => {}, spotUnsubscribe: (symbol: string) => {}, spotReadyState: 0, }; const Context = createContext(defaultContextValue); export function useBinanceWsProvider() { return useContext(Context); } const BinanceWsProvider = ({children}: BinanceWsProviderProps) => { const [futuresSymbols, setFuturesSymbols] = useState<Array<string>>([]); const [futuresQueue, setFuturesQueue] = useState<Array<string>>([]); const [spotSymbols, setSpotSymbols] = useState<Array<string>>([]); const [spotQueue, setSpotQueue] = useState<Array<string>>([]); const { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, } = useBinancePrice(); const futuresSymbolSubscribe = (symbol: string) => { if (futuresSymbols.includes(symbol) || futuresQueue.includes(symbol)) return; setFuturesQueue(prev => […prev, symbol]); }; const futuresSymbolUnsubscribe = (symbol: string) => { if (!futuresSymbols.includes(symbol) && !futuresQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // futuresUnsubscribe(symbol); setFuturesQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromFuturesQueue = () => { futuresQueue.forEach(symbol => { futuresSubscribe(symbol); }); setFuturesSymbols([…futuresSymbols, …futuresQueue]); setFuturesQueue([]); }; useEffect(() => { if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresQueue]); useEffect(() => { if (futuresReadyState === ReadyState.CLOSED) { setFuturesQueue([…futuresSymbols, …futuresQueue]); setFuturesSymbols([]); } if (futuresQueue.length > 0 && futuresReadyState === ReadyState.OPEN) { subscribeFromFuturesQueue(); } }, [futuresReadyState]); const spotSymbolSubscribe = (symbol: string) => { if (spotSymbols.includes(symbol) || spotQueue.includes(symbol)) return; setSpotQueue(prev => […prev, symbol]); }; const spotSymbolUnsubscribe = (symbol: string) => { if (!spotSymbols.includes(symbol) && !spotQueue.includes(symbol)) return; // TODO: сделать счетчик слушателей, если все отпишутся - отправлять UNSUBSCRIBE // spotUnsubscribe(symbol); setSpotQueue(prev => prev.filter(item => item !== symbol)); }; const subscribeFromSpotQueue = () => { spotQueue.forEach(symbol => { spotSubscribe(symbol); }); setSpotSymbols([…spotSymbols, …spotQueue]); setSpotQueue([]); }; useEffect(() => { if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotQueue]); useEffect(() => { if (spotReadyState === ReadyState.CLOSED) { setSpotQueue([…spotSymbols, …spotQueue]); setSpotSymbols([]); } if (spotQueue.length > 0 && spotReadyState === ReadyState.OPEN) { subscribeFromSpotQueue(); } }, [spotReadyState]); return <Context.Provider value={{ futuresSubscribe: futuresSymbolSubscribe, futuresUnsubscribe: futuresSymbolUnsubscribe, futuresReadyState: futuresReadyState, spotSubscribe: spotSymbolSubscribe, spotUnsubscribe: spotSymbolUnsubscribe, spotReadyState: spotReadyState, }} > {children} </Context.Provider>; }; export default BinanceWsProvider; import {useCallback, useEffect, useReducer, useState} from “react”; import {useDispatch} from “react-redux”; import {setFuturesBinancePriceState, setSpotBinancePriceState} from “…/store/binancePriceSlice”; export enum ReadyState { UNINSTANTIATED = -1, CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3, } export function useBinancePrice() { const stream = “@ticker”; const dispatch = useDispatch(); const [futuresWs, setFuturesWs] = useState<WebSocket|null>(null); const [futuresReadyState, setFuturesReadyState] = useState(0); const [spotWs, setSpotWs] = useState<WebSocket|null>(null); const [spotReadyState, setSpotReadyState] = useState(0); const connectToWs = () => { if (“undefined” === typeof window) { setTimeout(“connectToWs”, 1000); return; } setFuturesWs(new WebSocket(“wss://fstream.binance.com/stream”)); setSpotWs(new WebSocket(“wss://stream.binance.com:9443/stream”)); }; const futuresSubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “SUBSCRIBE”, params: [ ${symbol}${stream}, ], })); }, [futuresReadyState]); const futuresUnsubscribe = useCallback((symbol: string) => { if (null === futuresWs || futuresReadyState !== ReadyState.OPEN) return; futuresWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “UNSUBSCRIBE”, params: [ ${symbol}${stream}, ], })); }, [futuresReadyState]); useEffect(() => { if (null === futuresWs) return; futuresWs.onmessage = (message: MessageEvent) => { if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setFuturesBinancePriceState({symbol: data.stream.replace(stream, “”), price: data.data.c})); }; futuresWs.onopen = () => { setFuturesReadyState(ReadyState.OPEN); }; futuresWs.onclose = () => { setFuturesReadyState(ReadyState.CLOSED); }; }, [futuresWs]); const spotSubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “SUBSCRIBE”, params: [ ${symbol}${stream}, ], })); // console.log(spotWs); }, [spotReadyState]); const spotUnsubscribe = useCallback((symbol: string) => { if (null === spotWs || spotReadyState !== ReadyState.OPEN) return; spotWs.send(JSON.stringify({ id: ((new Date()).getTime() + Math.random() * 10000).toFixed(0), method: “UNSUBSCRIBE”, params: [ ${symbol}${stream}, ], })); // console.log(spotWs); }, [spotReadyState]); useEffect(() => { if (null === spotWs) return; spotWs.onmessage = (message: MessageEvent) => { // console.log(“message”, message); if (!message.data) return; const data = JSON.parse(message.data); if (!data?.stream) return; dispatch(setSpotBinancePriceState({symbol: data.stream.replace(stream, “”), price: data.data.c})); }; spotWs.onopen = () => { setSpotReadyState(ReadyState.OPEN); }; spotWs.onclose = () => { setSpotReadyState(ReadyState.CLOSED); }; }, [spotWs]); useEffect(() => { connectToWs(); }, []); return { futuresSubscribe, futuresUnsubscribe, futuresReadyState, spotSubscribe, spotUnsubscribe, spotReadyState, }; } import {createSlice} from “@reduxjs/toolkit”; import {HYDRATE} from “next-redux-wrapper”; export interface BinancePriceSlice { futures: {[key: string]: number}; spot: {[key: string]: number}; } const initialState: BinancePriceSlice = { futures: {}, spot: {}, }; export const binancePriceSlice = createSlice({ name: “binancePrice”, initialState, reducers: { setFuturesBinancePriceState(state, action) { state.futures[action.payload.symbol] = action.payload.price; }, setSpotBinancePriceState(state, action) { state.spot[action.payload.symbol] = action.payload.price; }, }, extraReducers: { [HYDRATE]: (state, action) => { return { …state, …action.payload, }; }, }, }); export const { setFuturesBinancePriceState, setSpotBinancePriceState, } = binancePriceSlice.actions; export default binancePriceSlice.reducer; проанализируй код и функцию const SpotBalanceComponent = ({balance, handleChangeModal, index}:SpotBalanceComponentType) => { const price = useSelector((state: AppState) => state.binancePrice.spot[${balance.asset}usdt.toLowerCase()]); как работает const price и почему он всегда undefined? ошибка приходит в useEffect(() => { if (null === spotWs) return; spotWs.onmessage = (message: MessageEvent) => { console.log("message", message); error : code : 2 msg : "Invalid request: request ID must be an unsigned integer" [[Prototype]] : Object
3f272a415e65ac9414d245b7c87898e4
{ "intermediate": 0.3387148976325989, "beginner": 0.4292478561401367, "expert": 0.2320372462272644 }
2,460
Give python code to return key name in a dict that contains a specific string in it.
ccb2b463b8603a5ba3d0abe709c62c56
{ "intermediate": 0.45644158124923706, "beginner": 0.15591315925121307, "expert": 0.38764524459838867 }
2,461
code: import cv2 import numpy as np # Define the dimensions of the court court_width = 20.0 # in feet court_length = 44.0 # in feet kitchen_length = 14.0 # in feet service_length = 7.0 # in feet basline_length = court_length - kitchen_length # Define the scale for mapping the court onto the minimap scale = 20.0 # each pixel on the minimap corresponds to 1 foot on the court # Define the colors for the court lines line_color = (255, 255, 255) # white baseline_color = (0, 255, 0) # green kitchen_color = (0, 0, 255) # red service_color = (255, 0, 0) # blue # Create the minimap image minimap_width = int(court_width * scale) minimap_length = int(court_length * scale) minimap = np.zeros((minimap_width, minimap_length, 3), dtype=np.uint8) court_lines = np.float32([[0, kitchen_length*scale], [basline_length*scale + service_length*scale, kitchen_length*scale], [basline_length*scale + service_length*scale, court_width*scale], [service_length*scale, court_width*scale]]) # Draw the court lines on the minimap cv2.rectangle(minimap, (0, 0), (minimap_length, minimap_width), line_color, thickness=2) cv2.line(minimap, (0, int(kitchen_length*scale)), (minimap_length, int(kitchen_length*scale)), line_color, thickness=2) cv2.line(minimap, (int(service_length*scale), 0), (int(service_length*scale), minimap_width), line_color, thickness=2) cv2.line(minimap, (int(basline_length*scale+service_length*scale), 0), (int(basline_length*scale+service_length*scale), minimap_width), baseline_color, thickness=2) # Initialize the video capture cap = cv2.VideoCapture('1_1.mp4') while True: # Read the video frame ret, frame = cap.read() # Convert the frame to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Apply a blur to reduce noise blur = cv2.GaussianBlur(gray, (5, 5), 0) # Apply edge detection to extract the lines edges = cv2.Canny(blur, 50, 150, apertureSize=3) # Apply Hough Transform to detect straight lines lines = cv2.HoughLinesP(edges, rho=1, theta=np.pi/180, threshold=50, minLineLength=80, maxLineGap=10) if lines is not None: # Transform the detected court lines to the minimap transform = cv2.getPerspectiveTransform(np.array(lines, np.float32), court_lines) transformed_court = cv2.warpPerspective(frame, transform, (minimap_length, minimap_width)) # Overlay the minimap onto the frame result = cv2.addWeighted(frame, 0.8, minimap, 1.0, 0.0) # Display the resulting images cv2.imshow('Original', result) cv2.imshow('Transformed', transformed_court) if cv2.waitKey(1) == ord('q'): break # Release the video capture and close all windows cap.release() cv2.destroyAllWindows() error: Traceback (most recent call last): File "/Users/surabhi/Documents/kalman/court", line 54, in <module> transform = cv2.getPerspectiveTransform(np.array(lines, np.float32), court_lines) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cv2.error: OpenCV(4.7.0) /Users/runner/work/opencv-python/opencv-python/opencv/modules/imgproc/src/imgwarp.cpp:3522: error: (-215:Assertion failed) src.checkVector(2, CV_32F) == 4 && dst.checkVector(2, CV_32F) == 4 in function 'getPerspectiveTransform'
926f1498ed5f03e33e5a64cd93497f9a
{ "intermediate": 0.39148643612861633, "beginner": 0.41653770208358765, "expert": 0.1919759064912796 }
2,462
what are the vba codes to enable calculation of a specific excel sheet, to calculate the sheet and to disable calculation of a specific sheet
9e7df8245bb532490beaa650cf7443cf
{ "intermediate": 0.46362078189849854, "beginner": 0.20693133771419525, "expert": 0.3294478952884674 }
2,463
select materialCode, materialName, defaultLocationCode, materialCategory, specification, taxRate, unitName, createTime from m_Material sql materialCode相同的只取一行
94e93dfc24ef964b693c490b9812a76a
{ "intermediate": 0.4314133822917938, "beginner": 0.2172987461090088, "expert": 0.351287841796875 }
2,464
Turtle Graphics is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like forward(…) and right(…) which can move the turtle around. Commonly used turtle methods are found in the posted pdf file “turtle — Turtle graphics — Python 3.10.2 documentation” To make use of the turtle methods and functionalities, we need to import turtle. “turtle” comes packed with the standard Python package and need not be installed externally. The roadmap for executing a turtle program follows 3 steps: a- Import the turtle module. b- Create a turtle to control. c- Draw around using the turtle methods. Problem: Based on the material presented in SS1 lecture and referring to the above reference, write a python program that produces the below diagram. Instructions: - You should use different colors for the squares. - You can choose any side’s length for each square, keeping the general view of the output similar to the given diagram. - You might place the desired colors in a list to access them by index in the drawing loop. - Make sure to properly set the starting position (x & y) of your drawing, to maintain the above diagram.
9731ea4de8d7500c33dd562aa7fac8f0
{ "intermediate": 0.48469939827919006, "beginner": 0.28242433071136475, "expert": 0.23287628591060638 }
2,465
docker cp命令报如下错误,如何处理 must specify at least one container source
ac4ec120f934d68875597e4a70d8d3ce
{ "intermediate": 0.30332568287849426, "beginner": 0.3212410807609558, "expert": 0.3754332363605499 }
2,466
elastic search 查询
c27a6103f957b752a2754a195787e895
{ "intermediate": 0.10907089710235596, "beginner": 0.11857800930738449, "expert": 0.772351086139679 }
2,467
Implement a simple pull-based cache invalidation scheme by using CSIM in C. Please note that i only have CSIM 0.02 so if there are any functions being used that aren't a part of it you will have to provide implementation. In the scheme, a node generates a query and sends a request message to a server if the queried data item is not found in its local cache. If the node generates a query that can be answered by its local cache, it sends a check message to the server for validity. The server replies to the node with a requested data item or a confirm message. A set of data items is updated in the server. This scheme ensures a strong consistency that guarantees to access the most updated data items. Note that remove a cold state before collecting any results. use the following simulation parameters .make sure to output cache hit ratio and (ii) query delay by changing mean query generation time and mean update arrival time. Parameter Values Number of clients 5 Database (DB) size 500 items Data item size 1024 bytes Bandwidth 10000 bits/s Cache size 100 items Cache replacement policy LRU Mean query generate time (T_query) 5, 10, 25, 50, 100 seconds Hot data items 1 to 50 Cold data items remainder of DB Hot data access prob. 0.8 Mean update arrival time (T_update) 5, 10, 20, 100, 200 seconds Hot data update prob. 0.33
93fb5e4078ec3d3298c09be9c08db0c5
{ "intermediate": 0.3192068636417389, "beginner": 0.2644318640232086, "expert": 0.4163612723350525 }
2,468
index_flag
b6160f30dd0bc3320bf01543abfa5cf6
{ "intermediate": 0.3180481493473053, "beginner": 0.3138839304447174, "expert": 0.3680679500102997 }
2,469
hello
de021a495406874671c168795554daf4
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
2,470
Act as a professional programmer. Your speciality is creating graphics shaders. Use your many years of experience to give clear, succinct, creative, and insightful answers to my queries. First I would like you to create a HLSL shader that takes an input and filters it to create look that emulates a CRT screen.
ba04f108d4c2c7cc307e1a7fb29af901
{ "intermediate": 0.4156282842159271, "beginner": 0.2807081639766693, "expert": 0.30366358160972595 }
2,471
I have a question regarding an SQL query in Oracle SQL. I have to select the worker which worked the shortest for every team. The table pracownicy contains all information about workers, field nazwisko is the workers surname, field zatrudniony is the date the worker was hired and id_zesp is the id of the team. I am supposed to use a subquery in this query. Is this query fine? SELECT nazwisko, zatrudniony, id_zesp FROM pracownicy WHERE zatrudniony IN (SELECT max(zatrudniony) FROM pracownicy WHERE id_zesp IS NOT NULL GROUP BY id_zesp) ORDER BY 2;
cabb56ff8312c73029499e7d5052769d
{ "intermediate": 0.39263543486595154, "beginner": 0.29841986298561096, "expert": 0.3089446425437927 }
2,472
$('input[type="radio"]').click(function () {         if ($(this).attr('value') == 'Y') {               $('#show-me').hide();           $('#id_priority').prop('required', false )         }         else {           $('#show-me').show();           $('#id_priority').prop('required', true)         }       }); i will paste other code too i will quest then
bca4c41476826501b5d940e3571237c3
{ "intermediate": 0.38202568888664246, "beginner": 0.33989590406417847, "expert": 0.2780783474445343 }
2,473
how to use discord bot to access midjourney's imagination function
d04aa66a56aa168f2132c3869d60b54b
{ "intermediate": 0.30495965480804443, "beginner": 0.24104884266853333, "expert": 0.453991562128067 }
2,474
write the code for solving integrals in python
96206f8544273e81a374d13cfbbae476
{ "intermediate": 0.30367588996887207, "beginner": 0.1397024542093277, "expert": 0.5566217303276062 }
2,475
find ./ -type f -name ".php" -o -name ".js" -o -name ".htaccess" -not -path "./bitrix/" -o -path "./upload/" -o -path "./news/" -o -path "./khm435let/" -o -path "./docs/" -o -path "./rule/" -o -path "./veteran_files/" -o -path "./digest/" -print0 | tar -czvf dump.tar.gz --null -T - find: warning: -path ./bitrix/ will not match anything because it ends with /. find: warning: -path ./upload/ will not match anything because it ends with /. find: warning: -path ./news/ will not match anything because it ends with /. find: warning: -path ./khm435let/ will not match anything because it ends with /. find: warning: -path ./docs/ will not match anything because it ends with /. find: warning: -path ./rule/ will not match anything because it ends with /. find: warning: -path ./veteran_files/ will not match anything because it ends with /. find: warning: -path ./digest/ will not match anything because it ends with /.
773356d610b90aaf2cd4c4fc10146eee
{ "intermediate": 0.3947164714336395, "beginner": 0.3331598937511444, "expert": 0.27212369441986084 }
2,476
hi
a597c7a36bac2562a66439ecdea2063a
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
2,477
net core elastic search search after
e6d5e8997ad023fc75ae491b50fd6165
{ "intermediate": 0.2649715840816498, "beginner": 0.21831271052360535, "expert": 0.5167157649993896 }
2,478
net core elastic search search after 查询数据用法
3a02dc30190e94c2605332a61c14490e
{ "intermediate": 0.23237094283103943, "beginner": 0.30329108238220215, "expert": 0.4643380045890808 }
2,479
net core elastic search search after分页
f4f83180e5eb433a9c5922cd9581ff2e
{ "intermediate": 0.2683010399341583, "beginner": 0.2708287835121155, "expert": 0.4608701765537262 }
2,480
Select an appropriate model and train it, Using google colab. The SDK includes lot of different machine learning models, choose whatever is more appropriate to the problem and outcome of analysis performed in Task 1. Discuss the whole process in detail.
df58f1c487940e482b53b4492494e280
{ "intermediate": 0.24417641758918762, "beginner": 0.1928386241197586, "expert": 0.5629850029945374 }
2,481
net core elastic search search after分页查询
540ae5e0641c72c2113f7aa890ff7c58
{ "intermediate": 0.3042488098144531, "beginner": 0.24221161007881165, "expert": 0.45353952050209045 }
2,482
elastic search search after分页
715518330f06e9324fe9b9cd34ca42e0
{ "intermediate": 0.14558586478233337, "beginner": 0.19076751172542572, "expert": 0.6636465787887573 }
2,483
Elastic Search SearchAfter分页
24078e5c2b20dbde53189022b83e5e43
{ "intermediate": 0.13599418103694916, "beginner": 0.17281889915466309, "expert": 0.6911869049072266 }
2,484
dawdasdaw
c53d31f7db709ad0a7e32f677ea59b31
{ "intermediate": 0.33738526701927185, "beginner": 0.3042748272418976, "expert": 0.35833990573883057 }
2,485
net Elastic Search SearchAfter分页
566fb5f763b8689288720c2cbe15ca29
{ "intermediate": 0.2892434895038605, "beginner": 0.2807179391384125, "expert": 0.4300385117530823 }
2,486
how to justify to end of block child element inside flex using only child element's styles
85d8f47781712efd0a8262ef9770e66f
{ "intermediate": 0.45774367451667786, "beginner": 0.23858405649662018, "expert": 0.30367228388786316 }
2,487
net core elastic search search after
049d00675eff4d0fc35d767fce726042
{ "intermediate": 0.2649715840816498, "beginner": 0.21831271052360535, "expert": 0.5167157649993896 }
2,488
net core Elastic Search SearchAfter分页查询
c3b488f55635458927ac212d8388cca8
{ "intermediate": 0.3430972695350647, "beginner": 0.2553429901599884, "expert": 0.4015597999095917 }
2,489
I have 2 sample python codes. I want to know the differences between them, which one right and good practice and why. You can also give suggestions for improvement. I shall provide the samples, if you get it.
0ce21b4fb4b61971acdcecc25b9eaa2a
{ "intermediate": 0.29463064670562744, "beginner": 0.22389459609985352, "expert": 0.48147475719451904 }
2,490
do you know the npm package ts-morph
69d0ac3c7a155084fe877acce491334d
{ "intermediate": 0.48261862993240356, "beginner": 0.17284807562828064, "expert": 0.3445333242416382 }
2,491
How do i convert a python array into a torch tensor?
898fe89b02fbbec38dd188c126faa97a
{ "intermediate": 0.4345044493675232, "beginner": 0.12049911916255951, "expert": 0.4449964165687561 }
2,492
php if paremeter == this than
0a08c856e98972712f5bc8d07395a63d
{ "intermediate": 0.3093579113483429, "beginner": 0.4110923111438751, "expert": 0.2795497477054596 }
2,493
net core Elastic Search SearchAfter分页
239e089fb65ea20b52e00cdbb2033a2c
{ "intermediate": 0.3177528381347656, "beginner": 0.29874956607818604, "expert": 0.3834976255893707 }
2,494
hi
9bb3fcbcd7014da2de80df5553490389
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
2,495
get a textarea element in python selenium
7d911d0f2b5ceef6b69e6ad0ad85df8a
{ "intermediate": 0.399386465549469, "beginner": 0.20788617432117462, "expert": 0.3927273154258728 }
2,496
how to print program pointer location in rapid code on abb robots
4da072dc4dd7c5453bdc308d835ccc57
{ "intermediate": 0.3575108051300049, "beginner": 0.1642010509967804, "expert": 0.4782881736755371 }
2,497
let's think it step by step. can you help to write a nodejs script that uses ts-morph to compare two ts source file and check the compatibility?
453527d509dad71016c5ff13e985e967
{ "intermediate": 0.5669870376586914, "beginner": 0.1934918463230133, "expert": 0.2395210862159729 }
2,498
Using the `date` command how can I read the Unix epoch?
c003cf06ea0506adcc9e83377068be99
{ "intermediate": 0.49677774310112, "beginner": 0.21352410316467285, "expert": 0.28969812393188477 }
2,499
is the below code correct? from pymavlink import mavutil import math import time class Drone: def __init__(self, system_id, connection): self.system_id = system_id self.connection = connection def set_mode(self, mode): self.connection.mav.set_mode_send( self.system_id, mavutil.mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED, mode ) def arm(self, arm=True): self.connection.mav.command_long_send(self.system_id, self.connection.target_component, mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, 0, int(arm), 0, 0, 0, 0, 0, 0) def takeoff(self, altitude): self.connection.mav.command_long_send(self.system_id, self.connection.target_component, mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, altitude) def send_waypoint(self, wp, next_wp, speed): vx, vy, vz = calculate_velocity_components(wp, next_wp, speed) self.connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_global_int_message( 10, self.system_id, self.connection.target_component, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, int(0b110111111000), int(wp[0] * 10 ** 7), int(wp[1] * 10 ** 7), wp[2], vx, vy, vz, 0, 0, 0, 0, 0 # Set vx, vy, and vz from calculated components )) def get_position(self): self.connection.mav.request_data_stream_send( self.system_id, self.connection.target_component, mavutil.mavlink.MAV_DATA_STREAM_POSITION, 1, 1) while True: msg = self.connection.recv_match(type='GLOBAL_POSITION_INT', blocking=True) if msg.get_srcSystem() == self.system_id: return (msg.lat / 10 ** 7, msg.lon / 10 ** 7, msg.alt / 10 ** 3) class PIDController: def __init__(self, kp, ki, kd, limit): self.kp = kp self.ki = ki self.kd = kd self.limit = limit self.prev_error = 0 self.integral = 0 def update(self, error, dt): derivative = (error - self.prev_error) / dt self.integral += error * dt self.integral = max(min(self.integral, self.limit), -self.limit) # Clamp the integral term output = self.kp * error + self.ki * self.integral + self.kd * derivative self.prev_error = error return output distance = 5 # Distance in meters angle = 60 # Angle in degrees kp = 0.1 ki = 0.01 kd = 0.05 pid_limit = 0.0001 pid_lat = PIDController(kp, ki, kd, pid_limit) pid_lon = PIDController(kp, ki, kd, pid_limit) def calculate_follower_coordinates(wp, distance, angle): earth_radius = 6371000.0 # in meters latitude_change = (180 * distance * math.cos(math.radians(angle))) / (math.pi * earth_radius) longitude_change = (180 * distance * math.sin(math.radians(angle))) / ( math.pi * earth_radius * math.cos(math.radians(wp[0]))) new_latitude = wp[0] + latitude_change new_longitude = wp[1] + longitude_change return (new_latitude, new_longitude, wp[2]) def calculate_velocity_components(current_wp, next_wp, speed): dx = next_wp[0] - current_wp[0] dy = next_wp[1] - current_wp[1] dz = next_wp[2] - current_wp[2] dx2 = dx ** 2 dy2 = dy ** 2 dz2 = dz ** 2 distance = math.sqrt(dx2 + dy2 + dz2) vx = (dx / distance) * speed vy = (dy / distance) * speed vz = (dz / distance) * speed return vx, vy, vz waypoints = [ (28.5861474, 77.3421320, 10), (28.5859040, 77.3420736, 10) ] the_connection = mavutil.mavlink_connection('/dev/ttyUSB0', baud=57600) master_drone = Drone(3, the_connection) follower_drone = Drone(2, the_connection) # Set mode to Guided and arm both drones for drone in [master_drone, follower_drone]: drone.set_mode(4) drone.arm() drone.takeoff(10) def abort(): print("Type 'abort' to return to Launch and disarm motors.") start_time = time.monotonic() while time.monotonic() - start_time < 7: user_input = input("Time left: {} seconds \n".format(int(7 - (time.monotonic() - start_time)))) if user_input.lower() == "abort": print("Returning to Launch and disarming motors…") for drone in [master_drone, follower_drone]: drone.set_mode(6) # RTL mode drone.arm(False) # Disarm motors return True print("7 seconds have passed. Proceeding with waypoint task...") return False mode = the_connection.mode_mapping()[the_connection.flightmode] print(f"the drone is currectly at mode {mode}") time_start = time.time() while mode == 4: if abort(): exit() if time.time() - time_start >= 1: for index, master_wp in enumerate(waypoints[:-1]): next_wp = waypoints[index + 1] master_drone.send_waypoint(master_wp, next_wp, speed=3) follower_position = master_drone.get_position() if follower_position is None: break follower_wp = calculate_follower_coordinates(follower_position, distance, angle) dt = time.time() - time_start pid_lat_output = pid_lat.update(follower_wp[0] - follower_position[0], dt) pid_lon_output = pid_lon.update(follower_wp[1] - follower_position[1], dt) adjusted_follower_wp = ( follower_wp[0] + pid_lat_output, follower_wp[1] + pid_lon_output, follower_wp[2]) follower_drone.send_waypoint(adjusted_follower_wp, next_wp, speed=3) else: mode_mapping = the_connection.mode_mapping() current_mode = the_connection.flightmode mode = mode_mapping[current_mode] time_start = time.time() time.sleep(0.1) continue break for drone in [master_drone, follower_drone]: drone.set_mode(6) drone.arm(False) the_connection.close()
7e532f105f4c58769ae65402ca0aaedb
{ "intermediate": 0.4016944169998169, "beginner": 0.4341188371181488, "expert": 0.16418682038784027 }
2,500
write R code for microarray data analysis
4255f419130b1a7a5c8d1095d70cb431
{ "intermediate": 0.44122055172920227, "beginner": 0.1744411438703537, "expert": 0.3843383193016052 }
2,501
is the below code corect? from pymavlink import mavutil import math import time class Drone: def __init__(self, system_id, connection): self.system_id = system_id self.connection = connection def set_mode(self, mode): self.connection.mav.set_mode_send( self.system_id, mavutil.mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED, mode ) def arm(self, arm=True): self.connection.mav.command_long_send(self.system_id, self.connection.target_component, mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, 0, int(arm), 0, 0, 0, 0, 0, 0) def takeoff(self, altitude): self.connection.mav.command_long_send(self.system_id, self.connection.target_component, mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, altitude) def send_waypoint(self, wp, next_wp, speed): vx, vy, vz = calculate_velocity_components(wp, next_wp, speed) self.connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_global_int_message( 10, self.system_id, self.connection.target_component, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, int(0b110111111000), int(wp[0] * 10 ** 7), int(wp[1] * 10 ** 7), wp[2], vx, vy, vz, 0, 0, 0, 0, 0 # Set vx, vy, and vz from calculated components )) def get_position(self): self.connection.mav.request_data_stream_send( self.system_id, self.connection.target_component, mavutil.mavlink.MAV_DATA_STREAM_POSITION, 1, 1) while True: msg = self.connection.recv_match(type='GLOBAL_POSITION_INT', blocking=True) if msg.get_srcSystem() == self.system_id: return (msg.lat / 10 ** 7, msg.lon / 10 ** 7, msg.alt / 10 ** 3) def get_battery_status(self): msg = self.connection.recv_match(type='SYS_STATUS', blocking=False) if msg and msg.get_srcSystem() == self.system_id: return msg.battery_remain def get_rc_status(self): msg = self.connection.recv_match(type='RC_CHANNELS_RAW', blocking=False) if msg and msg.get_srcSystem() == self.system_id: return msg.chan8_raw def get_gps_status(self): msg = self.connection.recv_match(type='GPS_RAW_INT', blocking=False) if msg and msg.get_srcSystem() == self.system_id: return msg.satellites_visible, msg.eph class PIDController: def __init__(self, kp, ki, kd, limit): self.kp = kp self.ki = ki self.kd = kd self.limit = limit self.prev_error = 0 self.integral = 0 def update(self, error, dt): derivative = (error - self.prev_error) / dt self.integral += error * dt self.integral = max(min(self.integral, self.limit), -self.limit) # Clamp the integral term output = self.kp * error + self.ki * self.integral + self.kd * derivative self.prev_error = error return output distance = 5 # Distance in meters angle = 60 # Angle in degrees kp = 0.1 ki = 0.01 kd = 0.05 pid_limit = 0.0001 pid_lat = PIDController(kp, ki, kd, pid_limit) pid_lon = PIDController(kp, ki, kd, pid_limit) def calculate_follower_coordinates(wp, distance, angle): earth_radius = 6371000.0 # in meters latitude_change = (180 * distance * math.cos(math.radians(angle))) / (math.pi * earth_radius) longitude_change = (180 * distance * math.sin(math.radians(angle))) / ( math.pi * earth_radius * math.cos(math.radians(wp[0]))) new_latitude = wp[0] + latitude_change new_longitude = wp[1] + longitude_change return (new_latitude, new_longitude, wp[2]) def calculate_velocity_components(current_wp, next_wp, speed): dx = next_wp[0] - current_wp[0] dy = next_wp[1] - current_wp[1] dz = next_wp[2] - current_wp[2] dx2 = dx ** 2 dy2 = dy ** 2 dz2 = dz ** 2 distance = math.sqrt(dx2 + dy2 + dz2) vx = (dx / distance) * speed vy = (dy / distance) * speed vz = (dz / distance) * speed return vx, vy, vz def check_safety(master_drone, follower_drone): # 1. Check battery levels master_battery = master_drone.get_battery_status() follower_battery = follower_drone.get_battery_status() if master_battery is not None and master_battery < 25 or follower_battery is not None and follower_battery < 25: print("Battery low!") return False # 2. Check RC fail master_rc_status = master_drone.get_rc_status() follower_rc_status = follower_drone.get_rc_status() if master_rc_status is not None and master_rc_status < 1000 or follower_rc_status is not None and follower_rc_status < 1000: print("RC fail!") return False # 3. Check GPS fail master_gps_status = master_drone.get_gps_status() follower_gps_status = follower_drone.get_gps_status() if master_gps_status is not None and master_gps_status[0] < 6 or follower_gps_status is not None and follower_gps_status[0] < 6 or <br/> master_gps_status is not None and master_gps_status[1] > 200 or <br/> follower_gps_status is not None and follower_gps_status[1] > 200: print("GPS fail!") return False return True waypoints = [ (28.5861474, 77.3421320, 10), (28.5859040, 77.3420736, 10) ] the_connection = mavutil.mavlink_connection('/dev/ttyUSB0', baud=57600) master_drone = Drone(3, the_connection) follower_drone = Drone(2, the_connection) # Set mode to Guided and arm both drones for drone in [master_drone, follower_drone]: drone.set_mode(4) drone.arm() drone.takeoff(10) def abort(): print("Type 'abort' to return to Launch and disarm motors.") start_time = time.monotonic() while time.monotonic() - start_time < 7: user_input = input("Time left: {} seconds \n".format(int(7 - (time.monotonic() - start_time)))) if user_input.lower() == "abort": print("Returning to Launch and disarming motors…") for drone in [master_drone, follower_drone]: drone.set_mode(6) # RTL mode drone.arm(False) # Disarm motors return True print("7 seconds have passed. Proceeding with waypoint task...") return False mode = the_connection.mode_mapping()[the_connection.flightmode] print(f"the drone is currectly at mode {mode}") time_start = time.time() while mode == 4: if abort(): exit() # Keep checking safety safeguards if not check_safety(master_drone, follower_drone): break if time.time() - time_start >= 1: for index, master_wp in enumerate(waypoints[:-1]): next_wp = waypoints[index + 1] master_drone.send_waypoint(master_wp, next_wp, speed=3) follower_position = master_drone.get_position() if follower_position is None: break follower_wp = calculate_follower_coordinates(follower_position, distance, angle) dt = time.time() - time_start pid_lat_output = pid_lat.update(follower_wp[0] - follower_position[0], dt) pid_lon_output = pid_lon.update(follower_wp[1] - follower_position[1], dt) adjusted_follower_wp = ( follower_wp[0] + pid_lat_output, follower_wp[1] + pid_lon_output, follower_wp[2]) follower_drone.send_waypoint(adjusted_follower_wp, next_wp, speed=3) else: mode_mapping = the_connection.mode_mapping() current_mode = the_connection.flightmode mode = mode_mapping[current_mode] time_start = time.time() time.sleep(0.1) continue break for drone in [master_drone, follower_drone]: drone.set_mode(6) drone.arm(False) the_connection.close()
187a306a1c4a01279ab4240e800bc887
{ "intermediate": 0.42279723286628723, "beginner": 0.4109477400779724, "expert": 0.16625505685806274 }
2,502
as we can use ts--morph to traverse the typescript AST. can you write a script to compare two AST from two source file to check if they are compatible?
5e50fb97a2f47a85b0fe854824ae3220
{ "intermediate": 0.5021289587020874, "beginner": 0.24369321763515472, "expert": 0.25417783856391907 }
2,503
hi
dc4be660333685fcb49141ad4ca3a8eb
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
2,504
Ты Андроид разработчик, пишешь на Java, Qt и Kotlin. Когда тебе ставят задачу, ты разбиваешь ее на этапы, и при возможности добавляешь примеры кода при необходимости. Текущая задача: Помоги адаптировать этот код для targetSDK 33 и minSDK 24: fun setupPermissionsRequest(activity: Activity) { if (ActivityCompat.shouldShowRequestPermissionRationale( activity, Manifest.permission.WRITE_EXTERNAL_STORAGE )) { AlertDialog.Builder(activity) .setTitle(R.string.title_permission_request) .setMessage(R.string.notify_storage_permission) .setPositiveButton(R.string.button_continue) { _, _ -> requestStoragePermissions(activity) } .setNegativeButton(R.string.button_quit) { _, _ -> activity.finishAffinity() } .show() } else { requestStoragePermissions(activity) } }
ae790da0b8ab726524a3d3f9f29bb611
{ "intermediate": 0.5708737969398499, "beginner": 0.2455075979232788, "expert": 0.1836187094449997 }
2,505
in the below code, give me the grey wolf optimization implementation for 2 drones connected with same telemetry from pymavlink import mavutil import math import time class Drone: def __init__(self, system_id, connection): self.system_id = system_id self.connection = connection def set_mode(self, mode): self.connection.mav.set_mode_send( self.system_id, mavutil.mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED, mode ) def arm(self, arm=True): self.connection.mav.command_long_send(self.system_id, self.connection.target_component, mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, 0, int(arm), 0, 0, 0, 0, 0, 0) def takeoff(self, altitude): self.connection.mav.command_long_send(self.system_id, self.connection.target_component, mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, altitude) def send_waypoint(self, wp, next_wp, speed): vx, vy, vz = calculate_velocity_components(wp, next_wp, speed) self.connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_global_int_message( 10, self.system_id, self.connection.target_component, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, int(0b110111111000), int(wp[0] * 10 ** 7), int(wp[1] * 10 ** 7), wp[2], vx, vy, vz, 0, 0, 0, 0, 0 # Set vx, vy, and vz from calculated components )) def get_position(self): self.connection.mav.request_data_stream_send( self.system_id, self.connection.target_component, mavutil.mavlink.MAV_DATA_STREAM_POSITION, 1, 1) while True: msg = self.connection.recv_match(type='GLOBAL_POSITION_INT', blocking=True) if msg.get_srcSystem() == self.system_id: return (msg.lat / 10 ** 7, msg.lon / 10 ** 7, msg.alt / 10 ** 3) def get_battery_status(self): msg = self.connection.recv_match(type='SYS_STATUS', blocking=False) if msg and msg.get_srcSystem() == self.system_id: return msg.battery_remain def get_rc_status(self): msg = self.connection.recv_match(type='RC_CHANNELS_RAW', blocking=False) if msg and msg.get_srcSystem() == self.system_id: return msg.chan8_raw def get_gps_status(self): msg = self.connection.recv_match(type='GPS_RAW_INT', blocking=False) if msg and msg.get_srcSystem() == self.system_id: return msg.satellites_visible, msg.eph class PIDController: def __init__(self, kp, ki, kd, limit): self.kp = kp self.ki = ki self.kd = kd self.limit = limit self.prev_error = 0 self.integral = 0 def update(self, error, dt): derivative = (error - self.prev_error) / dt self.integral += error * dt self.integral = max(min(self.integral, self.limit), -self.limit) # Clamp the integral term output = self.kp * error + self.ki * self.integral + self.kd * derivative self.prev_error = error return output distance = 5 # Distance in meters angle = 60 # Angle in degrees kp = 0.1 ki = 0.01 kd = 0.05 pid_limit = 0.0001 pid_lat = PIDController(kp, ki, kd, pid_limit) pid_lon = PIDController(kp, ki, kd, pid_limit) def calculate_follower_coordinates(wp, distance, angle): earth_radius = 6371000.0 # in meters latitude_change = (180 * distance * math.cos(math.radians(angle))) / (math.pi * earth_radius) longitude_change = (180 * distance * math.sin(math.radians(angle))) / ( math.pi * earth_radius * math.cos(math.radians(wp[0]))) new_latitude = wp[0] + latitude_change new_longitude = wp[1] + longitude_change return (new_latitude, new_longitude, wp[2]) def calculate_velocity_components(current_wp, next_wp, speed): dx = next_wp[0] - current_wp[0] dy = next_wp[1] - current_wp[1] dz = next_wp[2] - current_wp[2] dx2 = dx ** 2 dy2 = dy ** 2 dz2 = dz ** 2 distance = math.sqrt(dx2 + dy2 + dz2) vx = (dx / distance) * speed vy = (dy / distance) * speed vz = (dz / distance) * speed return vx, vy, vz def check_safety(master_drone, follower_drone): # 1. Check battery levels master_battery = master_drone.get_battery_status() follower_battery = follower_drone.get_battery_status() if master_battery is not None and master_battery < 25 or follower_battery is not None and follower_battery < 25: print("Battery low!") return False # 2. Check RC fail master_rc_status = master_drone.get_rc_status() follower_rc_status = follower_drone.get_rc_status() if master_rc_status is not None and master_rc_status < 1000 or follower_rc_status is not None and follower_rc_status < 1000: print("RC fail!") return False # 3. Check GPS fail master_gps_status = master_drone.get_gps_status() follower_gps_status = follower_drone.get_gps_status() if master_gps_status is not None and master_gps_status[0] < 6 or follower_gps_status is not None and follower_gps_status[0] < 6 or master_gps_status is not None and master_gps_status[1] > 200 or follower_gps_status is not None and follower_gps_status[1] > 200: print("GPS fail!") return False return True waypoints = [ (28.5861474, 77.3421320, 10), (28.5859040, 77.3420736, 10) ] the_connection = mavutil.mavlink_connection('/dev/ttyUSB0', baud=57600) master_drone = Drone(3, the_connection) follower_drone = Drone(2, the_connection) # Set mode to Guided and arm both drones for drone in [master_drone, follower_drone]: drone.set_mode(4) drone.arm() drone.takeoff(10) def abort(): print("Type 'abort' to return to Launch and disarm motors.") start_time = time.monotonic() while time.monotonic() - start_time < 7: user_input = input("Time left: {} seconds \n".format(int(7 - (time.monotonic() - start_time)))) if user_input.lower() == "abort": print("Returning to Launch and disarming motors…") for drone in [master_drone, follower_drone]: drone.set_mode(6) # RTL mode drone.arm(False) # Disarm motors return True print("7 seconds have passed. Proceeding with waypoint task...") return False mode = the_connection.mode_mapping()[the_connection.flightmode] print(f"the drone is currectly at mode {mode}") time_start = time.time() while mode == 4: if abort(): exit() # Keep checking safety safeguards if not check_safety(master_drone, follower_drone): break if time.time() - time_start >= 1: for index, master_wp in enumerate(waypoints[:-1]): next_wp = waypoints[index + 1] master_drone.send_waypoint(master_wp, next_wp, speed=3) follower_position = master_drone.get_position() if follower_position is None: break follower_wp = calculate_follower_coordinates(follower_position, distance, angle) dt = time.time() - time_start pid_lat_output = pid_lat.update(follower_wp[0] - follower_position[0], dt) pid_lon_output = pid_lon.update(follower_wp[1] - follower_position[1], dt) adjusted_follower_wp = ( follower_wp[0] + pid_lat_output, follower_wp[1] + pid_lon_output, follower_wp[2]) follower_drone.send_waypoint(adjusted_follower_wp, next_wp, speed=3) else: mode_mapping = the_connection.mode_mapping() current_mode = the_connection.flightmode mode = mode_mapping[current_mode] time_start = time.time() time.sleep(0.1) continue break for drone in [master_drone, follower_drone]: drone.set_mode(6) drone.arm(False) the_connection.close()
081172518ca80a81370abee1d12a4a6c
{ "intermediate": 0.3446667194366455, "beginner": 0.4273698925971985, "expert": 0.2279633730649948 }
2,506
将以下VB代码转换为HTML代码(按下按钮后执行): set aa=createobject("scripting.filesystemobject") aa.createtextfile "aaaaaaaa.aaa"
05944ff60a106dec48d74f164b205172
{ "intermediate": 0.3760968744754791, "beginner": 0.37769845128059387, "expert": 0.24620471894741058 }