row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
44,979
///TODO // The value of N is provided in R5 and the value of K is in R6. // There are N values stored in an array starting at address K. // Sum these values and store the result in memory location 0. // The value of N is provided in R5 and the value of K is in R6. // N == @R5 // the number of values in the array // K = @R6 // starting address // @R0 == 0 // N -> R7 @R5 D=M @N M=D // K -> R6 @R6 D=M @K M=D // 0 -> i @R0 D=A @i M=D // sum -> R0 @R0 D=A @sum (LOOP) // if i == N, jump to END @i D=M @N D=D-M @END D;JEQ // arr[i] -> sum + arr[i] @arr D=M @i A=D+M M=-1 (END) @END 0;JMP This HACK asm. please finish it
a7cec7eb4781ecdf6c8562cda5951104
{ "intermediate": 0.30688291788101196, "beginner": 0.38995227217674255, "expert": 0.3031647801399231 }
44,980
write a python program using huggingface's transformers to perform sentiment analysis
86e0d8214655c21c43ef64bfb355201b
{ "intermediate": 0.3593715727329254, "beginner": 0.08830678462982178, "expert": 0.5523216128349304 }
44,981
write a Python program using huggingface's transformers to perform sentiment analysis
4663bfa53a2f5b3d949ddff4dddaf367
{ "intermediate": 0.4066565930843353, "beginner": 0.08609244227409363, "expert": 0.5072510242462158 }
44,982
write a python program using huggingface's transformers to perform sentiment analysis
2aa3054c9258b320ca866d9888282eba
{ "intermediate": 0.3593715727329254, "beginner": 0.08830678462982178, "expert": 0.5523216128349304 }
44,983
Give me a python program using huggingface's transformers to performan sentiment analysis
bfacc702612a9cc3e3ece8ff88cc8df0
{ "intermediate": 0.3606889247894287, "beginner": 0.0754207894206047, "expert": 0.5638903379440308 }
44,984
run python program use huggingface 's transformers to perform business analystics
5ce1546ffe9328c0d580698398d303db
{ "intermediate": 0.5462302565574646, "beginner": 0.18189963698387146, "expert": 0.27187010645866394 }
44,985
write a python code and use hugging face's chatgpt to conduct sentiment analysis
88052d600cf88632d6cbf46d03c9b905
{ "intermediate": 0.3791002333164215, "beginner": 0.1142776682972908, "expert": 0.5066220760345459 }
44,986
with a python code and use the hugging face's transformer to make sentiment analysis
d14b1a34d5b607d6a783b4749feacf62
{ "intermediate": 0.3256942331790924, "beginner": 0.15349888801574707, "expert": 0.5208068490028381 }
44,987
do not close console when python script is done or error
dfc0bcfa805731baabb9f51cba706dbb
{ "intermediate": 0.44638240337371826, "beginner": 0.2808741629123688, "expert": 0.2727434039115906 }
44,988
create me 3 actions with OpenWhisk and wsk command with this librairies : numpy matplotlib soundfile librosa IPython for analyse graph with spectrogram and expose url with fourth action
eb8d27f17f5bac268468b1c9d72a665a
{ "intermediate": 0.7994394302368164, "beginner": 0.07251498103141785, "expert": 0.12804563343524933 }
44,989
I need a buffer to be accesed by two recieve threads , how to do this using mutex in cpp
aa83ad26d97c4ffb50a6cf75791ad79c
{ "intermediate": 0.5209072232246399, "beginner": 0.1310642808675766, "expert": 0.3480284810066223 }
44,990
Привет, ты технический писатель. Переведи справку "h, --help Print help. Use -hh for more options and -hhh for even more. -k, --keep-going Build as much as possible -C=BUILD_TARGETS, --target=BUILD_TARGETS Targets to build Platform/build configuration -D=FLAGS Set variables (name[=val], "yes" if val is omitted) --host-platform-flag=HOST_PLATFORM_FLAGS Host platform flag --target-platform=TARGET_PLATFORMS Target platform --target-platform-flag=TARGET_PLATFORM_FLAG Set build flag for the last target platform -d Debug build -r Release build --build=BUILD_TYPE Build type (debug, release, profile, gprof, valgrind, valgrind-release, coverage, relwithdebinfo, minsizerel, debugnoasserts, fastdebug) https://docs.yandex-team.ru/ya-make/usage/ya_make/#build-type (default: release) --sanitize=SANITIZE Sanitizer type(address, memory, thread, undefined, leak) --race Build Go projects with race detector "
63ed4619f470b3a32b8ce8b6d4838a38
{ "intermediate": 0.3552994728088379, "beginner": 0.45247331261634827, "expert": 0.19222722947597504 }
44,991
hy
aeb231eb83ce4e7281e982ded35aa1ae
{ "intermediate": 0.3395402133464813, "beginner": 0.3001152276992798, "expert": 0.3603445589542389 }
44,992
CREATE TABLE `edu`.`test` ( `id` INT NOT NULL AUTO_INCREMENT , `user` VARCHAR(255) NOT NULL , `password` VARCHAR(255) NOT NULL ) ENGINE = InnoDB; Incorrect table definition; there can be only one auto column and it must be defined as a key
7e4ce16904fff754f909a739000c368f
{ "intermediate": 0.47325053811073303, "beginner": 0.2738021910190582, "expert": 0.25294727087020874 }
44,993
hello
e379396e0b7fd23fe7f56ff4c0da2163
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
44,994
i have historical data of crypto as csv files, i have following code to train a model on them whithout merging them,: import os import numpy as np import pandas as pd from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler def data_generator(file_paths, batch_size, train=True, scaler=None): while True: # Loop forever so the generator never terminates # Shuffle file paths to ensure random distribution of data across files np.random.shuffle(file_paths) for file_path in file_paths: data = pd.read_csv(file_path) # Split features and labels X = data.drop([ ‘Date’, ‘Symbol’, ‘y_High_1d’, ‘y_Low_1d’, ‘y_Priority_1d’, ‘y_High_2d’, ‘y_Low_2d’, ‘y_Priority_2d’, ‘y_High_3d’, ‘y_Low_3d’, ‘y_Priority_3d’, ‘y_High_5d’, ‘y_Low_5d’, ‘y_Priority_5d’], axis=1).values y_high_1d = data[‘y_High_1d’].values y_low_1d = data[‘y_Low_1d’].values y_Priority_1d = data[‘y_Priority_1d’].values y_high_2d = data[‘y_High_2d’].values y_low_2d = data[‘y_Low_2d’].values y_Priority_2d = data[‘y_Priority_2d’].values y_high_3d = data[‘y_High_3d’].values y_low_3d = data[‘y_Low_3d’].values y_Priority_3d = data[‘y_Priority_3d’].values y_high_5d = data[‘y_High_5d’].values y_low_5d = data[‘y_Low_5d’].values y_Priority_5d = data[‘y_Priority_5d’].values # Optionally, apply preprocessing here (e.g., Scaler transform) if scaler is not None and train: X = scaler.fit_transform(X) elif scaler is not None: X = scaler.transform(X) # Splitting data into batches for i in range(0, len(data), batch_size): end = i + batch_size X_batch = X[i:end] y_high_batch_1d = y_high_1d[i:end] y_low_batch_1d = y_low_1d[i:end] y_priority_batch_1d = y_priority_1d[i:end] y_high_batch_2d = y_high_2d[i:end] y_low_batch_2d = y_low_2d[i:end] y_priority_batch_2d = y_priority_2d[i:end] y_high_batch_3d = y_high_3d[i:end] y_low_batch_3d = y_low_3d[i:end] y_priority_batch_3d = y_priority_3d[i:end] y_high_batch_5d = y_high_5d[i:end] y_low_batch_5d = y_low_5d[i:end] y_priority_batch_5d = y_priority_5d[i:end] yield X_batch, [y_high_batch_1d, y_low_batch_1d,y_priority_batch_1d, y_high_batch_2d, y_low_batch_2d,y_priority_batch_2d, y_high_batch_3d, y_low_batch_3d, y_priority_batch_3d, y_high_batch_5d, y_low_batch_5d, y_priority_batch_5d] dataset_dir = r’F:\day_spot’ file_paths = [os.path.join(dataset_dir, file_name) for file_name in os.listdir(dataset_dir)] train_files, val_files = train_test_split(file_paths, test_size=0.06, random_state=42) batch_size = 72 # Optional: Initialize a scaler for data normalization scaler = StandardScaler() # Create data generators train_gen = data_generator(train_files, batch_size, train=True, scaler=scaler) val_gen = data_generator(val_files, batch_size, train=False, scaler=scaler) input_shape = (6427,) inputs = Input(shape=(input_shape,)) x = Dense(6427, activation=‘relu’, input_shape=(input_shape,)) (inputs) x = Dropout(0.35) (x) x = Dense(3200, activation=‘relu’) (x) x = Dropout(0.30) (x) x = Dense(1800, activation=‘relu’) (x) x = Dropout(0.25) (x) x = Dense(1024, activation=‘relu’) (x) x = Dropout(0.20) (x) x = Dense(512, activation=‘relu’) (x) x = Dropout(0.15) (x) x = Dense(256, activation=‘relu’) (x) x = Dropout(0.1) (x) x = Dense(128, activation=‘relu’) (x) x = Dropout(0.05) (x) x = Dense(64, activation=‘relu’) (x) x = Dropout(0.05) (x) x = Dense(32, activation=‘relu’) (x) # Defining three separate outputs out_high_1d = Dense(1, name=‘high_output_1d’)(x) # No activation, linear output out_low_1d = Dense(1, name=‘low_output_1d’)(x) # No activation, linear output out_priority_1d = Dense(1, activation=‘sigmoid’, name=‘priority_output_1d’)(x) out_high_2d = Dense(1, name=‘high_output_2d’)(x) # No activation, linear output out_low_2d = Dense(1, name=‘low_output_2d’)(x) # No activation, linear output out_priority_2d = Dense(1, activation=‘sigmoid’, name=‘priority_output_2d’)(x) out_high_3d = Dense(1, name=‘high_output_3d’)(x) # No activation, linear output out_low_3d = Dense(1, name=‘low_output_3d’)(x) # No activation, linear output out_priority_3d = Dense(1, activation=‘sigmoid’, name=‘priority_output_3d’)(x) out_high_5d = Dense(1, name=‘high_output_5d’)(x) # No activation, linear output out_low_5d = Dense(1, name=‘low_output_5d’)(x) # No activation, linear output out_priority_5d = Dense(1, activation=‘sigmoid’, name=‘priority_output_5d’)(x) # Constructing the model model = Model(inputs=inputs, outputs=[ out_high_1d, out_low_1d, out_priority_1d,out_high_2d, out_low_2d, out_priority_2d, out_high_3d, out_low_3d, out_priority_3d,out_high_5d, out_low_5d, out_priority_5d]) model.compile(optimizer=‘adam’, loss={ ‘out_high_1d’: ‘mse’, ‘out_low_1d’: ‘mse’, ‘out_priority_1d’: ‘binary_crossentropy’, ‘out_high_2d’: ‘mse’, ‘out_low_2d’: ‘mse’, ‘out_priority_2d’: ‘binary_crossentropy’, ‘out_high_3d’: ‘mse’, ‘out_low_3d’: ‘mse’, ‘out_priority_3d’: ‘binary_crossentropy’, ‘out_high_5d’: ‘mse’, ‘out_low_5d’: ‘mse’, ‘out_priority_5d’: ‘binary_crossentropy’ }, metrics={ ‘out_high_1d’: [‘mae’], ‘out_low_1d’: [‘mae’], ‘out_priority_1d’: [‘accuracy’], ‘out_high_2d’: [‘mae’], ‘out_low_2d’: [‘mae’], ‘out_priority_2d’: [‘accuracy’], ‘out_high_3d’: [‘mae’], ‘out_low_3d’: [‘mae’], ‘out_priority_3d’: [‘accuracy’], ‘out_high_5d’: [‘mae’], ‘out_low_5d’: [‘mae’], ‘out_priority_5d’: [‘accuracy’] } loss_weights={ ‘out_high_1d’: 1.0, ‘out_low_1d’: 1.0, ‘out_priority_1d’: 1.0, ‘out_high_2d’: 1.0, ‘out_low_2d’: 1.0, ‘out_priority_2d’: 1.0, ‘out_high_3d’: 1.0, ‘out_low_3d’: 1.0, ‘out_priority_3d’: 1.0, ‘out_high_5d’: 1.0, ‘out_low_5d’: 1.0, ‘out_priority_5d’: 1.0 } ) def count_samples(file_paths): total_samples = 0 for file_path in file_paths: df = pd.read_csv(file_path) samples = len(df) total_samples += samples return total_samples number_of_training_samples = count_samples(train_files) number_of_validation_samples = count_samples(val_files) print(f’Number of training samples: {number_of_training_samples}‘) print(f’Number of validation samples: {number_of_validation_samples}’) # You’ll need to determine steps_per_epoch and validation_steps based on your data size and batch size steps_per_epoch = np.ceil(number_of_training_samples / batch_size) # Replace number_of_training_samples validation_steps = np.ceil(number_of_validation_samples / batch_size) # Replace number_of_validation_samples model.fit(train_gen, steps_per_epoch=steps_per_epoch, validation_data=val_gen, validation_steps=validation_steps, epochs=10000) in this code i train a standard neural network on my data please update code so i train LSTM model instead of standard neural network
d3040a869c95737cc2bb68ffa6214d51
{ "intermediate": 0.43122562766075134, "beginner": 0.38864389061927795, "expert": 0.18013054132461548 }
44,995
Write me a java function that calculates the collision point of a ray and a quad
20d3f0f4c6eec02a499950b737a07b8a
{ "intermediate": 0.3697321116924286, "beginner": 0.2563541531562805, "expert": 0.3739136755466461 }
44,996
("mp_meeting", 0, mesh_load_window, [ (ti_on_presentation_load, [ (set_fixed_point_multiplier, 1000), # # Chat Box Background Creation # (create_mesh_overlay, "chat_background", "mesh_load_window"), # (position_set_x, pos2, 400), # Width # (position_set_y, pos2, 400), # Height # (overlay_set_size, "chat_background", pos2), # (position_set_x, pos1, 500), # Adjust for actual placement # (position_set_y, pos1, 500), # (overlay_set_color, "chat_background", 0x000000), # Black background (create_mesh_overlay, reg1, "mesh_load_window"), (position_set_x, pos1, 50), # Setting position to 0 as specified (position_set_y, pos1, 150), # This Y position can be adjusted for your needs (overlay_set_position, reg1, pos1), (position_set_x, pos2, 600), # Width (position_set_y, pos2, 600), # Height adjusting for aesthetically pleasing proportions (overlay_set_size, reg1, pos2), (overlay_set_color, reg1, 0x000000), # Black background # Chat Display (create_text_overlay, "backround_chat", "@CHAT ------------------------------", tf_scrollable_style_2), (position_set_x, pos1, 250), # Adjust based on chat background (position_set_y, pos1, 310), (overlay_set_position, "backround_chat", pos1), (overlay_set_area_size, "backround_chat", 780, 430), # Adjust width and height (overlay_set_color, "backround_chat", 0xFFFFFF), # White text # Input Field (create_simple_text_box_overlay, "input_chat"), (position_set_x, pos1, 50), # Adjust based on overall UI layout (position_set_y, pos1, 120), (overlay_set_position, "input_chat", pos1), (position_set_x, pos2, 350), # Width of the input field (position_set_y, pos2, 1000), # Height of the input field (overlay_set_size, "input_chat", pos2), # Send Message Button (create_game_button_overlay, "send_button", "@This is send button", tf_center_justify), (position_set_x, pos1, 580), # 730 (position_set_y, pos1, 110), (overlay_set_position, "send_button", pos1), # Test Buttons to the right of the chat # Test Button 1 (create_game_button_overlay, "test_button_1", "@Test 1", tf_center_justify), (position_set_x, pos1, 800), (position_set_y, pos1, 500), (overlay_set_position, "test_button_1", pos1), # Test Button 2 (create_game_button_overlay, "test_button_2", "@Test 2", tf_center_justify), (position_set_x, pos1, 800), (position_set_y, pos1, 400), (overlay_set_position, "test_button_2", pos1), (create_text_overlay, "g_little_pos_helper", "@00,00"), (overlay_set_color, "g_little_pos_helper", 0xFF0000), (position_set_x, pos1, 40), (position_set_y, pos1, 690), (overlay_set_position, "g_little_pos_helper", pos1), (presentation_set_duration, 999999), ]), (ti_on_presentation_event_state_change, [ (store_trigger_param_1, ":object"), (try_begin), (eq, ":object", "send_button"), # (overlay_get_text, s1, "input_chat"), (neg|str_is_empty, s1), # Here you can include the script to display the message or send it to a server etc. # Example: Update chat display # This is purely illustrative and may not directly apply without additional scripts or setup: # (str_store_string, s2, "@Chat_text"), # Assumed existing chat display variable # (str_store_string, s3, "@New_Message"), # The new message # (str_store_string_concat, s2, s3), # (overlay_set_text, "chat_overlay_id", s2), # Assumes an ID for the chat text overlay (presentation_set_duration, 0), # Re-launch the presentation to refresh the chat display if necessary # (start_presentation, "mp_meeting"), # (else_try), # Handle inputs for 'input_chat', 'test_button_1', 'test_button_2', etc. (try_end), ]), (ti_on_presentation_run, [ (set_fixed_point_multiplier, 1000), (mouse_get_position, pos1), (position_get_x, reg1, pos1), (position_get_y, reg2, pos1), (overlay_set_text, "g_little_pos_helper", "@{reg1},{reg2}"), # (set_fixed_point_multiplier, 1000), # (mouse_get_position, pos1), # (position_get_x, reg1, pos1), # (position_get_y, reg2, pos1), # (overlay_set_text, "g_little_pos_helper", "@{reg1},{reg2}"), # (try_begin), # (map_free), # (presentation_set_duration, 0), # (else_try), # (this_or_next|key_clicked,key_escape), # (key_clicked,key_m), # (presentation_set_duration, 0), # (try_end), ]), ]), Example: --copy header_presentations.py, header_triggers.py and ID_meshes.py to your msfiles folder for this example. local index = game.addPrsnt({ id = "myPrsnt", flags = {game.const.prsntf_read_only, game.const.prsntf_manual_end_only}, --you can initialize an array like this, without keys - they don't matter here anyway. mesh = game.const.mesh_cb_ui_main, triggers = { [game.const.ti_on_presentation_load] = function () --The const inside the [] declares a number key, similar to keyName = 123 for string keys. game.presentation_set_duration(9999999) local overlay = game.create_mesh_overlay(0, game.const.mesh_mp_ingame_menu) local position = game.pos.new() position.o.x = 0.3 position.o.y = 0.3 game.overlay_set_position(overlay, position) position.o.x = 0.5 position.o.y = 0.8 game.overlay_set_size(overlay, position) end } }) game.start_presentation(index) Rewrite warband module presentation script to lua using the example
33854cd9d4a5d5b1b35490c0cca6f626
{ "intermediate": 0.35917526483535767, "beginner": 0.43576663732528687, "expert": 0.20505809783935547 }
44,997
python confluent_kafka graceful shutdown after sigint
cbf01a7ab851af9f676578b116bc41a8
{ "intermediate": 0.45451635122299194, "beginner": 0.18453383445739746, "expert": 0.3609497845172882 }
44,998
a lua script that checks whether a point is within a rectangle (defold engine)
bb9b6ca7a0747bed04177a32c2c68b75
{ "intermediate": 0.28860682249069214, "beginner": 0.20619294047355652, "expert": 0.505200207233429 }
44,999
public static Vector3 findRayQuadIntersection(Vector3 ray1, Vector3 ray2, Vector3 v1, Vector3 v2, Vector3 v3) { // Step 1: Compute the plane equation of the quad // A plane can be defined by the normal (N) and a point on the plane (P0) Vector3 edge1 = VectorUtils.subNew(v2, v1); Vector3 edge2 = VectorUtils.subNew(v3, v1); Vector3 planeNormal = VectorUtils.cross(edge1, edge2); planeNormal.normalize(); double D = -(planeNormal.dot(v1)); // Step 2: Find the intersection point with the plane double t = -(planeNormal.dot(ray1) + D) / planeNormal.dot(ray2); if(t < 0) { return null; // The intersection is behind the ray’s origin } Vector3 intersection = VectorUtils.addNew(ray1, VectorUtils.scaleNew(ray2, t)); // Step 3: Check if the intersection point lies within the quad if(isPointInsideQuad(intersection, quad)) { return intersection; } return null; // The intersection point lies outside the quad } Add the isPointInsideQuad method
4e839818d3d6d1c6a6cdd19836358bad
{ "intermediate": 0.35424426198005676, "beginner": 0.2871261239051819, "expert": 0.35862958431243896 }
45,000
у меня есть код на пайтоне я хочу чтобы ты добавил что при нажатии на клавишу b макрос 1 раз нажимал бы на колесико мышки (просто нажимал 1 раз без повтора пока я не нажму снова) вот код: from pynput import keyboard from pynput.keyboard import Key, Controller as KeyboardController import time keyboard_controller = KeyboardController() Флаги для отслеживания состояния (включено/выключено) is_f_active = False is_f1_active = False def on_press(key): global is_f_active, is_f1_active # Проверяем, нажата ли клавиша Caps Lock if key == Key.caps_lock: is_f_active = not is_f_active # Проверяем, нажата ли клавиша F1 elif key == Key.f1: is_f1_active = not is_f1_active def perform_presses(): while True: if is_f_active: # Нажимаем и отпускаем клавишу 'f' keyboard_controller.press('f') keyboard_controller.release('f') # Пауза 0.001 секунды time.sleep(0.000004) elif is_f1_active: # Нажимаем и отпускаем клавишу 'q' keyboard_controller.press('q') keyboard_controller.release('q') # Пауза 0.001 секунды time.sleep(0.001) else: # Короткая задержка, чтобы избежать чрезмерной загрузки процессора time.sleep(0.1) Создаем слушателя клавиатуры keyboard_listener = keyboard.Listener(on_press=on_press) keyboard_listener.start() Запускаем бесконечный цикл нажатий клавиши 'f' и 'q' perform_presses()
2a439f2410e8cacf854c19313a7b9de9
{ "intermediate": 0.3478817343711853, "beginner": 0.4785386323928833, "expert": 0.1735796183347702 }
45,001
pourquoi je n'arrive pas a delete le quizz : XHRDELETE http://127.0.0.1:5000/quiz/api/v1.0/quiz/1 [HTTP/1.1 405 METHOD NOT ALLOWED 31ms] Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data ​ <script> export default { data() { return { questionnaires: [], selectedQuestionnaire: null, title : 'Mes Questionnaires: ', name: '', selectedQuestionnaire: null, newQuestion: { title: '', type: 'Question simple', option1: '', option2: '', }, } }, methods: { openForm(questionnaire) { this.selectedQuestionnaire = questionnaire; }, selectQuestionnaire(questionnaire) { fetch(`http://127.0.0.1:5000/quiz/api/v1.0/quiz/${questionnaire.id}/questions`) .then(response => response.json()) .then(json => { console.log(json); this.selectedQuestionnaire = json; this.quizId = questionnaire.id; }); }, modif(question) { // ... }, creerQuiz(name) { fetch('http://127.0.0.1:5000/quiz/api/v1.0/quiz', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name: name }), }) .then(response => response.json()) .then(json => { console.log(json); this.fetchQuestionnaires(); }); }, fetchQuestionnaires() { fetch('http://127.0.0.1:5000/quiz/api/v1.0/quiz') .then(response => response.json()) .then(json => { this.questionnaires = json; }); }, supprimerQuestion(question) { fetch(`http://127.0.0.1:5000/quiz/api/v1.0/quiz/questions/${question.id}`, { method: 'DELETE', }) .then(response => response.json()) .then(json => { console.log(json); if (json.result) { this.selectedQuestionnaire = this.selectedQuestionnaire.filter(q => q.id !== question.id); } }); }, supprimerQuestionnaire(questionnaire) { console.log(questionnaire.id); fetch(`http://127.0.0.1:5000/quiz/api/v1.0/quiz/${questionnaire.id}`, { method: 'DELETE', }) .then(response => response.json()) .then(json => { console.log(json); if (json.result) { console.log(json.result) this.questionnaires = this.questionnaires.filter(q => q.id !== questionnaire.id); } }); }, // fonction a changer pour ajouter question a un questionnaire ajouterQuestion(questionnaire) { fetch(`http://127.0.0.1:5000/quiz/api/v1.0/quiz/<int:quiz_id>/questions`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title: this.newQuestion.title, text: this.newQuestion.questionType, option1: this.newQuestion.option1, option2: this.newQuestion.option2, quizId: questionnaire.id, }), }) .then(response => response.json()) .then(json => { console.log(json); if (json.result) { this.selectedQuestionnaire.push(json.question); } }); this.newQuestion = { title: '', text: '', option1: '', option2: '', }; this.showForm = false; }, }, mounted() { this.fetchQuestionnaires(); } } </script> <template> <div> <h1>{{ title }}</h1> <h2>Creer un Quiz</h2> <input type="text" v-model="name" /> <button @click="creerQuiz(name)">Creer Quiz</button> <!-- Modifier ici pour ajoute question a un questionnaire, pb affichage bizzare --> <ul> <li v-for="questionnaire in questionnaires" :key="questionnaire.id"> {{ questionnaire.name }} <button @click="openForm(questionnaire)">Ajouter Question</button> <button @click="supprimerQuestionnaire(questionnaire)">Supprimer Questionnaire</button> <div v-if="selectedQuestionnaire === questionnaire"> <input type="text" v-model="newQuestion.title" placeholder="Title" /> <select v-model="newQuestion.type"> <option value="Question multiple">Question multiple</option> <option value="Question simple">Question simple</option> </select> <input type="text" v-model="newQuestion.option1" placeholder="Option 1" /> <input v-if="newQuestion.type === 'Question multiple'" type="text" v-model="newQuestion.option2" placeholder="Option 2" /> <button @click="ajouterQuestion">Submit</button> </div> </li> </ul> <div v-if="selectedQuestionnaire"> <div v-for="question in selectedQuestionnaire" :key="question.id"> <h2>Modifier la question {{ question.title }}</h2> <p>{{ question.questionType }}</p> <button @click="modif(question)">Modifier</button> <button @click="supprimerQuestion(question)">Supprimer</button> </div> </div> </div> </template><script> export default { data() { return { questionnaire: {}, todoModif: true } }, props: { questionnaire: Object }, methods: { remove(questionnaire) { this.$emit('remove', this.questionnaire) }, modifierItem(questionnaire) { this.todoModif = false }, updateItem(questionnaire) { this.todoModif = true this.$emit('modifier', this.questionnaire) } }, emits: ['remove', 'modifier'] } </script> <template> <div> <h1>{{ questionnaire.name }}</h1> <div class="checkbox"> <input type="checkbox" id="checkbox" v-model="questionnaire.done"> <label for="checkbox"></label> </div> </div> </template> <style scoped> </style>from flask import jsonify , abort , make_response , request, url_for from .app import app from .models import * @app.route('/quiz/api/v1.0/quiz', methods = ['GET']) def get_quizs(): return jsonify(get_list_quizs()) @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>', methods = ['GET']) def get_quiz(quiz_id): return jsonify(get_quiz_by_id(quiz_id)) @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>/questions', methods = ['GET']) def get_questions(quiz_id): question = get_questions_by_quiz_id(quiz_id) if question is not None: return jsonify(question) else: abort(404) @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>/questions/<int:question_id>', methods = ['GET']) def get_question(quiz_id, question_id): question = get_question_by_quiz_id_question(quiz_id,question_id) if question is not None: return jsonify(question) else: abort(404) @app. errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) @app. errorhandler(400) def not_found(error): return make_response(jsonify({'error': 'Bad request'}), 400) @app.route('/quiz/api/v1.0/quiz', methods = ['POST']) def create_quiz(): if not request.json or not 'name' in request.json: abort(400) return add_quiz(request.json['name']).to_json() @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>/questions', methods = ['POST']) def create_question(quiz_id): if not request.json or not 'title' in request.json or not 'questionType' in request.json: abort(400) return add_question(quiz_id,request.json).to_json() @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>', methods = ['PUT']) def update_quiz(quiz_id): quiz = [get_quiz_by_id(quiz_id)] if len(quiz) == 0: abort(404) if not request.json: abort(400) if 'name' in request.json and type(request.json['name']) != str: abort(400) update_quiz_name(quiz_id, request.json.get('name', quiz[0]['name'])) quiz[0]['name'] = request.json.get('name', quiz[0]['name']) return jsonify({'quiz': quiz[0]}) @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>', methods = ['DELETE']) def delete_task(quiz_id): quiz = [get_quiz_by_id(quiz_id)] if len(quiz) == 0: abort(404) del_quiz(quiz_id) return jsonify({'result': True}) @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>/questions/<int:question_id>', methods = ['PUT']) def update_question(quiz_id, question_id,): if not request.json or not 'title' in request.json or not 'questionType' in request.json: abort(400) question = [get_questions_by_question_id(question_id)] if len(question) == 0: abort(404) return jsonify(update_questionn( question_id,request.json)) @app.route('/quiz/api/v1.0/quiz/questions/<int:question_id>', methods = ['DELETE']) def delete_question(question_id): question = [get_questions_by_question_id(question_id)] if len(question) == 0: abort(404) del_question(question_id) return jsonify({'result': True})
9e186c86097eef43448d542ff84d843a
{ "intermediate": 0.29916810989379883, "beginner": 0.5890454649925232, "expert": 0.11178640276193619 }
45,002
pourquoi je n'arrive pas a delete le quizz : XHRDELETE http://127.0.0.1:5000/quiz/api/v1.0/quiz/1 [HTTP/1.1 405 METHOD NOT ALLOWED 31ms] Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data ​ <script> export default { data() { return { questionnaires: [], selectedQuestionnaire: null, title : 'Mes Questionnaires: ', name: '', selectedQuestionnaire: null, newQuestion: { title: '', type: 'Question simple', option1: '', option2: '', }, } }, methods: { openForm(questionnaire) { this.selectedQuestionnaire = questionnaire; }, selectQuestionnaire(questionnaire) { fetch(`http://127.0.0.1:5000/quiz/api/v1.0/quiz/${questionnaire.id}/questions`) .then(response => response.json()) .then(json => { console.log(json); this.selectedQuestionnaire = json; this.quizId = questionnaire.id; }); }, modif(question) { // ... }, creerQuiz(name) { fetch('http://127.0.0.1:5000/quiz/api/v1.0/quiz', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name: name }), }) .then(response => response.json()) .then(json => { console.log(json); this.fetchQuestionnaires(); }); }, fetchQuestionnaires() { fetch('http://127.0.0.1:5000/quiz/api/v1.0/quiz') .then(response => response.json()) .then(json => { this.questionnaires = json; }); }, supprimerQuestion(question) { fetch(`http://127.0.0.1:5000/quiz/api/v1.0/quiz/questions/${question.id}`, { method: 'DELETE', }) .then(response => response.json()) .then(json => { console.log(json); if (json.result) { this.selectedQuestionnaire = this.selectedQuestionnaire.filter(q => q.id !== question.id); } }); }, supprimerQuestionnaire(questionnaire) { console.log(questionnaire.id); fetch(`http://127.0.0.1:5000/quiz/api/v1.0/quiz/${questionnaire.id}`, { method: 'DELETE', }) .then(response => response.json()) .then(json => { console.log(json); if (json.result) { console.log(json.result) this.questionnaires = this.questionnaires.filter(q => q.id !== questionnaire.id); } }); }, // fonction a changer pour ajouter question a un questionnaire ajouterQuestion(questionnaire) { fetch(`http://127.0.0.1:5000/quiz/api/v1.0/quiz/<int:quiz_id>/questions`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title: this.newQuestion.title, text: this.newQuestion.questionType, option1: this.newQuestion.option1, option2: this.newQuestion.option2, quizId: questionnaire.id, }), }) .then(response => response.json()) .then(json => { console.log(json); if (json.result) { this.selectedQuestionnaire.push(json.question); } }); this.newQuestion = { title: '', text: '', option1: '', option2: '', }; this.showForm = false; }, }, mounted() { this.fetchQuestionnaires(); } } </script> <template> <div> <h1>{{ title }}</h1> <h2>Creer un Quiz</h2> <input type="text" v-model="name" /> <button @click="creerQuiz(name)">Creer Quiz</button> <!-- Modifier ici pour ajoute question a un questionnaire, pb affichage bizzare --> <ul> <li v-for="questionnaire in questionnaires" :key="questionnaire.id"> {{ questionnaire.name }} <button @click="openForm(questionnaire)">Ajouter Question</button> <button @click="supprimerQuestionnaire(questionnaire)">Supprimer Questionnaire</button> <div v-if="selectedQuestionnaire === questionnaire"> <input type="text" v-model="newQuestion.title" placeholder="Title" /> <select v-model="newQuestion.type"> <option value="Question multiple">Question multiple</option> <option value="Question simple">Question simple</option> </select> <input type="text" v-model="newQuestion.option1" placeholder="Option 1" /> <input v-if="newQuestion.type === 'Question multiple'" type="text" v-model="newQuestion.option2" placeholder="Option 2" /> <button @click="ajouterQuestion">Submit</button> </div> </li> </ul> <div v-if="selectedQuestionnaire"> <div v-for="question in selectedQuestionnaire" :key="question.id"> <h2>Modifier la question {{ question.title }}</h2> <p>{{ question.questionType }}</p> <button @click="modif(question)">Modifier</button> <button @click="supprimerQuestion(question)">Supprimer</button> </div> </div> </div> </template><script> export default { data() { return { questionnaire: {}, todoModif: true } }, props: { questionnaire: Object }, methods: { remove(questionnaire) { this.$emit('remove', this.questionnaire) }, modifierItem(questionnaire) { this.todoModif = false }, updateItem(questionnaire) { this.todoModif = true this.$emit('modifier', this.questionnaire) } }, emits: ['remove', 'modifier'] } </script> <template> <div> <h1>{{ questionnaire.name }}</h1> <div class="checkbox"> <input type="checkbox" id="checkbox" v-model="questionnaire.done"> <label for="checkbox"></label> </div> </div> </template> <style scoped> </style>from flask import jsonify , abort , make_response , request, url_for from .app import app from .models import * @app.route('/quiz/api/v1.0/quiz', methods = ['GET']) def get_quizs(): return jsonify(get_list_quizs()) @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>', methods = ['GET']) def get_quiz(quiz_id): return jsonify(get_quiz_by_id(quiz_id)) @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>/questions', methods = ['GET']) def get_questions(quiz_id): question = get_questions_by_quiz_id(quiz_id) if question is not None: return jsonify(question) else: abort(404) @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>/questions/<int:question_id>', methods = ['GET']) def get_question(quiz_id, question_id): question = get_question_by_quiz_id_question(quiz_id,question_id) if question is not None: return jsonify(question) else: abort(404) @app. errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) @app. errorhandler(400) def not_found(error): return make_response(jsonify({'error': 'Bad request'}), 400) @app.route('/quiz/api/v1.0/quiz', methods = ['POST']) def create_quiz(): if not request.json or not 'name' in request.json: abort(400) return add_quiz(request.json['name']).to_json() @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>/questions', methods = ['POST']) def create_question(quiz_id): if not request.json or not 'title' in request.json or not 'questionType' in request.json: abort(400) return add_question(quiz_id,request.json).to_json() @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>', methods = ['PUT']) def update_quiz(quiz_id): quiz = [get_quiz_by_id(quiz_id)] if len(quiz) == 0: abort(404) if not request.json: abort(400) if 'name' in request.json and type(request.json['name']) != str: abort(400) update_quiz_name(quiz_id, request.json.get('name', quiz[0]['name'])) quiz[0]['name'] = request.json.get('name', quiz[0]['name']) return jsonify({'quiz': quiz[0]}) @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>', methods = ['DELETE']) def delete_task(quiz_id): quiz = [get_quiz_by_id(quiz_id)] if len(quiz) == 0: abort(404) del_quiz(quiz_id) return jsonify({'result': True}) @app.route('/quiz/api/v1.0/quiz/<int:quiz_id>/questions/<int:question_id>', methods = ['PUT']) def update_question(quiz_id, question_id,): if not request.json or not 'title' in request.json or not 'questionType' in request.json: abort(400) question = [get_questions_by_question_id(question_id)] if len(question) == 0: abort(404) return jsonify(update_questionn( question_id,request.json)) @app.route('/quiz/api/v1.0/quiz/questions/<int:question_id>', methods = ['DELETE']) def delete_question(question_id): question = [get_questions_by_question_id(question_id)] if len(question) == 0: abort(404) del_question(question_id) return jsonify({'result': True})
8755e3b40558204ef10b57660391aab1
{ "intermediate": 0.29916810989379883, "beginner": 0.5890454649925232, "expert": 0.11178640276193619 }
45,003
Extract bol number. For each stop, extract: stop number, delivery number, shipment number, carrier, all items (make this an ARRAY) (product number (numerical ONLY as string), batch (string), qty (batch quantity, number), qty unit (batch quantity unit, string), weight (net weight, number), weight unit (string) and return in JSON (snake case, replace "number" with "no", null if not found).
94b61b0371867290ecf69c0070a15a4f
{ "intermediate": 0.47103530168533325, "beginner": 0.26267147064208984, "expert": 0.2662931978702545 }
45,004
game.display_message("Open meeting...", 0xFF0000) local mpMeeting = game.addPrsnt({ id = "mpMeeting", flags = {game.const.mesh_load_window}, mesh = game.const.mesh_load_window, triggers = { [game.const.ti_on_presentation_load] = function () game.presentation_set_duration(999999) -- Chat Box Background Creation local chatBackground = game.create_mesh_overlay(game.const.mesh_load_window) local bgPosition = game.pos.new() bgPosition.o.x = 0.05 -- adjusted from original script bgPosition.o.y = 0.15 game.overlay_set_position(chatBackground, bgPosition) local bgSize = game.pos.new() bgSize.o.x = 0.6 bgSize.o.y = 0.6 game.overlay_set_size(chatBackground, bgSize) game.overlay_set_color(chatBackground, 0x000000) -- Black background -- Chat Display local chatDisplay = game.create_text_overlay("@CHAT ------------------------------", game.const.tf_scrollable_style_2) local chatDisplayPosition = game.pos.new() chatDisplayPosition.o.x = 0.25 chatDisplayPosition.o.y = 0.31 game.overlay_set_position(chatDisplay, chatDisplayPosition) game.overlay_set_area_size(chatDisplay, 780, 430) -- Adjust width and height game.overlay_set_color(chatDisplay, 0xFFFFFF) -- White text -- Input Field local inputField = game.create_simple_text_box_overlay() local inputFieldPosition = game.pos.new() inputFieldPosition.o.x = 0.05 -- Adjust based on overall UI layout inputFieldPosition.o.y = 0.12 game.overlay_set_position(inputField, inputFieldPosition) game.overlay_set_size(inputField, {350, 1000}) -- Width and height of the input field -- Send Message Button local sendMessageButton = game.create_game_button_overlay("@This is send button", game.const.tf_center_justify) local sendMessageButtonPosition = game.pos.new() sendMessageButtonPosition.o.x = 0.58 sendMessageButtonPosition.o.y = 0.11 game.overlay_set_position(sendMessageButton, sendMessageButtonPosition) -- Additional setup for test buttons, text overlays, etc., following similar patterns end [game.const.ti_on_presentation_event_state_change] = function () -- Example: Checking if the "send_button" was clicked and handle appropriately. -- This part might require specific functions in Bannerlord to capture and handle UI events, not directly translatable from the Warband script. end [game.const.ti_on_presentation_run] = function () game.set_fixed_point_multiplier(1000) local mousePosition = game.mouse_get_position() local positionText = string.format("@%d,%d", mousePosition.x, mousePosition.y) -- Assuming a way to update an overlay’s text directly, which might need adjustment for Bannerlord API specifics. game.overlay_set_text("g_little_pos_helper", positionText) end } }}) game.start_presentation(mpMeeting) 49: table index is nil
9fcfe9416f2e621f0018c95d07925612
{ "intermediate": 0.3582286238670349, "beginner": 0.42032209038734436, "expert": 0.22144930064678192 }
45,005
Set Temperature = Temperature \ 100 Calculate Red: If Temperature <= 66 Then Red = 255 Else Red = Temperature - 60 Red = 329.698727446 * (Red ^ -0.1332047592) If Red < 0 Then Red = 0 If Red > 255 Then Red = 255 End If Calculate Green: If Temperature <= 66 Then Green = Temperature Green = 99.4708025861 * Ln(Green) - 161.1195681661 If Green < 0 Then Green = 0 If Green > 255 Then Green = 255 Else Green = Temperature - 60 Green = 288.1221695283 * (Green ^ -0.0755148492) If Green < 0 Then Green = 0 If Green > 255 Then Green = 255 End If Calculate Blue: If Temperature >= 66 Then Blue = 255 Else If Temperature <= 19 Then Blue = 0 Else Blue = Temperature - 10 Blue = 138.5177312231 * Ln(Blue) - 305.0447927307 If Blue < 0 Then Blue = 0 If Blue > 255 Then Blue = 255 End If End If
64b968af95ce435224d3143c781dca0f
{ "intermediate": 0.32670846581459045, "beginner": 0.2908801734447479, "expert": 0.3824113607406616 }
45,006
Hi, everything good?
99b9c91c6e5d3ec2a22ee1c4f101b38f
{ "intermediate": 0.35852915048599243, "beginner": 0.2757224142551422, "expert": 0.3657483756542206 }
45,007
So I made an analysis of cyber crime data in India 2022
dc7dfbd87a5e5a05997903485c124520
{ "intermediate": 0.3764457702636719, "beginner": 0.2760998606681824, "expert": 0.34745439887046814 }
45,008
How to implement user sign up Colyseus
4030d7158cdce9db5b33a290b76db430
{ "intermediate": 0.2994372248649597, "beginner": 0.17091067135334015, "expert": 0.5296521186828613 }
45,009
Create a http request using lua
c06a1aa1ccf07a5bf51e9d4215714d46
{ "intermediate": 0.4216207265853882, "beginner": 0.21161909401416779, "expert": 0.3667602241039276 }
45,010
loop 10 times in python. 5 different methonds
f9bdb233b9821e6c7a4c0204df127e22
{ "intermediate": 0.18008878827095032, "beginner": 0.584733784198761, "expert": 0.2351774424314499 }
45,011
import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split # Подготовка данных x = np.arange(1, 100001) y = np.sin(0.01*x) x = x.reshape(-1, 1, 1) сохздай рекурентную нейронную сеть с attention
62c458e0e66f92ad4336b32de9b8650e
{ "intermediate": 0.3609161078929901, "beginner": 0.2576708197593689, "expert": 0.3814130425453186 }
45,012
make while True class in python
47ad6b216e2e1dcffada519cdc131532
{ "intermediate": 0.16542625427246094, "beginner": 0.6699692010879517, "expert": 0.1646045744419098 }
45,013
write a simple embedding code for a neural network, make all dimensions and properties tunable via appropriate types of variables, utilize Torch and numpy
b233eb34970903d67ec203f75a6da82d
{ "intermediate": 0.2608163058757782, "beginner": 0.07832597196102142, "expert": 0.6608577370643616 }
45,014
Fitting a regression model over this data and forecasting on using that model
fa790fda8fd2557c96e986e97ba1e30b
{ "intermediate": 0.3198644816875458, "beginner": 0.18457946181297302, "expert": 0.4955560266971588 }
45,015
if session.view is not None: classification_views = [] for sample in session.view: first_frame = sample.frames.first() if first_frame.classifications and first_frame.classifications.classifications: skip_full_frame_catalog = False for classification in first_frame.classifications.classifications: start, stop, step = 0, sample.metadata.total_frame_count, 1 if classification.label == "video_split": start, stop = classification.start, classification.stop elif classification.label == "single_frames": start, stop, step = classification.start, classification.stop, classification.step else: continue frame_ids_for_classification = [ frame.id for frame in sample.frames.values() if start <= frame.frame_number <= stop and (frame.frame_number - start) % step == 0 ] if frame_ids_for_classification: classification_view = session.view.select_frames(frame_ids_for_classification) classification_views.append(classification_view) skip_full_frame_catalog = True if skip_full_frame_catalog: continue start, stop, step = 0, sample.metadata.total_frame_count, 1 frame_ids_for_default = [ frame.id for frame in sample.frames.values() if start <= frame.frame_number <= stop and (frame.frame_number - start) % step == 0 ] if frame_ids_for_default: default_view = session.view.select_frames(frame_ids_for_default) classification_views.append(default_view) for view in classification_views: first_frame = view.first() parts = first_frame.filepath.split('/') og_data_loc = os.path.join(minio_endpoint, *parts[3:]) frames_view = view.to_frames(sample_frames=True, sparse=True) first_frame = frames_view.first() parts = first_frame.filepath.split('/') bucket_name = parts[3] rest_of_path = '/'.join(parts[4:-1]) now = datetime.datetime.now() date_time_folder = now.strftime("%Y%m%d_%H%M%S") folder_path = f"fiftyone_processed_data/{rest_of_path}/{date_time_folder}" local_video_directory = os.path.join("/".join(parts[:4]), os.path.dirname(rest_of_path)) video_file_name = f"stitched_{date_time_folder}.mp4" local_video_path = os.path.join(local_video_directory, video_file_name) # Determine the video format from the first frame extension = os.path.splitext(og_data_loc)[-1].upper() data_type = extension[1:] # Remove the dot from the extension # Initialize video writer frame = cv2.imread(first_frame.filepath) height, width, layers = frame.shape codec = cv2.VideoWriter_fourcc(*'mp4v') video = cv2.VideoWriter(local_video_path, codec, view.first().metadata.frame_rate, (width, height)) for frame in frames_view: frame_path = frame.filepath frame = cv2.imread(frame_path) video.write(frame) video.release() s3_upload_path = os.path.join(folder_path, video_file_name) try: with open(local_video_path, "rb") as f: s3_client.upload_fileobj(f, bucket_name, s3_upload_path) except Exception as e: print(f"Failed to upload stitched video due to {e}") task_name = video_file_name with ApiClient(configuration) as api_client: try: twr = TaskWriteRequest(task_name, project_id=target_project) data, response = api_client.tasks_api.create(twr, org=organization) server_files = [f"{bucket_name}/{s3_upload_path}"] data_request = DataRequest(image_quality=95, server_files=server_files, use_cache=True, use_zip_chunks=False) api_client.tasks_api.create_data(data.id, upload_finish=True, upload_multiple=False, upload_start=True, data_request=data_request) print("Uploaded task to CVAT") except exceptions.ApiException as e: print(f"Exception when calling CVAT API: {e}") The goal of this code is, given a project A, cataloging project, upload to project B with a downselect of the data. This works as expected. I have realized if the user isn't splitting the data, and going to: if skip_full_frame_catalog: area, it will essentially be the unmodified file. Which means we can use the original source and do not need to s3_client.upload_fileobj(f, bucket_name, s3_upload_path). Do you understand? If so, go ahead an fix that so we prevent data duplication where possible. Give me the entire code back, no omissions.
e983fc55a5114fb209309bfb4a04758f
{ "intermediate": 0.3568347692489624, "beginner": 0.4417445659637451, "expert": 0.20142069458961487 }
45,016
i have 2 points in global space and i need to know the quaternion of them. can you write me a python script to get the quaternior from point a to point b direction
728178d177253cc859d3236c152d133b
{ "intermediate": 0.4885367453098297, "beginner": 0.15695208311080933, "expert": 0.3545111417770386 }
45,017
realiza la lógica y dame el código completo para un boton que agregue el item o currentItem a favoritos median localStorage, que al recargar no se eliminen los datos, y que el boton sirva como toggle, si un elemento ya está en el arrayFav, que se elimine si no, que se agregue, solo cuando el usuario de clic, por favor, te dejo mi código: import React, { useEffect, useState } from "react"; import { BASE_URL } from "../data/consts"; import { MdExplicit } from "react-icons/md"; import { IoBookmarkOutline, IoHeartOutline } from "react-icons/io5"; export const FetchData = ({endPoint}) => { const urlApi = BASE_URL + endPoint; const [data, setData] = useState([]); const [loading, setLoading] = useState(false); const [currentItem, setCurrentItem] = useState([]); const [aniflowFav, setAniflowFav] = useState([]); useEffect(() => { const fetchData = async () => { setLoading(true); try { const response = await fetch(urlApi); if (!response.ok) { throw new Error('Network response was not ok'); } const jsonData = await response.json(); setData(jsonData); } catch (error) { console.error('Error fetching data:', error); } finally { setLoading(false) } }; fetchData(); }, [endPoint]); useEffect(() => { try { const isLocalStorage = JSON.parse(localStorage.getItem('aniflowFav')); console.log(isLocalStorage) if (isLocalStorage !== null) { setAniflowFav(isLocalStorage); } } catch (error) { console.error('Error parsing LocalStorage data:', error); } }, []); useEffect(() => { const isLocalStorage = JSON.parse(localStorage.getItem('aniflowFav')); if (isLocalStorage && currentItem) { // Actualizar los datos existentes en localStorage con el nuevo valor de currentItem localStorage.setItem('aniflowFav', JSON.stringify([...isLocalStorage, currentItem])); } }, [currentItem]); const handleCurrentItem = (e, item) => { e.preventDefault(); setCurrentItem(item); }; return ( <> { loading && //create an array with 5 Array.from({ length: 10 }, (_, i) => ( <div className="w-40 h-56 bg-zinc-900 animate-pulse flex-shrink-0" key={i}/> )) } {!loading && data && data?.results?.map((item, i) => { return ( <a key={i} href={`${ item?.episodeId ? `/watch/${item?.episodeId}` : `/anime/${item?.id}` }`} className="overflow-hidden flex-shrink-0 snap-start w-40 relative z-10" data-anime={JSON.stringify(item)} > <img loading="lazy" className="w-40 h-56 object-cover transition relative" src={item?.image} alt={`${item?.title} Cover Image`} /> <div className="absolute inset-0 p-2 bg-gradient-to-t from-zinc-900 via-transparent to-zinc-900 flex flex-col justify-between"> <div className={`relative z-40 text-sm flex items-center ${ item?.nsfw ? "justify-between" : "justify-end" }`} > {item?.nsfw && ( <> <MdExplicit size={20} /> <span className="font-medium"></span> </> )} <div className="flex items-center gap-2"> <button onClick={(e) => handleCurrentItem(e, item)}> <IoHeartOutline size={18} /> </button> <button onClick={(e) => handleCurrentItem(e, item)}> <IoBookmarkOutline size={18} /> </button> </div> </div> <h3 className="font-medium mt-2 text-sm line-clamp-2"> {item?.title} </h3> </div> </a> ); })} </> ); };
bbc491f3dafac38f30b8b15175e3322e
{ "intermediate": 0.33971288800239563, "beginner": 0.4358547329902649, "expert": 0.22443240880966187 }
45,018
realiza la lógica y dame el código completo para un boton que agregue el item o currentItem a favoritos median localStorage, que al recargar no se eliminen los datos, y que el boton sirva como toggle, si un elemento ya está en el arrayFav, que se elimine si no, que se agregue, solo cuando el usuario de clic, por favor, te dejo mi código: import React, { useEffect, useState } from "react"; import { BASE_URL } from "../data/consts"; import { MdExplicit } from "react-icons/md"; import { IoBookmarkOutline, IoHeartOutline } from "react-icons/io5"; export const FetchData = ({endPoint}) => { const urlApi = BASE_URL + endPoint; const [data, setData] = useState([]); const [loading, setLoading] = useState(false); const [currentItem, setCurrentItem] = useState([]); const [aniflowFav, setAniflowFav] = useState([]); useEffect(() => { const fetchData = async () => { setLoading(true); try { const response = await fetch(urlApi); if (!response.ok) { throw new Error('Network response was not ok'); } const jsonData = await response.json(); setData(jsonData); } catch (error) { console.error('Error fetching data:', error); } finally { setLoading(false) } }; fetchData(); }, [endPoint]); useEffect(() => { try { const isLocalStorage = JSON.parse(localStorage.getItem('aniflowFav')); console.log(isLocalStorage) if (isLocalStorage !== null) { setAniflowFav(isLocalStorage); } } catch (error) { console.error('Error parsing LocalStorage data:', error); } }, []); useEffect(() => { const isLocalStorage = JSON.parse(localStorage.getItem('aniflowFav')); if (isLocalStorage && currentItem) { // Actualizar los datos existentes en localStorage con el nuevo valor de currentItem localStorage.setItem('aniflowFav', JSON.stringify([...isLocalStorage, currentItem])); } }, [currentItem]); const handleCurrentItem = (e, item) => { e.preventDefault(); setCurrentItem(item); }; return ( <> { loading && //create an array with 5 Array.from({ length: 10 }, (_, i) => ( <div className="w-40 h-56 bg-zinc-900 animate-pulse flex-shrink-0" key={i}/> )) } {!loading && data && data?.results?.map((item, i) => { return ( <a key={i} href={`${ item?.episodeId ? `/watch/${item?.episodeId}` : `/anime/${item?.id}` }`} className="overflow-hidden flex-shrink-0 snap-start w-40 relative z-10" data-anime={JSON.stringify(item)} > <img loading="lazy" className="w-40 h-56 object-cover transition relative" src={item?.image} alt={`${item?.title} Cover Image`} /> <div className="absolute inset-0 p-2 bg-gradient-to-t from-zinc-900 via-transparent to-zinc-900 flex flex-col justify-between"> <div className={`relative z-40 text-sm flex items-center ${ item?.nsfw ? "justify-between" : "justify-end" }`} > {item?.nsfw && ( <> <MdExplicit size={20} /> <span className="font-medium"></span> </> )} <div className="flex items-center gap-2"> <button onClick={(e) => handleCurrentItem(e, item)}> <IoHeartOutline size={18} /> </button> <button onClick={(e) => handleCurrentItem(e, item)}> <IoBookmarkOutline size={18} /> </button> </div> </div> <h3 className="font-medium mt-2 text-sm line-clamp-2"> {item?.title} </h3> </div> </a> ); })} </> ); };
287f2457dcfdf29fe2bdc0caa6f9ea83
{ "intermediate": 0.33971288800239563, "beginner": 0.4358547329902649, "expert": 0.22443240880966187 }
45,019
realiza la lógica y dame el código completo para un boton que agregue el item o currentItem a favoritos median localStorage, que al recargar no se eliminen los datos, y que el boton sirva como toggle, si un elemento ya está en el arrayFav, que se elimine si no, que se agregue, solo cuando el usuario de clic, por favor, te dejo mi código: import React, { useEffect, useState } from "react"; import { BASE_URL } from "../data/consts"; import { MdExplicit } from "react-icons/md"; import { IoBookmarkOutline, IoHeartOutline } from "react-icons/io5"; export const FetchData = ({endPoint}) => { const urlApi = BASE_URL + endPoint; const [data, setData] = useState([]); const [loading, setLoading] = useState(false); const [currentItem, setCurrentItem] = useState([]); const [aniflowFav, setAniflowFav] = useState([]); useEffect(() => { const fetchData = async () => { setLoading(true); try { const response = await fetch(urlApi); if (!response.ok) { throw new Error('Network response was not ok'); } const jsonData = await response.json(); setData(jsonData); } catch (error) { console.error('Error fetching data:', error); } finally { setLoading(false) } }; fetchData(); }, [endPoint]); useEffect(() => { try { const isLocalStorage = JSON.parse(localStorage.getItem('aniflowFav')); console.log(isLocalStorage) if (isLocalStorage !== null) { setAniflowFav(isLocalStorage); } } catch (error) { console.error('Error parsing LocalStorage data:', error); } }, []); useEffect(() => { const isLocalStorage = JSON.parse(localStorage.getItem('aniflowFav')); if (isLocalStorage && currentItem) { // Actualizar los datos existentes en localStorage con el nuevo valor de currentItem localStorage.setItem('aniflowFav', JSON.stringify([...isLocalStorage, currentItem])); } }, [currentItem]); const handleCurrentItem = (e, item) => { e.preventDefault(); setCurrentItem(item); }; return ( <> { loading && //create an array with 5 Array.from({ length: 10 }, (_, i) => ( <div className="w-40 h-56 bg-zinc-900 animate-pulse flex-shrink-0" key={i}/> )) } {!loading && data && data?.results?.map((item, i) => { return ( <a key={i} href={`${ item?.episodeId ? `/watch/${item?.episodeId}` : `/anime/${item?.id}` }`} className="overflow-hidden flex-shrink-0 snap-start w-40 relative z-10" data-anime={JSON.stringify(item)} > <img loading="lazy" className="w-40 h-56 object-cover transition relative" src={item?.image} alt={`${item?.title} Cover Image`} /> <div className="absolute inset-0 p-2 bg-gradient-to-t from-zinc-900 via-transparent to-zinc-900 flex flex-col justify-between"> <div className={`relative z-40 text-sm flex items-center ${ item?.nsfw ? "justify-between" : "justify-end" }`} > {item?.nsfw && ( <> <MdExplicit size={20} /> <span className="font-medium"></span> </> )} <div className="flex items-center gap-2"> <button onClick={(e) => handleCurrentItem(e, item)}> <IoHeartOutline size={18} /> </button> <button onClick={(e) => handleCurrentItem(e, item)}> <IoBookmarkOutline size={18} /> </button> </div> </div> <h3 className="font-medium mt-2 text-sm line-clamp-2"> {item?.title} </h3> </div> </a> ); })} </> ); };
01ae734af144a87dff1452290c301ff1
{ "intermediate": 0.33971288800239563, "beginner": 0.4358547329902649, "expert": 0.22443240880966187 }
45,020
Как мне использовать этот виртуальный класс? #include <vector> #include <Eigen/Dense> enum class parallel_type { trace_based, block_based, both, sequential }; template <class T> class procedure_iface { public: using trace = Eigen::Matrix<T, Eigen::Dynamic, 1>; using block = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; using value_type = T; procedure_iface() = default; procedure_iface(const procedure_iface<T> &) = default; procedure_iface(procedure_iface<T> &&) noexcept = default; procedure_iface<T> &operator=(const procedure_iface<T> &) = default; procedure_iface<T> &operator=(procedure_iface<T> &&) noexcept = default; virtual ~procedure_iface() = default; // Will throw exception if procedure doesn't support trace based processing virtual void run(const Eigen::Ref<const trace> &in, Eigen::Ref<trace> out) = 0; // Will throw exception if procedure doesn't support block based processing virtual void run(const Eigen::Ref<const block> &in, Eigen::Ref<block> out) = 0; virtual parallel_type type_parallel() = 0; };
ac89b99355f37966efaa99d7d63075d5
{ "intermediate": 0.4395761489868164, "beginner": 0.39093929529190063, "expert": 0.16948451101779938 }
45,021
I am making a c++ sdl based game engine, and I need your help. First write me the doxygen code block of my EventManager class, remember to explain everything in detail on how to use it too: class EventManager { public: ~EventManager(); EventManager(const EventManager&) = delete; EventManager operator=(const EventManager&) = delete; static EventManager& GetInstance() noexcept; template<typename T> void Subscribe(std::function<void(std::shared_ptr<T>)> handler); void Publish(std::shared_ptr<Event> event); void Update(); private: struct EventComparator { bool operator()(const std::shared_ptr<Event>& a, const std::shared_ptr<Event>& b) const { return a->GetPriority() < b->GetPriority(); } }; EventManager(); void PublishSDL(); std::mutex queueMutex; std::priority_queue<std::shared_ptr<Event>, std::vector<std::shared_ptr<Event>>, EventComparator> eventQueue; std::unordered_map<std::type_index, std::vector<std::function<void(std::shared_ptr<Event>)>>> subscribers; };
00dd0175aa4865992c354eceed7807e9
{ "intermediate": 0.37701094150543213, "beginner": 0.4554418921470642, "expert": 0.16754716634750366 }
45,022
Как использовать эти виртуальные классы? Покажи пример с main() #include <vector> #include <Eigen/Dense> enum class parallel_type { trace_based, block_based, both, sequential }; template <class T> class procedure_iface { public: using trace = Eigen::Matrix<T, Eigen::Dynamic, 1>; using block = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; using value_type = T; procedure_iface() = default; procedure_iface(const procedure_iface<T> &) = default; procedure_iface(procedure_iface<T> &&) noexcept = default; procedure_iface<T> &operator=(const procedure_iface<T> &) = default; procedure_iface<T> &operator=(procedure_iface<T> &&) noexcept = default; virtual ~procedure_iface() = default; // Will throw exception if procedure doesn’t support trace based processing virtual void run(const Eigen::Ref<const trace> &in, Eigen::Ref<trace> out) = 0; // Will throw exception if procedure doesn’t support block based processing virtual void run(const Eigen::Ref<const block> &in, Eigen::Ref<block> out) = 0; virtual parallel_type type_parallel() = 0; }; template <class T> class trace_procedure_iface : procedure_iface<T> { public: using trace = typename procedure_iface<T>::trace; using block = typename procedure_iface<T>::block; using procedure_iface<T>::run; using value_type = T; void run(const Eigen::Ref<const block> &in, Eigen::Ref<block> out) override { for (Eigen::Index j = 0; j < in.rows(); j++) { run(Eigen::Ref<const trace_procedure_iface<T>::trace>((in.row(j))), Eigen::Ref<trace_procedure_iface<T>::trace>((out.row(j)))); } } parallel_type type_parallel() override { return parallel_type::both; } };
d718cfe6b47d5b51cc4af605b232fc96
{ "intermediate": 0.3995737135410309, "beginner": 0.39951032400131226, "expert": 0.20091596245765686 }
45,023
how do I open a file at a path in windows command line
b5a1eab6620de4cdc2272e6156d00b7d
{ "intermediate": 0.4065145254135132, "beginner": 0.29823967814445496, "expert": 0.29524582624435425 }
45,024
I am using the below prompt to compare two names obtained from two different sources, using an LLM. I need your help to optimize this prompt. It is generating too many false positives and too many false negatives. You are a comparison tool. You only output JSON object. Plain English output will cause errors downstream. Use logical processing and direct matching without inference or interpretation beyond the data provided. Follow those rules. You will be provided with two names, each obtained from a different source. The names will be in the format [firstname] [middlename] [lastname], where the middle name is optional. Your task is to compare the first name, middle name, and last name of the two inputs and score them based on whether they are a match or a mismatch. For the first name comparison: If the first names are an exact match or if one name is a common nickname of the other (e.g., Will for William), assign a score of 1. If the first names do not match or are not recognized nicknames, assign a score of 0. No partial scores For the middle name comparison: If the middle names are an exact match, assign a score of 1. If the middle names do not match or if either name does not have a middle name, assign a score of 0. No partial scores For the last name comparison. If the last names are an exact match, assign a score of 1. If the last names do not match, assign a score of 0. No partial scores. Output: If comparison scores for ALL components (first name, middle name, and last name) are 1, then set "RESULT" to "MATCH". If the comparison score for any one component is 0, then set "RESULT" to "MISMATCH". In the "REASON" field, provide a brief explanation of the match or mismatch. You must format your output as a JSON value that adheres to a given "JSON Schema" instance. "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents. Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match exactly. The JSON output that you generate will have two aspects, "RESULT" which can have values "MATCH" or "MISMATCH", and second "REASON", where you can print any additional text. Are the following objects a match? Value 1: {application_value} Value 2: {credit_report_value} Output:
43b0b1233e3a3bb7b18073d046656e49
{ "intermediate": 0.4185725152492523, "beginner": 0.21841566264629364, "expert": 0.36301177740097046 }
45,025
hello
da247e0d9650ee2cb11e40448ff27f10
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
45,026
Why do many C developers start functions by putting the opening left bracket on a new line?
0e3cca3081fb515771413e4e11c4e3e5
{ "intermediate": 0.17607051134109497, "beginner": 0.707207441329956, "expert": 0.11672201007604599 }
45,027
@page "/productDetail/{ProductId}" <div class="container mt-5 mb-5"> <div class="row d-flex justify-content-center"> <div class="col-md-10"> <div class="card"> <div class="row"> <div class="col-md-6"> <div class="images p-3"> <div class="text-center p-4"> <img id="main-image" src="@product.ImageUrl" width="250" /> </div> <!-- Add thumbnail images --> <div class="thumbnail text-center"> <img onclick="change_image(this)" src="@product.ImageUrl" width="70"> <img onclick="change_image(this)" src="@product.ImageUrl" width="70"> </div> </div> </div> <div class="col-md-6"> <div class="product p-4"> <!-- Brand and product name --> <div class="mt-4 mb-3"> <span class="text-uppercase text-muted brand">@* Orianz *@</span> <h2 class="text-uppercase font-weight-bold">@product.Name</h2> <!-- Adjusted font size and weight --> <!-- Price --> <div class="price d-flex flex-row align-items-center"> <div class="ml-2"> <span class="old-price text-muted">@product.Price</span> <!-- Display old price --> <span class="new-price ml-2">@* Add your discounted price here *@</span> <!-- Display discounted price --> </div> </div> </div> <!-- Description --> <h4><p class="about font-size-lg">@product.Description</p></h4> <!-- Sizes --> <div class="sizes mt-5"> <h6 class="text-uppercase">Size</h6> <!-- Add radio buttons for sizes --> <label class="radio"> <input type="radio" name="size" value="S" checked> <span>S</span> </label> <!-- Add more radio buttons for other sizes --> </div> <!-- Add to cart button --> <div class="cart mt-4 align-items-center"> <button class="btn btn-danger text-uppercase mr-2 px-4">Add to cart</button> <!-- Add wishlist and share buttons --> <i class="fa fa-heart text-muted"></i> <i class="fa fa-share-alt text-muted"></i> </div> </div> </div> </div> </div> </div> </div> </div> @code { [Inject] public IProductService ProductService { get; set; } [Parameter] public string? ProductId { get; set; } public GetProductDto product { get; set; } = new GetProductDto(); protected async override Task OnParametersSetAsync() { if (!string.IsNullOrEmpty(ProductId)) { product = await ProductService.GetById(new Guid(ProductId)); } } } make this product detail page looks better
bf680918ebe791ae9a91c5d7b63adeb1
{ "intermediate": 0.3296988010406494, "beginner": 0.3919100761413574, "expert": 0.27839115262031555 }
45,028
I'm using quasar / vue. How do I make this input tag change style when selected? <input role="search" type="text" class="bux-form__text-field search-box" placeholder="Search..." v-model="searchTerm" style="width: 100%; border: none !important; margin: 0; text-align: center;" @input="updateResults" @keydown.enter.prevent="selectOption()" autofocus />
48a2e891194a5dadf8026e3248607a37
{ "intermediate": 0.6842635273933411, "beginner": 0.1572771519422531, "expert": 0.15845930576324463 }
45,029
@focus, is there an @unfocus or an equivalent in vue / quasar
05ae8744c84af58acad34570114f2801
{ "intermediate": 0.44003021717071533, "beginner": 0.2404966652393341, "expert": 0.31947314739227295 }
45,030
create a 10 step detailed list on how to market an online learning platform which offers 2 prep couses for ATI TEAS 7 and HESI A2 as well as a learning platform for ongoing nursing students to brush up on all topics and a blog with nursing education related content. The marketing steps are supposed to be a strategy for a client that is responsible for administrating the website(adding new quizzes,study guides, video tutorials, blog posts and managing students), he is tech savy but not a developer tech savy. He has used google ads but i want a wholistic strategy he can use to boost SEO and marketing broken down into absolute specifics(give urls and highly specific instructions that can be easily understood). Create a wining strategy
704d0942cce50229625de53ec259a8dc
{ "intermediate": 0.2730986475944519, "beginner": 0.3176281750202179, "expert": 0.4092731773853302 }
45,031
i need help setting this so it looks legit: AccountExpirationDate : accountExpires : AccountLockoutTime : AuthenticationPolicy : {} AuthenticationPolicySilo : {} BadLogonCount : CannotChangePassword : False CanonicalName : Certificates : {} City : CN : Aisha Bruce codePage : 0 Company : Company, Inc. CompoundIdentitySupported : {} Country : countryCode : 0 Created : Deleted : Department : Executive Description : CEO DisplayName : Aisha Bruce DistinguishedName : CN=Aisha Bruce,OU=Executive OU,OU=Staff,OU=CompanyInc,DC=LJBS,DC=netw1500,DC=ca Division : EmailAddress : EmployeeID : EmployeeNumber : Fax : GivenName : Aisha HomeDirectory : HomeDrive : HomePage : HomePhone : Initials : instanceType : isDeleted : KerberosEncryptionType : {} LastBadPasswordAttempt : LastKnownParent : LastLogonDate : LogonWorkstations : Manager : MemberOf : {} MobilePhone : Modified : Name : Aisha Bruce nTSecurityDescriptor : System.DirectoryServices.ActiveDirectorySecurity ObjectCategory : CN=Person,CN=Schema,CN=Configuration,DC=LJBS,DC=netw1500,DC=ca ObjectClass : user ObjectGUID : 54b7edd3-a89b-4057-9873-3941d60e519e objectSid : S-1-5-21-962219732-413001405-3476524154-1117 Office : Room 302 OfficePhone : Organization : OtherName : PasswordLastSet : physicalDeliveryOfficeName : Room 302 POBox : PostalCode : PrimaryGroup : CN=Domain Users,CN=Users,DC=LJBS,DC=netw1500,DC=ca primaryGroupID : 513 PrincipalsAllowedToDelegateToAccount : {} ProfilePath : ProtectedFromAccidentalDeletion : False SamAccountName : ABruce sAMAccountType : 805306368 ScriptPath : sDRightsEffective : 0 ServicePrincipalNames : {} SID : S-1-5-21-962219732-413001405-3476524154-1117 SIDHistory : {} sn : Bruce State : StreetAddress : Surname : Bruce Title : CEO userCertificate : {} UserPrincipalName : <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS> (the account expirary has to be set as February 27th, 2025 at 12 am
ecec917b757c2c1d0c0681c253f63eca
{ "intermediate": 0.4696928560733795, "beginner": 0.3135707378387451, "expert": 0.21673646569252014 }
45,032
hello
38d78ab0b57e618623033ae6e9a9d61e
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
45,033
In vue / quasar, is there a way I can set default classes for a q-btn, for instance? Like whenever i define a new q-btn it will have an active-class property without me directly needing to set it
978926c98b3b42ec74c83cc1f041b729
{ "intermediate": 0.5199771523475647, "beginner": 0.36141452193260193, "expert": 0.11860834807157516 }
45,034
hello will you help me add code in [ </script> {% render 'theme-data' %} </head> <body id="m-theme" class="{{ body_classes }}" {% if template.name == 'product' %} data-product-id="{{ product.id }}" {% endif %} > {% render 'page-transition' %} {%- liquid render 'scroll-top-button' sections 'header-group' -%} <main role="main" id="MainContent"> {{ content_for_layout }} </main> ]] ""this code ] <!-- Google Tag Manager (noscript) --> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-NJZBWB6L" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) -->
5d5d7e3d11a5973334fdb0b5ed7b1a82
{ "intermediate": 0.27104002237319946, "beginner": 0.5634574890136719, "expert": 0.16550250351428986 }
45,035
how do I setup my quasar config file
1b703be44de41427f254dbb9c76f6686
{ "intermediate": 0.37817931175231934, "beginner": 0.2660556137561798, "expert": 0.35576507449150085 }
45,036
you are an expert Rust programmer and very good at algorithms. You are given the following problem: Input: A sorted vector of tuples: Vec<(u32, u32)>, representing coordinates. [(5,20), (10,20), (17,20),(25,40),(30,45),(42,45),(50,60),(55,57)] Problem: We need to keep ONLY tuples that ARE NOT inside other tuples in another vector. The first tuple of the list always will be pushed to the new vector. Example: Since the first tuple is always pushed, we will evaluate the second tuple: (10,20) -> 10 is between 5, 20 (first tuple), so it is inside. We discard it. The same occurs with (17,20), but no with (25,40). Since (25,40) does not overlap nothing from the past tuples, we pushed to the new list. (42,45) -> 42 is in between 30 and 45 (previous tuple), so we discard it. Output: a Vec<(u32, u32)> with the tuples that ARE NOT inside other tuples You need to make this the most efficient and fastest implementation. You are free to use any trick, crate, package or algorithm. You are also free to use unsafe code. Provide the code. The correct answer for that input should be: [(5,20), (25,40), (50,60)]
5637b7ecd3f044a421c28f95d1b66bd3
{ "intermediate": 0.2934414744377136, "beginner": 0.16704769432544708, "expert": 0.5395108461380005 }
45,037
Example of lua using: function spawnSquad(troop, amount, position)   local sideLen = math.floor(math.sqrt(amount))   local leftovers = amount - sideLen * sideLen   position.o.x = position.o.x - math.floor(sideLen/2) * spawnSpreadDistance   position.o.y = position.o.y - math.floor(sideLen/2) * spawnSpreadDistance   for i=1, sideLen do     for j=1, sideLen do       game.set_spawn_position(position)       game.spawn_agent(troop)       position.o.x = position.o.x + spawnSpreadDistance     end     position.o.x = position.o.x - spawnSpreadDistance * sideLen     position.o.y = position.o.y + spawnSpreadDistance   end end Example of module system: # (troop_get_slot,":troops_nr",1,":args"), # (party_count_members_of_type,":dest", "p_main_party",<troop_id>), # (try_for_range,":i",2,":troops_nr"), # (troop_get_slot,":troop_id",":i",":args"), # (party_count_members_of_type,":dest", "p_main_party",":troop_id"), I need to get a list of troops in player party. Write a lua script
7137cef05548afe053215ac7ab16f474
{ "intermediate": 0.39110347628593445, "beginner": 0.3482262194156647, "expert": 0.26067033410072327 }
45,039
what chatgpt version is this
20a6b112ceb24f5dc657fd1d0f9f39db
{ "intermediate": 0.2417256236076355, "beginner": 0.24987979233264923, "expert": 0.5083945393562317 }
45,040
hi
7afeec5aaf9a33b502baf9eb12c6bffa
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
45,041
hi there
d08681a36035e554363a7d122390ef84
{ "intermediate": 0.32885003089904785, "beginner": 0.24785484373569489, "expert": 0.42329514026641846 }
45,042
How do I change CSS when I tab-select over it, something like this? .q-btn__content:select { text-decoration: underline; }
99e9b240debea0ff53a104219044566b
{ "intermediate": 0.4423074424266815, "beginner": 0.33227232098579407, "expert": 0.22542020678520203 }
45,043
привет помоги с рефакторингом public class UIArchiveScreen : BaseUIScreen { [SerializeField] private ArchiveContent _archiveContent; [SerializeField] private PanelSearch _panelSearch; [Inject] private StatisticsProvider _statisticsProvider; private List<ArchivePanel> _currentArchivePanels; private List<ArchivePanel> _currentArchivePanelsDate; private List<ArchivePanel> _currentArchivePanelsName; public override void Initialized() { base.Initialized(); _statisticsProvider.Connecting(); var users = _statisticsProvider.GetUsers(); _statisticsProvider.Disconnect(); _archiveContent.Initialize(users); _panelSearch.Initialize(users); _panelSearch.OnChangeDate += DropdownChangedDate; _panelSearch.OnChangeName += DropdownChangedName; _currentArchivePanels = _archiveContent.ArchivePanels; _currentArchivePanelsName = _archiveContent.ArchivePanels; _currentArchivePanelsDate = _archiveContent.ArchivePanels; } private void DropdownChangedDate(string text) { List<ArchivePanel> foundDate = _archiveContent.ArchivePanels; if (text != "Все") { DateTime stringDate = DateTime.ParseExact(text, "yyyy - MM - dd", CultureInfo.InvariantCulture); foundDate = _archiveContent.ArchivePanels.FindAll(date => date._BaseUser.Date.Date == stringDate.Date); } _currentArchivePanelsDate = foundDate; UpdateContent(foundDate, _currentArchivePanelsName); } private void DropdownChangedName(string text) { List<ArchivePanel> foundName = _archiveContent.ArchivePanels; if (text != "Все") { foundName = _archiveContent.ArchivePanels.FindAll(date => date._BaseUser.Name == text); } _currentArchivePanelsName = foundName; UpdateContent(foundName, _currentArchivePanelsDate); } private void UpdateContent(IEnumerable<ArchivePanel> panelsName, IEnumerable<ArchivePanel> panelsDate) { foreach (var panel in _currentArchivePanels) { panel.Deactive(); } var panels = panelsName.Intersect(panelsDate).ToList(); foreach (var panel in panels) { panel.Active(); } } } }
65d27b53810273b9f5ca2b4ef4007c99
{ "intermediate": 0.23914465308189392, "beginner": 0.6406203508377075, "expert": 0.12023506313562393 }
45,044
I want you to act as a linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. do not write explanations. do not type commands unless I instruct you to do so. When I need to tell you something in English, I will do so by putting text inside curly brackets {like this}. My first command is pwdUser:ls Model:
22077d88cf69ed2928703b7bbd0b2ea7
{ "intermediate": 0.3085750639438629, "beginner": 0.27498680353164673, "expert": 0.41643810272216797 }
45,045
How do I make CSS underline just the "Logout" text, and not the i class? Like excluding anything with q-icon as a class? <span class="q-btn__content text-center col items-center q-anchor--skip justify-center row"><i class="q-icon notranslate material-icons" aria-hidden="true" role="img">logout</i>Logout</span>
f8b66ba592943ec25e640b0225986187
{ "intermediate": 0.3734906017780304, "beginner": 0.40736812353134155, "expert": 0.21914124488830566 }
45,046
Analyze the following text:
b44cbd71667eb09afac4880d9526665f
{ "intermediate": 0.263119637966156, "beginner": 0.3738831877708435, "expert": 0.3629971742630005 }
45,047
Assuming you are a CDO of a rideshare company, can you create a data model (star schema) of ride share related products?
42c0f096280fd15b3585ba370d61bb3b
{ "intermediate": 0.424275279045105, "beginner": 0.22210170328617096, "expert": 0.35362303256988525 }
45,048
import cv2 import numpy as np import matplotlib.pyplot as plt from Crypto.Cipher import AES from Crypto.Random import get_random_bytes # تشفير الصورة باستخدام XOR def encrypt_image(image): # توليف مفتاح تشفير عشوائي بطول أكبر key1 = np.random.randint(0, 256, size=image.shape, dtype=np.uint8) key2 = np.random.randint(0, 256, size=image.shape, dtype=np.uint8) # التشفير بواسطة XOR متعدد المراحل encrypted_image = cv2.bitwise_xor(image, key1) encrypted_image = cv2.bitwise_xor(encrypted_image, key2) return encrypted_image, key1, key2 # فك تشفير الصورة المشفرة بواسطة XOR def decrypt_image(encrypted_image, key1, key2): # فك التشفير بواسطة XOR متعدد المراحل decrypted_image = cv2.bitwise_xor(encrypted_image, key2) decrypted_image = cv2.bitwise_xor(decrypted_image, key1) return decrypted_image # خوارزمية التشفير الفوضوية باستخدام خريطة لوجيستية def chaotic_encrypt_image(image): # المتغيرات التحكمية للخريطة اللوجستية r = 3.8 x0 = 0.5 # إعداد الخريطة اللوجستية def logistic_map(x, r): return r * x * (1 - x) # إعداد الصورة المشفرة encrypted_image = np.zeros_like(image, dtype=np.uint8) # بدء التشفير for i in range(image.shape[0]): for j in range(image.shape[1]): pixel_value = image[i, j] # حساب القيمة الفوضوية x0 = logistic_map(x0, r) # تطبيق التشفير باستخدام XOR encrypted_pixel = pixel_value ^ int(x0 * 255) # تخزين القيمة المشفرة في الصورة المشفرة encrypted_image[i, j] = encrypted_pixel return encrypted_image # فك تشفير الصورة المشفرة بواسطة الخوارزمية الفوضوية def chaotic_decrypt_image(encrypted_image): # المتغيرات التحكمية للخريطة اللوجستية r = 3.8 x0 = 0.5 # إعداد الخريطة اللوجستية def logistic_map(x, r): return r * x * (1 - x) # إعداد الصورة المفككة decrypted_image = np.zeros_like(encrypted_image, dtype=np.uint8) # بدء فك التشفير for i in range(encrypted_image.shape[0]): for j in range(encrypted_image.shape[1]): encrypted_pixel = encrypted_image[i, j] # حساب القيمة الفوضوية x0 = logistic_map(x0, r) # تطبيق فك التشفير باستخدام XOR decrypted_pixel = encrypted_pixel ^ int(x0 * 255) # تخزين القيمة المفككة في الصورة المفككة decrypted_image[i, j] = decrypted_pixel return decrypted_image # خوارزمية التشفير الخلوية def cellular_encrypt_image(image): # قيم التحكم rule = 110 rows, cols = image.shape # إعداد الصورة المشفرة encrypted_image = np.zeros_like(image, dtype=np.uint8) # بدء التشفير for i in range(1, rows): for j in range(cols): # حساب القيمة الفوضوية باستخدام الخوارزمية الخلوية encrypted_image[i, j] = image[i - 1, (j - 1) % cols] ^ image[i - 1, j] ^ image[i - 1, (j + 1) % cols] encrypted_image[i, j] ^= (rule >> ((image[i - 1, (j - 1) % cols] << 2) + (image[i - 1, j] << 1) + image[i - 1, (j + 1) % cols])) & 1 return encrypted_image # قراءة الصورة x = cv2.imread(r'C:\Users\abdulwahed\Documents\photo enc\Kirigiri.Kyouko.full.3364419.jpg') # تحويل الصورة إلى الرمادي I = cv2.cvtColor(x, cv2.COLOR_BGR2GRAY) # تشفير الصورة باستخدام XOR encrypted_image_xor, key1, key2 = encrypt_image(I) # فك تشفير الصورة المشفرة بواسطة XOR decrypted_image_xor = decrypt_image(encrypted_image_xor, key1, key2) # تشفير الصورة بخوارزمية التشفير الفوضوية encrypted_image_chaotic = chaotic_encrypt_image(I) # فك تشفير الصورة المشفرة بواسطة الخوارزمية الفوضوية decrypted_image_chaotic = chaotic_decrypt_image(encrypted_image_chaotic) # تشفير الصورة بخوارزمية التشفير الخلوية encrypted_image_cellular = cellular_encrypt_image(I) # عرض الصور plt.figure(figsize=(15, 10)) plt.subplot(3, 3, 1) plt.imshow(I, cmap='gray') plt.title('Original Image') plt.axis('off') plt.subplot(3, 3, 2) plt.imshow(encrypted_image_xor, cmap='gray') plt.title('Encrypted Image (XOR)') plt.axis('off') plt.subplot(3, 3, 3) plt.imshow(decrypted_image_xor, cmap='gray') plt.title('Decrypted Image (XOR)') plt.axis('off') plt.subplot(3, 3, 4) plt.imshow(I, cmap='gray') plt.title('Original Image') plt.axis('off') plt.subplot(3, 3, 5) plt.imshow(encrypted_image_chaotic, cmap='gray') plt.title('Encrypted Image (Chaotic)') plt.axis('off') plt.subplot(3, 3, 6) plt.imshow(decrypted_image_chaotic, cmap='gray') plt.title('Decrypted Image (Chaotic)') plt.axis('off') plt.subplot(3, 3, 7) plt.imshow(I, cmap='gray') plt.title('Original Image') plt.axis('off') plt.subplot(3, 3, 8) plt.imshow(encrypted_image_cellular, cmap='gray') plt.title('Encrypted Image (Cellular)') plt.axis('off') plt.subplot(3, 3, 9) plt.imshow(I, cmap='gray') plt.title('Original Image') plt.axis('off') plt.tight_layout() plt.show() this code use 3 type of encryption and 3 tpye of decrypte can you group all 3 togther (user enter photo the program apply all 3 encryption on it then decrypte with all decryption method) please edit and give me full working code
a1a4126809e4b02ecfdb3e9aff41c258
{ "intermediate": 0.2903984487056732, "beginner": 0.4127240777015686, "expert": 0.2968774139881134 }
45,049
How do I change this to do both focus and hover in the same line? &:focus &:hover { border: none; text-decoration: underline; }
0df50b79a17d4a97649a8535b410de0f
{ "intermediate": 0.4402340352535248, "beginner": 0.16846990585327148, "expert": 0.3912960886955261 }
45,050
maximum number of collections that can be created on solr?
a8cd41db702345a8a829b9c58ec49d18
{ "intermediate": 0.3944794535636902, "beginner": 0.26465100049972534, "expert": 0.3408695161342621 }
45,051
Hypothetical 1970's Third Doctor serial , (with Sarah Jane) . " The Silver Statues!" - (Cyberman story) - A curios silver suit of armour arrives at UNIT HQ. The Brigadder blusters about it's presence... but the Doctor and Sarah are merely smused until it seems to move subtley when no-ones looking.. The first episode of a (6 part serial) has a cliffhanger , whereby Sarah is alone in the lab , with the suit of armour in a crate.. She hears a mouse and shugs, she jokingly grasps the hand of the suti of armour.. only for it to grasp back ! Expand this into a scene, and write the cliffhanger in an era appropriate way.. Write from Sarah entering the lab upto the sting into the credits...
969bdf7ea56dd076b56d54a68cbb7b35
{ "intermediate": 0.3026454448699951, "beginner": 0.3495495915412903, "expert": 0.3478049635887146 }
45,052
i need the formula 1 calender for 2024 in emacs orgmode agenda format in CET with grand prix name and country
39a975474a0900e99afaf70e7e013ecc
{ "intermediate": 0.3298305571079254, "beginner": 0.3018644154071808, "expert": 0.368304967880249 }
45,053
i need the formula 1 calender for 2024 in emacs orgmode agenda format in CET with grand prix name and country
c7226a6f6b1b92249b6d3b532b571bfb
{ "intermediate": 0.3298305571079254, "beginner": 0.3018644154071808, "expert": 0.368304967880249 }
45,054
check this code: for (start, end, exons, introns, _, _) in txs { // find an existing group that overlaps and merge, or create a new group let group = acc .iter_mut() .any(|(group_start, group_end, seen_5e, group_exons)| { // check if this transcript overlaps with the current group if start >= *group_start && end <= *group_end { *group_start = (*group_start).min(start); *group_end = (*group_end).max(end); // group_exons.extend(&exons); // group_introns.extend(&introns); true } else { false } }); if !group { let mut x: HashSet<(u64, u64)> = HashSet::new(); x.insert(exons.get(0)); acc.push((start, end, x, exons)); } } I am getting this error: error[E0308]: mismatched types --> src/track.rs:212:36 | 212 | x.insert(exons.get(0)); | --- ^ expected `&_`, found integer | | | arguments to this method are incorrect | = note: expected reference `&_` found type `{integer}` note: method defined here --> /home/alejandro/.cargo/registry/src/index.crates.io-6f17d22bba15001f/hashbrown-0.14.3/src/set.rs:887:12 | 887 | pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T> | ^^^ help: consider borrowing here | 212 | x.insert(exons.get(&0)); | + error[E0308]: mismatched types --> src/track.rs:212:26 | 212 | x.insert(exons.get(0)); | ------ ^^^^^^^^^^^^ expected `(u64, u64)`, found `Option<&(u64, u64)>` | | | arguments to this method are incorrect | = note: expected tuple `(u64, u64)` found enum `Option<&(u64, u64)>` note: method defined here --> /home/alejandro/.cargo/registry/src/index.crates.io-6f17d22bba15001f/hashbrown-0.14.3/src/set.rs:1114:12 | 1114 | pub fn insert(&mut self, value: T) -> bool { | ^^^^^^ the only thing I want to do is extract the first tuple from exons and create a new mutable HashSet with that element
bb900db134adbef6267b8056c210587f
{ "intermediate": 0.2669144868850708, "beginner": 0.5589281916618347, "expert": 0.1741572469472885 }
45,055
I'm doing documentation for implementing ApexCharts into a ClojureScript program. Here's my markdown page so far. Please help me complete it. # Apex Charts and You ## Required Framework to Add to Any Page ### Basic Requirements Add to ns require list:
f3bb1fdff0b3bf6adac39bba3b8f6511
{ "intermediate": 0.6610113978385925, "beginner": 0.10494714230298996, "expert": 0.23404142260551453 }
45,056
I'm trying to make a custom tooltip for this chart, but it's not working: (defn approved-invoice-chart [drafted-amt invoiced-amt] (let [percent (get-percentage invoiced-amt drafted-amt)] [ApexChart {:options (clj->js {:chart {:id "invoice-chart" :toolbar download-option-only} :plotOptions {:radialBar {:hollow {:size "60%"} :dataLabels {:value {:offsetY 154}}}} :title {:text "Approved Invoices" :align "left"} :tooltip {:custom (str "Actual revenue is " percent "% of estimated revenue.")}} :labels [["Revenue Estimate Total" "" "Actual Revenue Total"]] ; these are styled separately to the values we want to import :subtitle {:text ["" ; total estimated revenue (str "$" drafted-amt) "" ; total actual revenue (str "$" invoiced-amt)] ; replace with real values later :align "center" :margin 0 :offsetX 0 :offsetY 196 :floating true :style {:fontWeight "bold" :fontSize "14px"}} :colors (colours :orange-dark)}) :series [percent] :type "radialBar" :width 500 :height 400}]))
e4064035e42c5d623d9775b7475e35c1
{ "intermediate": 0.4010147452354431, "beginner": 0.4112475514411926, "expert": 0.18773779273033142 }
45,057
I'm trying to make a custom tooltip for this chart but it isn't working: (defn approved-invoice-chart [drafted-amt invoiced-amt] (let [percent (get-percentage invoiced-amt drafted-amt)] [ApexChart {:options (clj->js {:chart {:id "invoice-chart" :toolbar download-option-only} :plotOptions {:radialBar {:hollow {:size "60%"} :dataLabels {:value {:offsetY 154}}}} :title {:text "Approved Invoices" :align "left"} :tooltip {:custom (str "Actual revenue is " percent "% of estimated revenue.")}} :labels [["Revenue Estimate Total" "" "Actual Revenue Total"]] ; these are styled separately to the values we want to import :subtitle {:text ["" ; total estimated revenue (str "" drafted-amt) "" ; total actual revenue (str "" invoiced-amt)] ; replace with real values later :align "center" :margin 0 :offsetX 0 :offsetY 196 :floating true :style {:fontWeight "bold" :fontSize "14px"}} :colors (colours :orange-dark)}) :series [percent] :type "radialBar" :width 500 :height 400}]))
79fed8554ab6b570849304d83433c223
{ "intermediate": 0.3566439151763916, "beginner": 0.4090619385242462, "expert": 0.234294131398201 }
45,058
Change this JavaScript to ClojureScript format: subtitle: { text: undefined, align: 'left', margin: 10, offsetX: 0, offsetY: 0, floating: false, style: { fontSize: '12px', fontWeight: 'normal', fontFamily: undefined, color: '#9699a2' }, }
bdb2b6dad5a378a7482553fffbe31e0b
{ "intermediate": 0.3015791177749634, "beginner": 0.3913189172744751, "expert": 0.3071019649505615 }
45,059
this is my code: pub fn consensus_5e_branch(tracks: TranscriptMap, mode: &str) -> ConsensusMap { let cmap: Mutex<ConsensusMap> = Mutex::new(HashMap::new()); // iterate over each chromosome in parallel tracks.into_par_iter().for_each(|(chr, txs)| { // creates a local-thread accumulator -> Vec<Transcript> let mut acc: ConsensusTxHash = Vec::new(); for (start, end, exons, introns, , ) in txs { // find an existing group that overlaps and merge, or create a new group let group = acc .iter_mut() .any(|(group_start, group_end, seen_5e, group_exons)| { // check if this transcript overlaps with the current group if start >= group_start && end <= group_end { _group_start = (_group_start).min(start); _group_end = (_group_end).max(end); // group_exons.extend(&exons); // group_introns.extend(&introns); true } else { false } }); if !group { let mut x: HashSet<(u64, u64)> = HashSet::new(); if let Some(first_exon) = exons.get(&0) { x.insert(*first_exon); } acc.push((start, end, x, exons)); } } // HashSet -> Vec to allow sorting let sort_acc: ConsensusTx = acc .into_iter() .map(|(s, e, mut exs, mut ints)| { let mut vex: Vec<(u64, u64)> = exs.drain().collect::<Vec<_>>(); let mut vint: Vec<(u64, u64)> = ints.drain().collect::<Vec<_>>(); vex.par_sort_unstable(); vint.par_sort_unstable(); let c_vex = if mode == FIVEND { reduce_ends(vex) } else { vex }; (s, e, c_vex, vint) }) .collect(); cmap.lock().unwrap().insert(chr, sort_acc); }); cmap.into_inner().unwrap() } I am getting this error: error[E0277]: the trait bound (u64, u64): Borrow<{integer}> is not satisfied --> src/track.rs:212:53 | 212 | if let Some(first_exon) = exons.get(&0) { | --- ^^ the trait Borrow<{integer}> is not implemented for (u64, u64) | | | required by a bound introduced by this call | = note: required for {integer} to implement Equivalent<(u64, u64)> note: required by a bound in hashbrown::HashSet::<T, S, A>::get --> /home/alejandro/.cargo/registry/src/index.crates.io-6f17d22bba15001f/hashbrown-0.14.3/src/set.rs:889:19 | 887 | pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T> | --- required by a bound in this associated function 888 | where 889 | Q: Hash + Equivalent<T>, | ^^^^^^^^^^^^^ required by this bound in HashSet::<T, S, A>::get For more information about this error, try rustc --explain E0277. error: could not compile deintronize (lib) due to 1 previous error
13ab6cb51b9718a177677c9bf41e78e8
{ "intermediate": 0.36916011571884155, "beginner": 0.37861138582229614, "expert": 0.2522284686565399 }
45,060
Here's an example Apex chart I'm working with in ClojureScript. (defn approved-invoice-chart [drafted-amt invoiced-amt] (let [percent (get-percentage invoiced-amt drafted-amt)] [ApexChart {:options (clj->js {:chart {:id "invoice-chart" :toolbar download-option-only} :plotOptions {:radialBar {:hollow {:size "60%"} :dataLabels {:value {:offsetY 154}}}} :title {:text "Approved Invoices" :align "left"} :labels [["Revenue Estimate Total" "" "Actual Revenue Total"]] ; these are styled separately to the values we want to import :subtitle {:text ["" ; total estimated revenue (str "" drafted-amt) "" ; total actual revenue (str "" invoiced-amt)] ; replace with real values later :align "center" :margin 0 :offsetX 0 :offsetY 196 :floating true :style {:fontWeight "bold" :fontSize "14px"}} :colors (colours :orange-dark)}) :series [percent] :type "radialBar" :width 500 :height 400}])) I want to make a chart to show total amount of cost incurred on jobs, and total amount of cost remaining on jobs. I haven't received any spec about what they should look like. There are already 3 bar charts and 2 radial bar charts on the page.
44a559fc408c282a5f6815a8498622e6
{ "intermediate": 0.29459449648857117, "beginner": 0.5286916494369507, "expert": 0.176713764667511 }
45,061
Bantu ubah kode JS ini ke cjs import fs from 'fs';import path from 'path';import { toBuffer } from 'qrcode';import ws from 'ws';import Connection from '../lib/connection.js';import Store from '../lib/store.js';import db from '../lib/database/index.js';const { DisconnectReason, areJidsSameUser, useMultiFileAuthState} = await import('@whiskeysockets/baileys');
50d89eb1b9161a42490837e0b2a0abcd
{ "intermediate": 0.5465079545974731, "beginner": 0.24927619099617004, "expert": 0.20421583950519562 }
45,062
#include <iostream> #include <vector> #include <cmath> #include <gsl/gsl_math.h> #include <gsl/gsl_linalg.h> #include <gsl/gsl_integration.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_sf_log.h> #include "const.h" #include "const_ion.h" #include "func_declarations.h" using namespace std; // ################# COMPLETE BASED ON THE ACTUAL DATA ############### // ################# COMPLETE BASED ON THE ACTUAL DATA ############### double lognH = 1.0; // Replace 1.0 with the actual value for lognH double logne = 1.0; // Replace 1.0 with the actual value for logne double nH = pow(10, lognH); double nu = 1.0; // Replace 1.0 with the actual value for nu double logZ = 1.0; // Replace 1.0 with the actual value for logZ double Z = pow(10, logZ); double logQ= 1.0; // Replace 1.0 with the actual value for logQ double T4OII = 1.0; // Replace 1.0 with the actual value for T4OII double VOII2VHII = 1.0; // Replace 1.0 with the actual value for VOII2VHII double VOIII2VHII = 1.0; // Replace 1.0 with the actual value for VOIII2VHII double T4OIII = 1.0; // Replace 1.0 with the actual value for T4OIII double T4HII = T4OII * VOII2VHII + T4OIII * VOIII2VHII; // Function to solve OIII level population abundances vector<double> assignL(std::vector<double> INPUT) { double nO = pow(10, -3.31) * pow(10, logZ) * pow(10, lognH); // number density of O double ne = pow(10, lognH) * (1 + 0.0737 + 0.0293 * pow(10, logZ)); // number density of free electron gsl_matrix *A = gsl_matrix_alloc(4, 4); gsl_vector *B = gsl_vector_alloc(4); gsl_vector *levelPop = gsl_vector_alloc(4); // Set up the matrix A gsl_matrix_set(A, 0, 0, R10_OIII(ne, T4OIII) + R12_OIII(ne, T4OIII) + R13_OIII(ne, T4OIII) + R14_OIII(ne, T4OIII)); gsl_matrix_set(A, 0, 1, -R21_OIII(ne, T4OIII)); gsl_matrix_set(A, 0, 2, -R31_OIII(ne, T4OIII)); gsl_matrix_set(A, 0, 3, -R41_OIII(ne, T4OIII)); gsl_matrix_set(A, 1, 0, -R12_OIII(ne, T4OIII)); gsl_matrix_set(A, 1, 1, R20_OIII(ne, T4OIII) + R21_OIII(ne, T4OIII) + R23_OIII(ne, T4OIII) + R24_OIII(ne, T4OIII)); gsl_matrix_set(A, 1, 2, -R32_OIII(ne, T4OIII)); gsl_matrix_set(A, 1, 3, -R42_OIII(ne, T4OIII)); gsl_matrix_set(A, 2, 0, -R13_OIII(ne, T4OIII)); gsl_matrix_set(A, 2, 1, -R23_OIII(ne, T4OIII)); gsl_matrix_set(A, 2, 2, R30_OIII(ne, T4OIII) + R31_OIII(ne, T4OIII) + R32_OIII(ne, T4OIII) + R34_OIII(ne, T4OIII)); gsl_matrix_set(A, 2, 3, -R43_OIII(ne, T4OIII)); gsl_matrix_set(A, 3, 0, -R14_OIII(ne, T4OIII)); gsl_matrix_set(A, 3, 1, -R24_OIII(ne, T4OIII)); gsl_matrix_set(A, 3, 2, -R34_OIII(ne, T4OIII)); gsl_matrix_set(A, 3, 3, R40_OIII(ne, T4OIII) + R41_OIII(ne, T4OIII) + R42_OIII(ne, T4OIII) + R43_OIII(ne, T4OIII)); // Set up vector B gsl_vector_set(B, 0, R01_OIII(ne, T4OIII)); gsl_vector_set(B, 1, R02_OIII(ne, T4OIII)); gsl_vector_set(B, 2, R03_OIII(ne, T4OIII)); gsl_vector_set(B, 3, R04_OIII(ne, T4OIII)); // Set up other elements of vector B // ... // Solve for level populations gsl_permutation *p = gsl_permutation_alloc(4); int s; gsl_linalg_LU_decomp(A, p, &s); gsl_linalg_LU_solve(A, p, B, levelPop); // Calculate n0, n1, n2, n3, n4 double n0 = nO / (1 + gsl_vector_get(levelPop, 0) + gsl_vector_get(levelPop, 1) + gsl_vector_get(levelPop, 2) + gsl_vector_get(levelPop, 3)); double n1 = n0 * gsl_vector_get(levelPop, 0); double n2 = n0 * gsl_vector_get(levelPop, 1); double n3 = n0 * gsl_vector_get(levelPop, 2); double n4 = n0 * gsl_vector_get(levelPop, 3); // Calculate OIII line luminosities double logL10_OIII = log10(h) + log10(nu10_OIII * n1 * A10_OIII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOIII2VHII); double logL21_OIII = log10(h) + log10(nu21_OIII * n2 * A21_OIII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOIII2VHII); double logL31_OIII = log10(h) + log10(nu31_OIII * n3 * A31_OIII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOIII2VHII); double logL32_OIII = log10(h) + log10(nu32_OIII * n3 * A32_OIII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOIII2VHII); double logL43_OIII = log10(h) + log10(nu43_OIII * n4 * A43_OIII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOIII2VHII); // Solve linear equations A x = B //gsl_permutation *p = gsl_permutation_alloc(4); gsl_linalg_LU_decomp(A, p, &s); gsl_linalg_LU_solve(A, p, B, levelPop); // Solve OII level population abundances gsl_matrix *A_OII = gsl_matrix_alloc(4, 4); gsl_vector *B_OII = gsl_vector_alloc(4); gsl_matrix_set(A_OII, 0, 0, R10_OII(ne, T4OII) + R12_OII(ne, T4OII) + R13_OII(ne, T4OII) + R14_OII(ne, T4OII)); gsl_matrix_set(A_OII, 0, 1, -R21_OII(ne, T4OII)); gsl_matrix_set(A_OII, 0, 2, -R31_OII(ne, T4OII)); gsl_matrix_set(A_OII, 0, 3, -R41_OII(ne, T4OII)); gsl_matrix_set(A_OII, 1, 0, -R12_OII(ne, T4OII)); gsl_matrix_set(A_OII, 1, 1, R20_OII(ne, T4OII) + R21_OII(ne, T4OII) + R23_OII(ne, T4OII) + R24_OII(ne, T4OII)); gsl_matrix_set(A_OII, 1, 2, -R32_OII(ne, T4OII)); gsl_matrix_set(A_OII, 1, 3, -R42_OII(ne, T4OII)); gsl_matrix_set(A_OII, 2, 0, -R13_OII(ne, T4OII)); gsl_matrix_set(A_OII, 2, 1, -R23_OII(ne, T4OII)); gsl_matrix_set(A_OII, 2, 2, R30_OII(ne, T4OII) + R31_OII(ne, T4OII) + R32_OII(ne, T4OII) + R34_OII(ne, T4OII)); gsl_matrix_set(A_OII, 2, 3, -R43_OII(ne, T4OII)); gsl_matrix_set(A_OII, 3, 0, -R14_OII(ne, T4OII)); gsl_matrix_set(A_OII, 3, 1, -R24_OII(ne, T4OII)); gsl_matrix_set(A_OII, 3, 2, -R34_OII(ne, T4OII)); gsl_matrix_set(A_OII, 3, 3, R40_OII(ne, T4OII) + R41_OII(ne, T4OII) + R42_OII(ne, T4OII) + R43_OII(ne, T4OII)); gsl_vector_set(B_OII, 0, R01_OII(ne, T4OII)); gsl_vector_set(B_OII, 1, R02_OII(ne, T4OII)); gsl_vector_set(B_OII, 2, R03_OII(ne, T4OII)); gsl_vector_set(B_OII, 3, R04_OII(ne, T4OII)); // Set up other elements of vector B_OII gsl_vector *levelPop_OII = gsl_vector_alloc(4); gsl_linalg_LU_solve(A_OII, p, B_OII, levelPop_OII); double n0_OII = nO / (1 + gsl_vector_get(levelPop_OII, 0) + gsl_vector_get(levelPop_OII, 1) + gsl_vector_get(levelPop_OII, 2) + gsl_vector_get(levelPop_OII, 3)); double n1_OII = n0_OII * gsl_vector_get(levelPop_OII, 0); double n2_OII = n0_OII * gsl_vector_get(levelPop_OII, 1); double n3_OII = n0_OII * gsl_vector_get(levelPop_OII, 2); double n4_OII = n0_OII * gsl_vector_get(levelPop_OII, 3); double logL10_OII = log10(h) + log10(nu10_OII * n1_OII * A10_OII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOII2VHII); double logL20_OII = log10(h) + log10(nu20_OII * n2_OII * A20_OII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOII2VHII); double logL30_OII = log10(h) + log10(nu30_OII * n3_OII * A30_OII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOII2VHII); double logL31_OII = log10(h) + log10(nu31_OII * n3_OII * A31_OII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOII2VHII); double logL32_OII = log10(h) + log10(nu32_OII * n3_OII * A32_OII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOII2VHII); double logL40_OII = log10(h) + log10(nu40_OII * n4_OII * A40_OII / alphaB_HI(T4HII) * Jps2Lsun) + logQ - lognH - logne + log10(VOII2VHII); double logLHalpha = log10(h) + log10(nu_Halpha * alphaB_Halpha(T4HII) / alphaB_HI(T4HII) * Jps2Lsun) + logQ; double logLHbeta = log10(h) + log10(nu_Hbeta * alphaB_Hbeta(T4HII) / alphaB_HI(T4HII) * Jps2Lsun) + logQ; gsl_matrix_free(A_OII); gsl_vector_free(B_OII); gsl_vector_free(levelPop_OII); //return std::make_tuple(logL10_OII, logL20_OII, logL30_OII, logL31_OII, logL32_OII, logL40_OII, logL10_OIII, logL21_OIII, logL31_OIII, logL32_OIII, logL43_OIII, logLHalpha, logLHbeta); std::vector<double> result = {logL10_OII, logL20_OII, logL30_OII, logL31_OII, logL32_OII, logL40_OII, logL10_OIII, logL21_OIII, logL31_OIII, logL32_OIII, logL43_OIII, logLHalpha, logLHbeta}; return result; } //#####################################################// //#########################################// // Function to compute hydrogen ionization fraction double y(double nHI_para, double nHeI_para, double nuy) { std::vector<double> nuy_vec(1, nuy); if (nHI_para == 0 && nHeI_para == 0) { return 0.5; } else { return nHI_para * sigma_HI(nuy_vec)[0] / (nHI_para * sigma_HI(nuy_vec)[0] + nHeI_para * sigma_HeI(nuy_vec)[0]); } } void compute_VO_ratios(double nu[], double L[], double logQ, double lognH, double logZ, double T4, double &VOII2HII, double &VOIII2HII) { // Constants const double nu_OII = 2.2e15; // Frequency of OII transition (Hz) const double nu_OIII = 2.5e15; // Frequency of OIII transition (Hz) const double alphaB_HI = 2.6e-13 * pow(10, T4) * pow(10, 4 - lognH); // Recombination coefficient of H I (cm^3 s^-1) // Constants for OII transition const double A10_OII = 6.85e-6; // Einstein coefficient for spontaneous emission for OII transition (s^-1) const double A20_OII = 6.03e-6; // Einstein coefficient for spontaneous emission for OII transition (s^-1) const double A30_OII = 5.71e-6; // Einstein coefficient for spontaneous emission for OII transition (s^-1) const double A32_OII = 8.14e-6; // Einstein coefficient for spontaneous emission for OII transition (s^-1) const double A40_OII = 5.91e-6; // Einstein coefficient for spontaneous emission for OII transition (s^-1) // Constants for OIII transition const double A10_OIII = 8.63e-5; // Einstein coefficient for spontaneous emission for OIII transition (s^-1) const double A21_OIII = 6.03e-5; // Einstein coefficient for spontaneous emission for OIII transition (s^-1) const double A31_OIII = 7.92e-5; // Einstein coefficient for spontaneous emission for OIII transition (s^-1) const double A32_OIII = 6.97e-5; // Einstein coefficient for spontaneous emission for OIII transition (s^-1) const double A43_OIII = 2.84e-5; // Einstein coefficient for spontaneous emission for OIII transition (s^-1) // Compute level populations // (You may need to define the relevant functions or provide them) double levelPop_OII[4]; double levelPop_OIII[4]; // Compute level populations for OII and OIII transitions using appropriate functions // Calculate luminosities double logL10_OII = log10(nu_OII * levelPop_OII[0] * A10_OII / alphaB_HI * L[0]) + logQ - lognH + logZ; double logL20_OII = log10(nu_OII * levelPop_OII[1] * A20_OII / alphaB_HI * L[1]) + logQ - lognH + logZ; double logL30_OII = log10(nu_OII * levelPop_OII[2] * A30_OII / alphaB_HI * L[2]) + logQ - lognH + logZ; double logL31_OII = log10(nu_OII * levelPop_OII[2] * A32_OII / alphaB_HI * L[3]) + logQ - lognH + logZ; double logL40_OII = log10(nu_OII * levelPop_OII[3] * A40_OII / alphaB_HI * L[4]) + logQ - lognH + logZ; double logL10_OIII = log10(nu_OIII * levelPop_OIII[0] * A10_OIII / alphaB_HI * L[5]) + logQ - lognH + logZ; double logL21_OIII = log10(nu_OIII * levelPop_OIII[1] * A21_OIII / alphaB_HI * L[6]) + logQ - lognH + logZ; double logL31_OIII = log10(nu_OIII * levelPop_OIII[2] * A31_OIII / alphaB_HI * L[7]) + logQ - lognH + logZ; double logL32_OIII = log10(nu_OIII * levelPop_OIII[2] * A32_OIII / alphaB_HI * L[8]) + logQ - lognH + logZ; double logL43_OIII = log10(nu_OIII * levelPop_OIII[3] * A43_OIII / alphaB_HI * L[9]) + logQ - lognH + logZ; // Compute VOII2HII and VOIII2HII ratios VOII2HII = pow(10, logL10_OII) / (pow(10, logL10_OII) + pow(10, logL10_OIII)); VOIII2HII = pow(10, logL10_OIII) / (pow(10, logL10_OII) + pow(10, logL10_OIII)); } // Main function int main() { // // Sample input parameters // double nu[] = {1e15, 2e15, 3e15, 4e15, 5e15, 6e15, 7e15, 8e15, 9e15, 10e15}; // Sample frequency array // double L[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Sample incident spectrum array // double logQ = 5.0; // Sample log10(Q) // double lognH = 2.0; // Sample log10(nH) // double logZ = -3.0; // Sample log10(Z) // double T4 = 1.0; // Sample T/10000K // double VOII2HII, VOIII2HII; // // Get the size of the nu array // int nu_size = sizeof(nu) / sizeof(nu[0]); // // Calculations // std::vector<double> E(nu_size); // for (int i = 0; i < nu_size; i++) { // E[i] = nu[i] * h / eV2J; // } // std::vector<double> dnu(nu_size); // dnu[0] = nu[0]; // for (int i = 1; i < nu_size; i++) { // dnu[i] = nu[i] - nu[i - 1]; // } // std::vector<int> idx_H, idx_HI, idx_HeI, idx_HeII, idx_OII, idx_OI; // for (int i = 0; i < E.size(); i++) { // if (E[i] > 13.6) idx_H.push_back(i); // if (E[i] > 13.6 && E[i] <= 24.59) idx_HI.push_back(i); // if (E[i] > 24.59 && E[i] <= 54.42) idx_HeI.push_back(i); // if (E[i] > 54.42) idx_HeII.push_back(i); // if (E[i] > 35.12) idx_OII.push_back(i); // if (E[i] > 13.62) idx_OI.push_back(i); // } // double nH = pow(10, lognH); // double Z = pow(10, logZ); // double nHe = nH * (0.0737 + 0.0293 * Z); // double nO = nH * pow(10, -3.31) * Z; // std::vector<double> nuy = { (24.59 * eV2J + kb * T4 * 10000) / h }; // // Compute VOII2HII and VOIII2HII ratios // compute_VO_ratios(nu, L, logQ, lognH, logZ, T4, VOII2HII, VOIII2HII); // // Output results // std::cout << "VOII2HII: " << VOII2HII << std::endl; // std::cout << "VOIII2HII: " << VOIII2HII << std::endl; ///////////////////////////////////// // Define the input parameters double logQ = 1.0; double lognH = 1.0; double logZ = 1.0; double T4OII = 1.0; double T4OIII = 1.0; double VOII2VHII = 1.0; double VOIII2VHII = 1.0; // Call assignL std::vector<double> input_values = {logQ, lognH, logZ, T4OII, T4OIII, VOII2VHII, VOIII2VHII}; std::vector<double> result = assignL(input_values); std::cout << "Hello World ma!" << std::endl; // Print the result std::cout << "Result from assignL function:" << std::endl; for (double val : result) { std::cout << val << " "; } std::cout << std::endl; std::cout << "Hello World main!" << std::endl; return 0; } why am i getting no output?
e255e44571a0e933c5a9c721793c4152
{ "intermediate": 0.3223634362220764, "beginner": 0.27922746539115906, "expert": 0.39840906858444214 }
45,063
do you know crewai
3985c8996a7cbcc31744610d74852f12
{ "intermediate": 0.38493314385414124, "beginner": 0.27230924367904663, "expert": 0.3427576720714569 }
45,064
In deep learning, is there any learning rate scheduling method will initial set a learning rate, e.g. lr=0.001, then it decays exponentially, e.g. at epoch =20, lr=0.0001, then at the middle epoch e.g. epoch=50 lr=0.001 ?
a84742fa514e8134efc121402aa970b4
{ "intermediate": 0.04021061584353447, "beginner": 0.04188990592956543, "expert": 0.9178994297981262 }
45,065
write an html file with javascript that could calulate this with user entered data find the savings plan balance after 12 months with an APR of 3% and monthly payments of $150. Assume monthly compounding. asnwer: $1824.96
a06269b22f176bdec8e4ede6f7e4e3be
{ "intermediate": 0.6067519783973694, "beginner": 0.19925977289676666, "expert": 0.19398818910121918 }
45,066
write an html file with javascript that could calulate this with user entered data find the savings plan balance after 12 months with an APR of 3% and monthly payments of $150. Assume monthly compounding. asnwer: $1824.96
b914de5a4606ffe840af3eaabf45d3be
{ "intermediate": 0.6067519783973694, "beginner": 0.19925977289676666, "expert": 0.19398818910121918 }
45,067
Hi there, what does the below code block mean? It should be something related to a api. @FunctionPointCode(SecurityConstants.FunctionPoints.EXPORT_MISSING_UNASSIGNED_ACCELERATOR) @GetMapping(value = “/missingUnassignedAccelerator”) ResponseEntity<InputStreamResource> generateMissingUnassignedAccelerator(@RequestBody(required = false) Map payload) {
178849643cc75599aad6f249797577ed
{ "intermediate": 0.600865364074707, "beginner": 0.2840689718723297, "expert": 0.11506567895412445 }
45,068
generate the python code to embed a message in an image
14e463282081181bb455256e39996c43
{ "intermediate": 0.3425891399383545, "beginner": 0.189875528216362, "expert": 0.4675352871417999 }
45,069
modify this script. the problem is, audio file and video are being generating multiple times. also change the directory to current directroy to save everything in current directory: import os from flask import Flask, request, render_template, redirect, url_for, send_file import subprocess import requests from bs4 import BeautifulSoup import openai import cv2 from mutagen.mp3 import MP3 import math import assemblyai as aai from moviepy.editor import VideoFileClip, AudioFileClip, TextClip, CompositeVideoClip import re import pysrt from datetime import datetime, timedelta app = Flask(__name__) # Set your OpenAI API key from environment variable os.environ["OPENAI_API_KEY"] = "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" def execute_curl_command(text_parameter): curl_command = [ 'curl', 'https://crikk.com/text-to-speech/hindi/', '-H', 'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7', '-H', 'accept-language: en-US,en;q=0.9', '-H', 'cache-control: max-age=0', '-H', 'content-type: application/x-www-form-urlencoded', '-H', 'cookie: _ga=GA1.1.2143147333.1711495228; _clck=qkcllh%7C2%7Cfke%7C0%7C1546; _fbp=fb.1.1711495228668.2045563708; PHPSESSID=ujrc5sds303mh4orukvohl3dsf; _clsk=71uycd%7C1711495249954%7C5%7C1%7Ce.clarity.ms%2Fcollect; _ga_0PRQTGTWRS=GS1.1.1711495227.1.1.1711495301.0.0.0', '-H', 'origin: https://crikk.com', '-H', 'referer: https://crikk.com/text-to-speech/hindi/', '-H', 'sec-ch-ua: "Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"', '-H', 'sec-ch-ua-mobile: ?0', '-H', 'sec-ch-ua-platform: "Windows"', '-H', 'sec-fetch-dest: document', '-H', 'sec-fetch-mode: navigate', '-H', 'sec-fetch-site: same-origin', '-H', 'sec-fetch-user: ?1', '-H', 'upgrade-insecure-requests: 1', '-H', 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36', '--data-raw', f'language=hindi%2F&charecter=hi-IN-MadhurNeural&text={text_parameter}' ] try: result = subprocess.run(curl_command, capture_output=True, text=True, check=True, encoding='utf-8') return result.stdout except subprocess.CalledProcessError as e: print("Error executing curl command:", e) return None def check_output_for_mp3(output): if output is None: print("No output received.") return soup = BeautifulSoup(output, 'html.parser') link = soup.find('a', class_='btn btn-primary px-5 mx-auto')['href'] if soup.find('a', class_='btn btn-primary px-5 mx-auto') else None if link and link.endswith('.mp3'): download_mp3(link) else: print("Not Possible") def download_mp3(url): response = requests.get(url) if response.status_code == 200: filename = url.split('/')[-1] # Extract the filename from the URL with open(filename, 'wb') as f: f.write(response.content) print("The MP3 file has been saved as", filename) else: print("Failed to save the MP3 file") def adjust_contrast_brightness(image, contrast=1.2, brightness=20): # Apply contrast and brightness adjustments to the image adjusted_image = cv2.convertScaleAbs(image, alpha=contrast, beta=brightness) return adjusted_image def generate_video(image_folder, audio_folder, video_path, width=1920, height=1080, min_duration=10): # Get list of image files images = [img for img in os.listdir(image_folder) if img.endswith(".jpg") or img.endswith(".jpeg") or img.endswith(".png")] images.sort() # Ensure images are sorted in alphabetical order # Calculate the total duration for the video total_images = len(images) total_duration = max(total_images * 9, min_duration) # Ensure a minimum duration of 10 seconds # Calculate the duration per image duration_per_image = total_duration / total_images # Search for an MP3 file in the audio folder audio_file = None for file in os.listdir(audio_folder): if file.endswith(".mp3"): audio_file = os.path.join(audio_folder, file) break if not audio_file: print("No MP3 file found in the specified audio folder.") return # Get audio duration audio = MP3(audio_file) audio_duration = audio.info.length # Adjust total duration if audio duration is shorter total_duration = min(total_duration, audio_duration) # Define the codec and create VideoWriter object fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Codec for MP4 format out = cv2.VideoWriter(video_path, fourcc, 30, (width, height)) # 30 fps # Calculate the number of frames needed total_frames = math.ceil(total_duration * 30) # Loop through images and add to video frame_count = 0 for image in images: img_path = os.path.join(image_folder, image) img = cv2.imread(img_path) img = cv2.resize(img, (width, height)) # Resize image to desired dimensions # Adjust contrast and brightness adjusted_img = adjust_contrast_brightness(img, contrast=1.2, brightness=20) # Write the same frame for the specified duration for _ in range(int(30 * duration_per_image)): # Assuming 30 fps out.write(adjusted_img) frame_count += 1 if frame_count >= total_frames: break # Release VideoWriter and close OpenCV windows out.release() cv2.destroyAllWindows() # Replace with your API key ASSEMBLY_AI_API_KEY = "81c02da947d94a12a5c87cd5b220f795" def generate_subtitles_assemblyai(audio_path: str, voice: str) -> str: language_mapping = { "br": "pt", "id": "en", # AssemblyAI doesn't have Indonesian "jp": "ja", "kr": "ko", "in": "hi", } if voice in language_mapping: lang_code = language_mapping[voice] else: lang_code = voice aai.settings.api_key = ASSEMBLY_AI_API_KEY config = aai.TranscriptionConfig(language_code=lang_code) transcriber = aai.Transcriber(config=config) transcript = transcriber.transcribe(audio_path) if transcript.status == aai.TranscriptStatus.error: return transcript.error else: subtitles = transcript.export_subtitles_srt() with open("generated_subtitles.srt", "w", encoding="utf-8") as file: file.write(subtitles) return "generated_subtitles.srt" def parse_srt(subtitle_path): subs = pysrt.open(subtitle_path) subtitles = [] for sub in subs: start_time = sub.start.to_time() end_time = sub.end.to_time() text = sub.text subtitles.append((start_time, end_time, text)) return subtitles def add_subtitles(video_path, audio_path, subtitle_path, output_path, font_path=None): # Load video and audio clips video_clip = VideoFileClip(video_path) audio_clip = AudioFileClip(audio_path) # Parse subtitles subtitles = parse_srt(subtitle_path) # Calculate offset between video and audio video_start_time = video_clip.start audio_start_time = video_start_time + 1 # Adding a one-second offset video_clip = video_clip.set_start(video_start_time) audio_clip = audio_clip.set_start(audio_start_time) # Generate text clips from subtitles caption_clips = [] for start_time, end_time, text in subtitles: duration = (end_time.hour * 3600 + end_time.minute * 60 + end_time.second + end_time.microsecond / 1000000) - \ (start_time.hour * 3600 + start_time.minute * 60 + start_time.second + start_time.microsecond / 1000000) caption_clip = TextClip(text, fontsize=40, bg_color='black', color='yellow', font=font_path).set_position(('center', 'center'), relative=True).set_duration(duration).set_start((start_time.hour * 3600 + start_time.minute * 60 + start_time.second + start_time.microsecond / 1000000)) caption_clips.append(caption_clip) # Combine video and caption clips video_with_captions = CompositeVideoClip([video_clip.set_audio(audio_clip)] + caption_clips) # Write the final video with captions to a file video_with_captions.write_videofile(output_path, codec='libx264', audio_codec='aac') # Close the clips video_clip.close() audio_clip.close() @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': # Prompt for theme theme = request.form['theme'] # Generate text parameter using OpenAI GPT-3.5 Turbo model prompt = f"Generate content on - \"{theme}\"" openai.api_key = os.environ["OPENAI_API_KEY"] response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": prompt} ] ) text_parameter = response.choices[0].message['content'] print("Generated text parameter:", text_parameter) output = execute_curl_command(text_parameter) check_output_for_mp3(output) # Get the current directory current_dir = os.getcwd() # Path to the folder containing images image_folder = os.path.join(current_dir, 'images') # Path to the folder containing audio files audio_folder = current_dir # Path to save the video video_path = os.path.join(current_dir, 'with_video_adjusted.mp4') # Generate the video generate_video(image_folder, audio_folder, video_path) # Generate subtitles AUDIO_DIRECTORY = audio_folder mp3_files = [file for file in os.listdir(AUDIO_DIRECTORY) if file.endswith(".mp3")] if mp3_files: audio_path = os.path.join(AUDIO_DIRECTORY, mp3_files[0]) voice_language = "hi" # Change to the appropriate language code subtitles_file = generate_subtitles_assemblyai(audio_path, voice_language) print("Subtitles saved to:", subtitles_file) # Add subtitles to the video video_directory = current_dir audio_directory = current_dir subtitle_path = os.path.join(current_dir, subtitles_file) output_path = os.path.join(current_dir, 'output_video_with_subtitles.mp4') font_path = os.path.join(current_dir, 'in.ttf') add_subtitles(video_path, audio_path, subtitle_path, output_path, font_path) return redirect(url_for('download_video')) return render_template('index.html') @app.route('/download') def download_video(): video_path = os.path.join(os.getcwd(), 'output_video_with_subtitles.mp4') return send_file(video_path, as_attachment=True) if __name__ == '__main__': app.run(debug=True)
b1fd9e64717f424886fab50f9833e6e6
{ "intermediate": 0.5279510021209717, "beginner": 0.3273901343345642, "expert": 0.14465881884098053 }
45,070
Convert this method from ray origin and direction to just using 2 ray points, and checking if that line intersects the quad and returning where if it does: private static Vector3 rayQuadIntersection(Vector3 rayOrigin, Vector3 rayDirection, Vector3 v1, Vector3 v2, Vector3 v3) { // https://stackoverflow.com/questions/21114796/3d-ray-quad-intersection-test-in-java // 1. Get tht normal of the plane Vector3 a = VectorUtils.subNew(v2, v1); Vector3 b = VectorUtils.subNew(v3, v1); Vector3 normal = VectorUtils.cross(a, b); normal.normalize(); // 2. double dotDifference = normal.dot(rayDirection); // Parallel tolerance if(Math.abs(dotDifference) < 1e-6f) return null; double t = -normal.dot(VectorUtils.subNew(rayOrigin, v1)) / dotDifference; if(t < 0) return null; // Check if the intersection is behind the rays origin? Vector3 collision = VectorUtils.addNew(rayOrigin, VectorUtils.scaleNew(rayDirection, t)); // 3. // 3. Project collision point onto the plane defined by quad vertices Vector3 dMS1 = VectorUtils.subNew(collision, v1); double dotA = a.dot(a); double dotB = b.dot(b); double u = dMS1.dot(a) / dotA; double v = dMS1.dot(b) / dotB; // // Vector3 dMS1 = VectorUtils.subNew(collision, v1); // double u = dMS1.dot(a); // double v = dMS1.dot(b); // 4. if(u >= 0.0f && u <= 1.0f && v >= 0.0f && v <= 1.0f) { return collision; } return null; }
69a846743915085b45b715b29c9e9e60
{ "intermediate": 0.4697161912918091, "beginner": 0.19781489670276642, "expert": 0.33246898651123047 }
45,071
Guess why this method isn't working, then fix it by rewriting the method: private static Vector3 rayPointsQuadIntersection(Vector3 rayPoint1, Vector3 rayPoint2, Vector3 v1, Vector3 v2, Vector3 v3) { System.out.println(rayPoint1 + " " + rayPoint2); // Compute ray direction from two points Vector3 rayDirection = VectorUtils.subNew(rayPoint2, rayPoint1); rayDirection.normalize(); // The starting point of the ray remains the same as the first point Vector3 rayOrigin = rayPoint1; // 1. Compute the normal of the plane Vector3 a = VectorUtils.subNew(v2, v1); Vector3 b = VectorUtils.subNew(v3, v1); Vector3 normal = VectorUtils.cross(a, b); normal.normalize(); // 2. Check for ray-plane intersection double dotDifference = normal.dot(rayDirection); if(Math.abs(dotDifference) < 1e-6f) return null; // Parallel check double t = -normal.dot(VectorUtils.subNew(rayOrigin, v1)) / dotDifference; // Check if intersection is in the direction of the ray // And within the segment defined by rayPoint1 and rayPoint2 if(t < 0 || t > 1) return null; // Compute the potential collision point Vector3 collision = VectorUtils.addNew(rayOrigin, VectorUtils.scaleNew(rayDirection, t)); // 3. Project the collision point onto the plane defined by quad vertices Vector3 dMS1 = VectorUtils.subNew(collision, v1); double dotA = a.dot(a); double dotB = b.dot(b); double u = dMS1.dot(a) / dotA; double v = dMS1.dot(b) / dotB; // 4. Check if the point is within the quad bounds if(u >= 0.0f && u <= 1.0f && v >= 0.0f && v <= 1.0f) { // Collision within quad bounds return collision; } // No valid collision found return null; }
e7f769bcb75567c29b99b8f1e5927610
{ "intermediate": 0.38768258690834045, "beginner": 0.3301268219947815, "expert": 0.28219062089920044 }
45,072
Finish the method in java: private static Vector3 rayPointsQuadIntersection(Vector3 rayPoint1, Vector3 rayPoint2, Vector3 v1, Vector3 v2, Vector3 v3, Vector3d v4)
f098122470fa91d08e9288b1ba94cc6b
{ "intermediate": 0.3952837586402893, "beginner": 0.3255927264690399, "expert": 0.2791235148906708 }
45,073
import os import openai from dotenv import load_dotenv import os load_dotenv() # load the environment variables from the .env file openai_api_key = os.getenv('OPENAI_API_KEY') # get the value of the OPENAI_API_KEY environment variable
a48b7780758ea03b238d045895c47f09
{ "intermediate": 0.41428253054618835, "beginner": 0.384958952665329, "expert": 0.20075853168964386 }
45,074
Привет нужно сформировать правильный массив со структурой, папка, а в ней файлы, другая папка, а в ней другие файлы и т.д <?php $dir = '../storage/'; function getTree($dir) { $root = scandir($dir); foreach($root as $value) { print_r($root); if ($value === '.' || $value === '..') {continue;} if(is_file("$dir/$value")) {$result[] = "$dir/$value"; continue;} foreach(getTree("$dir/$value") as $value) { $result[] = $value; } } return $result; } ?><pre><?php print_r( getTree($dir)); ?></pre>
6560955e155667ece1f9d4f82871448c
{ "intermediate": 0.2655937671661377, "beginner": 0.589004635810852, "expert": 0.14540164172649384 }
45,075
write a simple platformer unlimited run pygame
3ca0cf3d2afcbf873fb206cef85e9edc
{ "intermediate": 0.3581472635269165, "beginner": 0.3886886239051819, "expert": 0.253164142370224 }
45,076
hi gpt hi gpt i want you to code in autohotkey can you do this for me yes or no
89ba46e98b73f3d4a4e5c54d2b6f2400
{ "intermediate": 0.3550032079219818, "beginner": 0.2944630980491638, "expert": 0.35053369402885437 }
45,077
Can I do this in my Playwright code? // Get all question elements let questionItems = await page.$$('.ia-Questions-item'); // For each question element for (const questionItem of questionItems) { let radioGroup = await page.getByRole('radiogroup'); let textInput = await page.getByRole('spinbutton') if (radioGroup) { // Do something } else if (textInput) { // Do something } }
3b43bee57e6e414ff35a728fcff835c7
{ "intermediate": 0.39897286891937256, "beginner": 0.3579329252243042, "expert": 0.24309419095516205 }
45,078
write arudino code for when pin state to high print("helo")
56a725f65cfa4fa115fa4f326a7b9e4b
{ "intermediate": 0.2837854027748108, "beginner": 0.34331637620925903, "expert": 0.3728981614112854 }
45,079
def get_most_similar_question(userText, history): print(userText) # Compute embedding for the user input text using the initial retrieval model inp_emb = retrieval_model.encode([userText]) # Calculate similarity scores between user input text and data embeddings corr = np.inner(inp_emb, data_emb).flatten() # Get indices of the top 5 most similar texts top_5_idx = np.argsort(corr)[-5:] print('idx',top_5_idx) top_5_values = corr[top_5_idx] print('values',top_5_values) # Retrieve the texts/questions corresponding to these indices top_5_texts = new_df.iloc[top_5_idx, 1].values # Column 1 contains the texts/questions print(top_5_texts) # # Re-encode these top 5 texts using the new retrieval model # data_emb_1 = new_retrieval_model(top_5_texts) # # Calculate similarity with the input text using the new model's embeddings # inp_emb_1 = new_retrieval_model([userText]) # corr_1 = np.inner(inp_emb_1, data_emb_1).flatten() # print('corr_1',corr_1) # # Identify the highest similarity score and its index # top_1_idx = np.argmax(corr_1) # print('top_1_idx',top_1_idx) # top_1_idx = top_1_idx+1 # print('top_1_idx_11',top_1_idx) # top_1_value = corr_1[top_1_idx] # print('top_1_value',top_1_value) # top_1_texts = top_5_texts[top_1_idx+1] # print('top_1_texts',top_1_texts) print('Matching score:', top_5_values[0]) # print('Matching score second time:', top_1_value) # Decision to call predict or return the highest ranked text based on similarity threshold if top_5_values[0] < 0.8: # Placeholder for the 'predict' function, assuming you have it defined elsewhere to handle insufficient similarity scenarios return predict(userText, history) else: # Crafting a DataFrame to convert to HTML, using top_1_idx to find original index in new_df most_similar_data = new_df.iloc[top_5_idx, [1]] # Adjusted for Python's indexing most_similar_data_df = pd.DataFrame(most_similar_data) df_html_with_sql = most_similar_data_df.to_html(index=False) html_output = f"<h3>Here is the top matching result(s) for your query:</h3>{df_html_with_sql}" return html_output find top 20 matches first and then again apply the same model to top 20 for fresh embeddings and get top 10 results then then top 5 results and then top1 result
b9f796f9f009cada8f3a9a9b34d9d720
{ "intermediate": 0.32811397314071655, "beginner": 0.40225949883461, "expert": 0.2696264982223511 }