row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
10,846
Laravel is there a way to loop through all cache files stored in framwwork/cache?
dd30d72bea669661394169244724ecac
{ "intermediate": 0.5433370471000671, "beginner": 0.20877031981945038, "expert": 0.24789272248744965 }
10,847
laravel how to loop through all cached files?
3a91933f1f53ea3bda2d3d6b83e562b3
{ "intermediate": 0.41755056381225586, "beginner": 0.20447787642478943, "expert": 0.3779715299606323 }
10,848
#pragma once #include "ProtocolStructures.h" #include <atv.h> #include <nlohmann/json.hpp> #include <optional> #include <std_msgs/msg/string.h> #include <type_traits> template<typename E> constexpr auto to_underlying(E e) noexcept { return static_cast<std::underlying_type_t<E>>(e); } inline std::optional<nlohmann::json> ParseToJSON(const void* msgin) { if (msgin == nullptr) { return std::nullopt; } const auto* msg = (const std_msgs__msg__String*)msgin; nlohmann::json j = nlohmann::json::parse(msg->data.data, msg->data.data + msg->data.size, nullptr, false); if (j.is_discarded()) { return std::nullopt; } return j; } inline Auto_VCU_Vehicle_Mode_Req_t ParseToATV(const Auto_Vehicle_Mode_Req& in) { Auto_VCU_Vehicle_Mode_Req_t out; out.Auto_Allow_VRC_Offline_Req = in.Allow_VRC_Offline ? 1 : 0; out.Auto_VCU_Work_Mode_Req = to_underlying(in.Mode); return out; } inline Auto_Direct_Vehicle_Req_t ParseToATV_Direct_V(const Auto_Direct_Req& in) { Auto_Direct_Vehicle_Req_t out; out.Direct_Em_Stop_Req = in.E_Stop ? 1 : 0; out.Direct_Gear_Req = to_underlying(in.Gear); out.Direct_Tank_Mode_Req = to_underlying(in.Tank); out.Direct_Brake_Value_Req_ro = ATV_Direct_Brake_Value_Req_ro_toS(in.Brake); out.Direct_Parking_Req_ro = ATV_Direct_Parking_Req_ro_toS(in.Parking); out.Direct_St_Value_Req_ro = ATV_Direct_St_Value_Req_ro_toS(in.Steer); return out; } inline Auto_Direct_MCU_Req_A_t ParseToATV_Direct_A(const Auto_Direct_Req& in) { Auto_Direct_MCU_Req_A_t out; out.Direct_MCUFL_Tq_Req_ro = ATV_Direct_MCUFL_Tq_Req_ro_toS(in.FL_Tq); out.Direct_MCUFR_Tq_Req_ro = ATV_Direct_MCUFR_Tq_Req_ro_toS(in.FR_Tq); out.Direct_MCURL_Tq_Req_ro = ATV_Direct_MCURL_Tq_Req_ro_toS(in.RL_Tq); out.Direct_MCURR_Tq_Req_ro = ATV_Direct_MCURR_Tq_Req_ro_toS(in.RR_Tq); return out; } inline Auto_Direct_MCU_Req_B_t ParseToATV_Direct_B(const Auto_Direct_Req& in) { Auto_Direct_MCU_Req_B_t out; out.Direct_MCUML_Tq_Req_ro = ATV_Direct_MCUML_Tq_Req_ro_toS(in.ML_Tq); out.Direct_MCUMR_Tq_Req_ro = ATV_Direct_MCUMR_Tq_Req_ro_toS(in.MR_Tq); return out; } inline Auto_Indirect_Vehicle_Req_t ParseToATV(const Auto_Indirect_Req& in) { Auto_Indirect_Vehicle_Req_t out; out.Indirect_Em_Stop_Req = in.E_Stop ? 1 : 0; out.Indirect_Gear_Req = to_underlying(in.Gear); out.Indirect_Tank_Mode_Req = to_underlying(in.Tank); out.Indirect_Max_Sp_Limit_Req = in.Sp_Limit; out.Indirect_Target_Sp_Req_ro = ATV_Indirect_Target_Sp_Req_ro_toS(in.Target_Sp); out.Indirect_Brake_Value_Req_ro = ATV_Indirect_Brake_Value_Req_ro_toS(in.Brake); out.Indirect_Parking_Req_ro = ATV_Indirect_Parking_Req_ro_toS(in.Parking); out.Indirect_St_Value_Req_ro = ATV_Indirect_St_Value_Req_ro_toS(in.Steer); return out; } inline VCU_Vehicle_Status Generate_VCU_Vehicle_Status(VCU_Vehicle_Status_FB_t& fb, VCU_Vehicle_Status_FB_A_t& fba, VCU_Vehicle_Status_FB_B_t& fbb) { VCU_Vehicle_Status out{}; out.Mode = (Vehicle_Ctrl_Mode)fb.VCU_Vehicle_Ctrl_Mode_FB; out.Speed = ATV_VCU_Vehicle_Speed_FB_ro_fromS(fb.VCU_Vehicle_Speed_FB_ro); out.Battery = ATV_VCU_Vehicle_SOC_FB_ro_fromS(fb.VCU_Vehicle_SOC_FB_ro); out.Ready = (VCU_Veh_Ready_Status)fb.VCU_Veh_Ready_Status_FB; out.Gear = (Vehicle_Gear)fb.VCU_Gear_Status_FB; out.Parking = (Parking_Status)fb.VCU_Parking_Status_FB; out.E_Switch = (VCU_Emergency_Switch)fb.VCU_Emergency_Switch_FB; out.FL_Rpm = ATV_VCU_FLMotor_Rpm_FB_ro_fromS(fba.VCU_FLMotor_Rpm_FB_ro); out.FR_Rpm = ATV_VCU_FRMotor_Rpm_FB_ro_fromS(fba.VCU_FRMotor_Rpm_FB_ro); out.RL_Rpm = ATV_VCU_RLMotor_Rpm_FB_ro_fromS(fba.VCU_RLMotor_Rpm_FB_ro); out.RR_Rpm = ATV_VCU_RRMotor_Rpm_FB_ro_fromS(fba.VCU_RRMotor_Rpm_FB_ro); out.ML_Rpm = ATV_VCU_MLMotor_Rpm_FB_ro_fromS(fbb.VCU_MLMotor_Rpm_FB_ro); out.MR_Rpm = ATV_VCU_MRMotor_Rpm_FB_ro_fromS(fbb.VCU_MRMotor_Rpm_FB_ro); out.FSES_Angle = fbb.VCU_FSES_Angle_FB; out.Brake_Pre = ATV_VCU_SEB_Brake_Pre_FB_ro_fromS(fbb.VCU_SEB_Brake_Pre_FB_ro); return out; }
b852b56d94a8f119a843aac37638a1d7
{ "intermediate": 0.33020836114883423, "beginner": 0.4575117528438568, "expert": 0.21227993071079254 }
10,849
laravel how to loop through all cached files?
5f16ec8f258b7f5d87dd0ddcc6b76b5b
{ "intermediate": 0.41755056381225586, "beginner": 0.20447787642478943, "expert": 0.3779715299606323 }
10,850
p strong Instrument: должен быть скрыт в профиле, если выбрана роль band. Однако, при регистрации в профиле текст Instrument: остается пустым, когда должно быть скрыто полностью. p.s: пожалуйста, используй квадратные кавычки, иначе мой код не будет работать profile.ejs: <!DOCTYPE html> <html> <head> <title><%= musician.name %> - Musician Profile</title> </head> <body> <img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”> <h1><%= musician.name %></h1> <p><strong>Role:</strong> <%= musician.role %></p> <p><strong>Genre:</strong> <%= musician.genre %></p> <p><strong>Instrument:</strong> <% if (musician.role === ‘Artist’ && musician.instrument) { %> <%= musician.instrument %> <% } else if (musician.role === ‘Band’) { %> <!-- Instrument field should be hidden for bands --> <% } %> </p> <p><strong>Location:</strong> <%= musician.location %></p> <p><strong>Bio:</strong> <%= musician.bio %></p> <% if (musician.soundcloud) { %> <iframe width=“50%” height=“150” scrolling=“no” frameborder=“no” src=“https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true”></iframe> <% } %> <% if (musician.soundcloud1) { %> <iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” src=“https://w.soundcloud.com/player/?url=<%= musician.soundcloud1 %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true”></iframe> <% } %> <% if (userLoggedIn && username === musician.name) { %> <a href=“/profile/<%= musician.id %>/edit”>Edit profile</a> <div id=“edit-profile-modal” class=“modal”> <div class=“modal-content”> <span class=“close”>×</span> <h2>Edit Profile</h2> <form action=“/profile/<%= musician.id %>/edit” method=“POST” enctype=“multipart/form-data”> <div> <label for=“name”>Name:</label> <input type=“text” id=“name” name=“name” value=“<%= musician.name %>”> </div> <div> <label for=“name”>Role:</label> <input type=“role” id=“role” name=“role” value=“<%= musician.role %>”> </div> <div> <label for=“genre”>Genre:</label> <input type=“text” id=“genre” name=“genre” value=“<%= musician.genre %>”> </div> <div> <label for=“instrument”>Instrument:</label> <input type=“text” id=“instrument” name=“instrument” value=“<%= musician.instrument %>”> </div> <div> <label for=“location”>Location:</label> <input type=“text” id=“location” name=“location” value=“<%= musician.location %>”> </div> <div> <label for=“bio”>Bio:</label> <textarea id=“bio” name=“bio”><%= musician.bio %></textarea> </div> <div> <label for=“soundcloud”>Song 1:</label> <input type=“text” id=“soundcloud” name=“soundcloud” value=“<%= musician.soundcloud %>”> </div> <div> <label for=“soundcloud”>Song 2:</label> <input type=“text” id=“soundcloud1” name=“soundcloud1” value=“<%= musician.soundcloud1 %>”> </div> <div> <label for=“thumbnail”>Thumbnail:</label> <input type=“file” id=“thumbnail” name=“thumbnail”> </div> <button type=“submit”>Save</button> </form> </div> </div> <!-- <div> <input type=“text” name=“soundcloud[]” placeholder=“Soundcloud track URL”> <button type=“button” class=“add-music-button”>Add Music</button> </div> </div> </div> <div> <label for=“thumbnail”>Thumbnail:</label> <input type=“file” id=“thumbnail” name=“thumbnail”> </div> <button type=“submit”>Save</button> </form> </div> </div> --> <% } %> <script> const modal = document.getElementById(“edit-profile-modal”); const btn = document.getElementsByTagName(“a”)[0]; const span = document.getElementsByClassName(“close”)[0]; btn.onclick = function() { modal.style.display = “block”; } span.onclick = function() { modal.style.display = “none”; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = “none”; } } //скрыть плеер, если ссылка не внесена const song1Input = document.getElementById(“soundcloud”); const song2Input = document.getElementById(“soundcloud1”); const player1 = document.getElementsByTagName(‘iframe’)[0]; const player2 = document.getElementsByTagName(‘iframe’)[1]; let songs = { song: “”, song1: “” } function hidePlayer(player) { player.src = “”; player.style.display = “none”; } function updateSongs() { songs.song = song1Input.value.trim(); songs.song1 = song2Input.value.trim(); } function updatePlayers() { if (songs.song !== “”) { player1.src = https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true; player1.style.display = “block”; } else { hidePlayer(player1); } if (songs.song1 !== “”) { player2.src = https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true; player2.style.display = “block”; } else { hidePlayer(player2); } } song1Input.addEventListener(“input”, function() { updateSongs(); updatePlayers(); }); song2Input.addEventListener(“input”, function() { updateSongs(); updatePlayers(); }); updateSongs(); updatePlayers(); //Валидация ссылок с soundcloud function updatePlayers() { if (isValidSoundcloudUrl(songs.song)) { player1.src = https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true; player1.style.display = “block”; } else { hidePlayer(player1); } if (isValidSoundcloudUrl(songs.song1)) { player2.src = https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true; player2.style.display = “block”; } else { hidePlayer(player2); } } function isValidSoundcloudUrl(url) { const regex = /^https?://(soundcloud.com|snd.sc)/(.*)$/; return regex.test(url); } </script> <style> </style> </body> </html> register.ejs: <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8” /> <meta name=“viewport” content=“width=device-width, initial-scale=1.0” /> <meta http-equiv=“X-UA-Compatible” content=“ie=edge” /> <link rel=“stylesheet” href=“/css/main.css” /> <title>Register as a Musician</title> </head> <body> <header> <nav> <ul> <li><a href=“/”>Home</a></li> <li><a href=“/register”>Register</a></li> <li><a href=“/search”>Search</a></li> </ul> </nav> </header> <main> <h1>Register as a Musician</h1> <form method=“post” enctype=“multipart/form-data”> <label for=“name”>Name</label> <input type=“text” id=“name” name=“name” required> <label for=“role”>Role</label> <select id=“role” name=“role” required onchange=“showInstrument(this.value)”> <option value=“”>Select a role</option> <option value=“Band”>A band</option> <option value=“Artist”>Artist</option> </select> <label for=“genre”>Genre</label> <select id=“genre” name=“genre” required> <option value=“”>Select a genre</option> <option value=“Rock”>Rock</option> <option value=“Pop”>Pop</option> <option value=“Hip hop”>Hip hop</option> <option value=“Electronic”>Electronic</option> </select> <label for=“instrument” id=“instrument-label”>Instrument</label> <select id=“instrument” name=“instrument”> <option value=“”>Select a instrument</option> <option value=“Bass”>Bass</option> <option value=“Rythm guitar”>Rythm guitar</option> <option value=“Lead guitar”>Lead guitar</option> <option value=“Vocal”>Vocal</option> </select> <label for=“soundcloud”>SoundCloud URL</label> <input type=“url” id=“soundcloud” name=“soundcloud”> <label for=“password”>Password</label> <input type=“password” id=“password” name=“password” required> <label for=“location”>Location</label> <input type=“text” id=“location” name=“location” required> <label for=“login”>Login</label> <input type=“text” id=“login” name=“login” required> <label for=“thumbnail”>Thumbnail</label> <input type=“file” id=“thumbnail” name=“thumbnail”> <button type=“submit”>Register</button> </form> </main> <script> function showInstrument(role) { if (role === ‘Artist’) { document.querySelector(‘#instrument-label’).style.display = ‘block’; document.querySelector(‘#instrument’).style.display = ‘block’; } else { document.querySelector(‘#instrument-label’).style.display = ‘none’; document.querySelector(‘#instrument’).style.display = ‘none’; } } </script> </body> </html>
9496ac7dea8612ee44cef0c753b0f5a8
{ "intermediate": 0.3252398371696472, "beginner": 0.5296093225479126, "expert": 0.14515087008476257 }
10,851
in java, how to use constants in switch
4bcb27504e22ff34758a22acedd2b30a
{ "intermediate": 0.3557876646518707, "beginner": 0.47998368740081787, "expert": 0.1642286628484726 }
10,852
Historial.to_csv("C:/Users/80732688/Downloads/Demográficos/Historial_formularios_consolidado_latin1.csv",index=False,sep=";",decimal=",",encoding='latin-1') UnicodeEncodeError: 'latin-1' codec can't encode character '\u202c' in position 503: ordinal not in range(256)
ebdfebf2027da2a39b65724c9649f1f4
{ "intermediate": 0.43536150455474854, "beginner": 0.26731956005096436, "expert": 0.2973190248012543 }
10,853
Your task is to do this completely and successfully. The program must run perfectly with out any errors. It must be efficient. First off for context, here are the directions that were given: Write a program to build a schedule for a small school. You will ultimately need to figure out: A schedule for each student A schedule for each teacher A roster for each teacher’s sections Whether or not we need to hire another teacher and what that teacher would need to teach Scheduling Requirements: Every full-time teacher teaches 3 classes per day Every student takes all 4 of their classes every day Section sizes → Minimum: 5 students Maximum: 30 students A teacher may teach any course within their department, but no courses outside their department Programming Minimum Requirements: Make use of Python Dictionaries (key-value pairs) Include a Student class with the defined functions: __init__ → name, courses set_name get_name add_courses get_courses You may add anything else you deem necessary Include a Teacher class with the defined functions: __init__ → name, courses, department set_name get_name set_department get_department add_courses get_courses You may add anything else you deem necessary For more context, here is the csv file titled Schedule Builder - Students.csv: Student Name,English Course Recommendation ,Science Course Recommendation ,Math Course Recommendation ,History Course Recommendation Maria,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One Haley,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One Ryan,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two Andrei,Level 2.5,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two Timothe,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Marvin,Level 3,Sheltered Chemistry,Mainstream Math Course,Mainstream History Course Genesis,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Ashley,Level 3,Mainstream Science Course,Sheltered Geometry,Sheltered U.S. History Two Rachelle,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two Katia,Level 2,Mainstream Science Course,Sheltered Geometry,Sheltered U.S. History Two Jorge,Level 3,Mainstream Science Course,Sheltered Algebra Two,Sheltered U.S. History Two Juan,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Rosa,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Felipe,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two Jennifer,Level 2,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two Andrea,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two Luis,Level 2,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two Eddy,Level 2.5,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two Liza,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two Shoshana,Level 2.5,Sheltered Chemistry,Sheltered Pre-Algebra,Sheltered U.S. History Two Carlos,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Jesus,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Mohammed,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One Naya,Level 3,Mainstream Science Course,Sheltered Algebra Two,Sheltered U.S. History Two Francisco,Level 2,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two Jacques,Level 2,Sheltered Biology Two,Sheltered Geometry,Mainstream History Course Abdi,Level 2,Sheltered Biology Two,Sheltered Algebra Two,Sheltered U.S. History One Trinity,Level 2,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History One Aleksandr,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One Giovanna,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History One Giuliana,Level 2,Sheltered Biology Two,Sheltered Pre-Algebra,Sheltered U.S. History One Hullerie,Level 3,Mainstream Science Course,Sheltered Algebra Two,Mainstream History Course Sara,Level 2.5,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two David,Level 2,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History Two Paolo,Level 2,Mainstream Science Course,Sheltered Algebra One,Sheltered U.S. History Two Ferdinand,Level 2,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two Fernando,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two Lucia,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course Lucas,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course Damien,Level 2.5,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History Two Boris,Level 2.5,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History One Sabrina,Level 2,Sheltered Biology Two,Sheltered Algebra Two,Sheltered U.S. History Two Sabyne,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Miqueli,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two Nicolly,Level 2,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History One Nicolas,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two Jaime,Level 2,Sheltered Biology Two,Sheltered Pre-Algebra,Sheltered U.S. History One Daniel,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two Daniela,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Michelle,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two Carson,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two Janaya,Level 2,Sheltered Biology One,Sheltered Pre-Algebra,Sheltered U.S. History Two Janja,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Maria Fernanda,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two Rafael,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One Rafaela,Level 3,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two Yves,Level 2.5,Mainstream Science Course,Sheltered Geometry,Mainstream History Course Eva,Level 2.5,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History Two Amalia,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One Denis,Level 2.5,Sheltered Chemistry,Sheltered Pre-Algebra,Sheltered U.S. History Two Thelma,Level 2.5,Mainstream Science Course,Sheltered Geometry,Sheltered U.S. History Two Esther,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course Roberto,Level 3,Mainstream Science Course,Sheltered Algebra Two,Mainstream History Course Diogo,Level 2,Sheltered Biology One,Sheltered Pre-Algebra,Sheltered U.S. History Two Diego,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Samuel,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One Harriet,Level 2.5,Mainstream Science Course,Sheltered Algebra One,Sheltered U.S. History Two Cassie,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course Chandra,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two Louis,Level 3,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two Marc,Level 2.5,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two Michael,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One Jan Carlos,Level 2,Sheltered Chemistry,Sheltered Algebra One,Sheltered U.S. History One Brayan,Level 2.5,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two Martin,Level 3,Mainstream Science Course,Mainstream Math Course,Sheltered U.S. History Two Simone,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One Emilia,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One Emillie,Level 2.5,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History One Catherine,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History Two Darwin,Level 2,Sheltered Biology One,Sheltered Geometry,Sheltered U.S. History Two Fiorella,Level 3,Mainstream Science Course,Mainstream Math Course,Sheltered U.S. History Two Carmelo,Level 3,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History Two Savanna,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One Emilio,Level 3,Mainstream Science Course,Mainstream Math Course,Sheltered U.S. History Two Antonio,Level 2,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History One Steve,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Rosabella,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course Isadora,Level 2,Sheltered Chemistry,Sheltered Algebra Two,Sheltered U.S. History One Minnie,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two Pedro,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Pierre,Level 3,Mainstream Science Course,Sheltered Geometry,Mainstream History Course Isaiah,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Kayla,Level 2.5,Sheltered Chemistry,Sheltered Geometry,Sheltered U.S. History Two Adriana,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History One Jamily,Level 2,Sheltered Biology Two,Sheltered Geometry,Sheltered U.S. History One Chiara,Level 3,Mainstream Science Course,Mainstream Math Course,Mainstream History Course Charlotte,Level 2,Sheltered Biology One,Sheltered Algebra One,Sheltered U.S. History One Zach,Level 2,Sheltered Biology Two,Sheltered Algebra One,Sheltered U.S. History Two Here is the other csv file titled Schedule Builder - Teachers.csv: Teacher,Department Orion,English Leonard,English Clovis,English Hartford,English Simiczek,Math Rodrigues,Math Martinez,Math Canton,Math Thibault,History Lord,History Vu,History Bergerone,History Domenico,Science Daley,Science Lopez,Science DeMendonca,Science
75d4d65ea516503c3a98c151562c5191
{ "intermediate": 0.22594940662384033, "beginner": 0.542069137096405, "expert": 0.23198144137859344 }
10,854
Теперь мне надо придумать с поиском по городу, который брался бы из базы данных, чтоб можно было искать по городу и не было никакой путаницы. В данный момент при регистрации можно в свободной форме ввести город, поиска по городу нет. P.S: используй квадратные кавычки, когда будешь давать мне ответ app.js: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); let results = []; if (query || role) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return nameScore + genreScore > 0 && (role === '' || musician.role === role); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return (bNameScore + bGenreScore) - (aNameScore + aGenreScore); }); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; let musicians = []; if (query || role) { musicians = search(query, role); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role }); res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); register.ejs: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="/css/main.css" /> <title>Register as a Musician</title> </head> <body> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/register">Register</a></li> <li><a href="/search">Search</a></li> </ul> </nav> </header> <main> <h1>Register as a Musician</h1> <form method="post" enctype="multipart/form-data"> <label for="name">Name</label> <input type="text" id="name" name="name" required> <label for="role">Role</label> <select id="role" name="role" required onchange="showInstrument(this.value)"> <option value="">Select a role</option> <option value="Band">A band</option> <option value="Artist">Artist</option> </select> <label for="genre">Genre</label> <select id="genre" name="genre" required> <option value="">Select a genre</option> <option value="Rock">Rock</option> <option value="Pop">Pop</option> <option value="Hip hop">Hip hop</option> <option value="Electronic">Electronic</option> </select> <label for="instrument" id="instrument-label" style="display: none">Instrument</label> <select id="instrument" name="instrument" style="display: none"> <option value="">Select a instrument</option> <option value="Bass">Bass</option> <option value="Rythm guitar">Rythm guitar</option> <option value="Lead guitar">Lead guitar</option> <option value="Vocal">Vocal</option> </select> <label for="soundcloud">SoundCloud URL</label> <input type="url" id="soundcloud" name="soundcloud"> <label for="password">Password</label> <input type="password" id="password" name="password" required> <label for="location">Location</label> <input type="text" id="location" name="location" required> <label for="login">Login</label> <input type="text" id="login" name="login" required> <label for="thumbnail">Thumbnail</label> <input type="file" id="thumbnail" name="thumbnail"> <button type="submit">Register</button> </form> </main> <script> function showInstrument(role) { const instrumentLabel = document.querySelector('#instrument-label'); const instrumentSelect = document.querySelector('#instrument'); if (role === 'Artist') { instrumentLabel.style.display = 'block'; instrumentSelect.style.display = 'block'; } else { instrumentLabel.style.display = 'none'; instrumentSelect.style.display = 'none'; } } </script> </body> </html> search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action="/search" method="get"> <label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br> <br> <label for="role">Search by role:</label> <select id="role" name="role"> <option value=""> All </option> <option selected value="Band"> Band </option> <option selected value="Artist"> Artist </option> </select><br> <br> <button type="submit">Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <script> document.querySelector('form').addEventListener('submit', function (event) { event.preventDefault(); const query = document.querySelector('#query').value; const role = document.querySelector('#role').value; const url = '/search?query=' + encodeURIComponent(query) + '&role=' + encodeURIComponent(role); window.location.href = url; }); </script> </body> </html> profile.ejs: <!DOCTYPE html> <html> <head> <title><%= musician.name %> - Musician Profile</title> </head> <body> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <h1><%= musician.name %></h1> <p><strong>Role:</strong> <%= musician.role %></p> <p><strong>Genre:</strong> <%= musician.genre %></p> <% if (musician.role === 'Artist' && musician.instrument) { %> <p><strong>Instrument:</strong> <%= musician.instrument %></p> <% } %> <p><strong>Location:</strong> <%= musician.location %></p> <p><strong>Bio:</strong> <%= musician.bio %></p> <% if (musician.soundcloud) { %> <iframe width="50%" height="150" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe> <% } %> <% if (musician.soundcloud1) { %> <iframe width="100%" height="300" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud1 %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe> <% } %> <% if (userLoggedIn && username === musician.name) { %> <a href="/profile/<%= musician.id %>/edit">Edit profile</a> <div id="edit-profile-modal" class="modal"> <div class="modal-content"> <span class="close">&times;</span> <h2>Edit Profile</h2> <form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data"> <div> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<%= musician.name %>"> </div> <div> <label for="name">Role:</label> <input type="role" id="role" name="role" value="<%= musician.role %>"> </div> <div> <label for="genre">Genre:</label> <input type="text" id="genre" name="genre" value="<%= musician.genre %>"> </div> <div> <label for="instrument">Instrument:</label> <input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>"> </div> <div> <label for="location">Location:</label> <input type="text" id="location" name="location" value="<%= musician.location %>"> </div> <div> <label for="bio">Bio:</label> <textarea id="bio" name="bio"><%= musician.bio %></textarea> </div> <div> <label for="soundcloud">Song 1:</label> <input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud %>"> </div> <div> <label for="soundcloud">Song 2:</label> <input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 %>"> </div> <div> <label for="thumbnail">Thumbnail:</label> <input type="file" id="thumbnail" name="thumbnail"> </div> <button type="submit">Save</button> </form> </div> </div> <!-- <div> <input type="text" name="soundcloud[]" placeholder="Soundcloud track URL"> <button type="button" class="add-music-button">Add Music</button> </div> </div> </div> <div> <label for="thumbnail">Thumbnail:</label> <input type="file" id="thumbnail" name="thumbnail"> </div> <button type="submit">Save</button> </form> </div> </div> --> <% } %> <script> const modal = document.getElementById("edit-profile-modal"); const btn = document.getElementsByTagName("a")[0]; const span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display = "block"; } span.onclick = function() { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } //скрыть плеер, если ссылка не внесена const song1Input = document.getElementById("soundcloud"); const song2Input = document.getElementById("soundcloud1"); const player1 = document.getElementsByTagName('iframe')[0]; const player2 = document.getElementsByTagName('iframe')[1]; let songs = { song: "", song1: "" } function hidePlayer(player) { player.src = ""; player.style.display = "none"; } function updateSongs() { songs.song = song1Input.value.trim(); songs.song1 = song2Input.value.trim(); } function updatePlayers() { if (songs.song !== "") { player1.src = `https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`; player1.style.display = "block"; } else { hidePlayer(player1); } if (songs.song1 !== "") { player2.src = `https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`; player2.style.display = "block"; } else { hidePlayer(player2); } } song1Input.addEventListener("input", function() { updateSongs(); updatePlayers(); }); song2Input.addEventListener("input", function() { updateSongs(); updatePlayers(); }); updateSongs(); updatePlayers(); //Валидация ссылок с soundcloud function updatePlayers() { if (isValidSoundcloudUrl(songs.song)) { player1.src = `https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`; player1.style.display = "block"; } else { hidePlayer(player1); } if (isValidSoundcloudUrl(songs.song1)) { player2.src = `https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`; player2.style.display = "block"; } else { hidePlayer(player2); } } function isValidSoundcloudUrl(url) { const regex = /^https?:\/\/(soundcloud\.com|snd\.sc)\/(.*)$/; return regex.test(url); } </script> <style> </style> </body> </html>
15a6c1da48be3ff2026ce8ef42c38708
{ "intermediate": 0.3239416480064392, "beginner": 0.5750296115875244, "expert": 0.1010286957025528 }
10,855
Теперь мне надо придумать с поиском по городу, который брался бы из базы данных, чтоб можно было искать по городу и не было никакой путаницы. В данный момент при регистрации можно в свободной форме ввести город, поиска по городу нет. P.S: используй квадратные кавычки, когда будешь давать мне ответ app.js: const express = require(“express”); const fs = require(“fs”); const session = require(“express-session”); const fileUpload = require(“express-fileupload”); const app = express(); app.set(“view engine”, “ejs”); app.use(express.static(“public”)); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: “mysecretkey”, resave: false, saveUninitialized: false })); const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’]; function getMusicianById(id) { const data = fs.readFileSync(“./db/musicians.json”); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect(“/login”); } } function search(query = ‘’, role = ‘’) { const data = fs.readFileSync(‘./db/musicians.json’); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: /profile/${musician.id}, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); let results = []; if (query || role) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return nameScore + genreScore > 0 && (role === ‘’ || musician.role === role); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return (bNameScore + bGenreScore) - (aNameScore + aGenreScore); }); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get(“/”, (req, res) => { const data = fs.readFileSync(“./db/musicians.json”); const musicians = JSON.parse(data); res.render(“index”, { musicians: musicians.musicians }); }); app.get(“/register”, (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect(“/profile/” + musician.id); } else { res.render(“register”); } }); app.post(“/register”, (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect(“/profile/” + musician.id); } else { const data = fs.readFileSync(“./db/musicians.json”); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = “musician_” + newMusician.id + “" + file.name; file.mv(“./public/img/” + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect(“/profile/” + newMusician.id); } }); app.get(“/profile/:id”, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render(“profile”, { musician: musician }); } else { res.status(404).send(“Musician not found”); } }); app.get(“/login”, (req, res) => { res.render(“login”); }); app.post(“/login”, (req, res) => { const data = fs.readFileSync(“./db/musicians.json”); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect(“/profile/” + musician.id); } else { res.render(“login”, { error: “Invalid login or password” }); } }); app.get(“/logout”, (req, res) => { req.session.destroy(); res.redirect(“/”); }); app.get(‘/search’, (req, res) => { const query = req.query.query || ‘’; const role = req.query.role || ‘’; let musicians = []; if (query || role) { musicians = search(query, role); } else { const data = fs.readFileSync(‘./db/musicians.json’); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: /profile/${musician.id}, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); } res.locals.predefinedGenres = predefinedGenres; res.render(‘search’, { musicians, query, role }); res.redirect(‘/search’); }); app.get(“/profile/:id/edit”, requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render(“edit-profile”, { musician: musician }); } else { res.status(403).send(“Access denied”); } } else { res.status(404).send(“Musician not found”); } }); app.post(‘/profile/:id/edit’, requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send(‘Please fill out all fields’); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician’ + musician.id + ‘_’ + file.name; file.mv(‘./public/img/’ + filename); musician.thumbnail = filename; } const data = fs.readFileSync(‘./db/musicians.json’); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians)); res.redirect(‘/profile/’ + musician.id); } } else { res.status(404).send(‘Musician not found’); } }); function isValidSoundCloudUrl(url) { return url.startsWith(‘https://soundcloud.com/’); } app.listen(3000, () => { console.log(“Server started on port 3000”); }); register.ejs: <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8” /> <meta name=“viewport” content=“width=device-width, initial-scale=1.0” /> <meta http-equiv=“X-UA-Compatible” content=“ie=edge” /> <link rel=“stylesheet” href=”/css/main.css" /> <title>Register as a Musician</title> </head> <body> <header> <nav> <ul> <li><a href=“/”>Home</a></li> <li><a href=“/register”>Register</a></li> <li><a href=“/search”>Search</a></li> </ul> </nav> </header> <main> <h1>Register as a Musician</h1> <form method=“post” enctype=“multipart/form-data”> <label for=“name”>Name</label> <input type=“text” id=“name” name=“name” required> <label for=“role”>Role</label> <select id=“role” name=“role” required onchange=“showInstrument(this.value)”> <option value=“”>Select a role</option> <option value=“Band”>A band</option> <option value=“Artist”>Artist</option> </select> <label for=“genre”>Genre</label> <select id=“genre” name=“genre” required> <option value=“”>Select a genre</option> <option value=“Rock”>Rock</option> <option value=“Pop”>Pop</option> <option value=“Hip hop”>Hip hop</option> <option value=“Electronic”>Electronic</option> </select> <label for=“instrument” id=“instrument-label” style=“display: none”>Instrument</label> <select id=“instrument” name=“instrument” style=“display: none”> <option value=“”>Select a instrument</option> <option value=“Bass”>Bass</option> <option value=“Rythm guitar”>Rythm guitar</option> <option value=“Lead guitar”>Lead guitar</option> <option value=“Vocal”>Vocal</option> </select> <label for=“soundcloud”>SoundCloud URL</label> <input type=“url” id=“soundcloud” name=“soundcloud”> <label for=“password”>Password</label> <input type=“password” id=“password” name=“password” required> <label for=“location”>Location</label> <input type=“text” id=“location” name=“location” required> <label for=“login”>Login</label> <input type=“text” id=“login” name=“login” required> <label for=“thumbnail”>Thumbnail</label> <input type=“file” id=“thumbnail” name=“thumbnail”> <button type=“submit”>Register</button> </form> </main> <script> function showInstrument(role) { const instrumentLabel = document.querySelector(‘#instrument-label’); const instrumentSelect = document.querySelector(‘#instrument’); if (role === ‘Artist’) { instrumentLabel.style.display = ‘block’; instrumentSelect.style.display = ‘block’; } else { instrumentLabel.style.display = ‘none’; instrumentSelect.style.display = ‘none’; } } </script> </body> </html> search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action=“/search” method=“get”> <label for=“query”>Search by name or genre:</label> <input id=“query” name=“query” type=“text” value=“<%= query %>”><br> <br> <label for=“role”>Search by role:</label> <select id=“role” name=“role”> <option value=“”> All </option> <option selected value=“Band”> Band </option> <option selected value=“Artist”> Artist </option> </select><br> <br> <button type=“submit”>Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href=“<%= musician.profileLink %>”><%= musician.name %> <%if (musician.thumbnail) { %> <img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”> <%} %></a> - <%= musician.genre %> <%if (musician.soundcloud) { %> <a href=“%3C%=%20musician.soundcloud%20%%3E”>SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <script> document.querySelector(‘form’).addEventListener(‘submit’, function (event) { event.preventDefault(); const query = document.querySelector(‘#query’).value; const role = document.querySelector(‘#role’).value; const url = ‘/search?query=’ + encodeURIComponent(query) + ‘&role=’ + encodeURIComponent(role); window.location.href = url; }); </script> </body> </html> вот так выглядят данные в musicians.json: {“musicians”:[{“id”:1,“name”:“sukaAAAAAAA”,“genre”:“BluesZ”,“instrument”:“Guitar”,“soundcloud”:“http://soundcloud.com/dasdasdasd",“password”:“password123”,“location”:"New York”,“login”:“suka”,“bio”:“”} используй нормальные кавычки, а не закрученные
77b594164cdab1aa1308585f73f8c7f7
{ "intermediate": 0.3411130905151367, "beginner": 0.5401456356048584, "expert": 0.11874131858348846 }
10,856
Теперь мне надо придумать с поиском по городу, который брался бы из базы данных, чтоб можно было искать по городу и не было никакой путаницы. В данный момент при регистрации можно в свободной форме ввести город, поиска по городу нет. P.S: используй квадратные кавычки, когда будешь давать мне ответ app.js: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); let results = []; if (query || role) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return nameScore + genreScore > 0 && (role === '' || musician.role === role); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return (bNameScore + bGenreScore) - (aNameScore + aGenreScore); }); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; let musicians = []; if (query || role) { musicians = search(query, role); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role }); res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); register.ejs: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="/css/main.css" /> <title>Register as a Musician</title> </head> <body> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/register">Register</a></li> <li><a href="/search">Search</a></li> </ul> </nav> </header> <main> <h1>Register as a Musician</h1> <form method="post" enctype="multipart/form-data"> <label for="name">Name</label> <input type="text" id="name" name="name" required> <label for="role">Role</label> <select id="role" name="role" required onchange="showInstrument(this.value)"> <option value="">Select a role</option> <option value="Band">A band</option> <option value="Artist">Artist</option> </select> <label for="genre">Genre</label> <select id="genre" name="genre" required> <option value="">Select a genre</option> <option value="Rock">Rock</option> <option value="Pop">Pop</option> <option value="Hip hop">Hip hop</option> <option value="Electronic">Electronic</option> </select> <label for="instrument" id="instrument-label" style="display: none">Instrument</label> <select id="instrument" name="instrument" style="display: none"> <option value="">Select a instrument</option> <option value="Bass">Bass</option> <option value="Rythm guitar">Rythm guitar</option> <option value="Lead guitar">Lead guitar</option> <option value="Vocal">Vocal</option> </select> <label for="soundcloud">SoundCloud URL</label> <input type="url" id="soundcloud" name="soundcloud"> <label for="password">Password</label> <input type="password" id="password" name="password" required> <label for="location">Location</label> <input type="text" id="location" name="location" required> <label for="login">Login</label> <input type="text" id="login" name="login" required> <label for="thumbnail">Thumbnail</label> <input type="file" id="thumbnail" name="thumbnail"> <button type="submit">Register</button> </form> </main> <script> function showInstrument(role) { const instrumentLabel = document.querySelector('#instrument-label'); const instrumentSelect = document.querySelector('#instrument'); if (role === 'Artist') { instrumentLabel.style.display = 'block'; instrumentSelect.style.display = 'block'; } else { instrumentLabel.style.display = 'none'; instrumentSelect.style.display = 'none'; } } </script> </body> </html> search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action="/search" method="get"> <label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br> <br> <label for="role">Search by role:</label> <select id="role" name="role"> <option value=""> All </option> <option selected value="Band"> Band </option> <option selected value="Artist"> Artist </option> </select><br> <br> <button type="submit">Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <script> document.querySelector('form').addEventListener('submit', function (event) { event.preventDefault(); const query = document.querySelector('#query').value; const role = document.querySelector('#role').value; const url = '/search?query=' + encodeURIComponent(query) + '&role=' + encodeURIComponent(role); window.location.href = url; }); </script> </body> </html> вот так выглядят данные в musicians.json: {"musicians":[{"id":1,"name":"sukaAAAAAAA","genre":"BluesZ","instrument":"Guitar","soundcloud":"http://soundcloud.com/dasdasdasd","password":"password123","location":"New York","login":"suka","bio":""}
b38b593d422ead2fea371df8fdaf87b5
{ "intermediate": 0.3239416480064392, "beginner": 0.5750296115875244, "expert": 0.1010286957025528 }
10,857
in testng, with xml in maven, how to run specific test in command
35a70d7c081957f7e49c36548e8c5a27
{ "intermediate": 0.6001169085502625, "beginner": 0.17359893023967743, "expert": 0.22628416121006012 }
10,858
Теперь мне надо придумать с поиском по городу, который брался бы из базы данных, чтоб можно было искать по городу и не было никакой путаницы. В данный момент при регистрации можно в свободной форме ввести город, поиска по городу нет. P.S: используй квадратные кавычки, когда будешь давать мне ответ app.js: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); let results = []; if (query || role) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return nameScore + genreScore > 0 && (role === '' || musician.role === role); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return (bNameScore + bGenreScore) - (aNameScore + aGenreScore); }); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; let musicians = []; if (query || role) { musicians = search(query, role); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role }); res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); register.ejs: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="/css/main.css" /> <title>Register as a Musician</title> </head> <body> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/register">Register</a></li> <li><a href="/search">Search</a></li> </ul> </nav> </header> <main> <h1>Register as a Musician</h1> <form method="post" enctype="multipart/form-data"> <label for="name">Name</label> <input type="text" id="name" name="name" required> <label for="role">Role</label> <select id="role" name="role" required onchange="showInstrument(this.value)"> <option value="">Select a role</option> <option value="Band">A band</option> <option value="Artist">Artist</option> </select> <label for="genre">Genre</label> <select id="genre" name="genre" required> <option value="">Select a genre</option> <option value="Rock">Rock</option> <option value="Pop">Pop</option> <option value="Hip hop">Hip hop</option> <option value="Electronic">Electronic</option> </select> <label for="instrument" id="instrument-label" style="display: none">Instrument</label> <select id="instrument" name="instrument" style="display: none"> <option value="">Select a instrument</option> <option value="Bass">Bass</option> <option value="Rythm guitar">Rythm guitar</option> <option value="Lead guitar">Lead guitar</option> <option value="Vocal">Vocal</option> </select> <label for="soundcloud">SoundCloud URL</label> <input type="url" id="soundcloud" name="soundcloud"> <label for="password">Password</label> <input type="password" id="password" name="password" required> <label for="location">Location</label> <input type="text" id="location" name="location" required> <label for="login">Login</label> <input type="text" id="login" name="login" required> <label for="thumbnail">Thumbnail</label> <input type="file" id="thumbnail" name="thumbnail"> <button type="submit">Register</button> </form> </main> <script> function showInstrument(role) { const instrumentLabel = document.querySelector('#instrument-label'); const instrumentSelect = document.querySelector('#instrument'); if (role === 'Artist') { instrumentLabel.style.display = 'block'; instrumentSelect.style.display = 'block'; } else { instrumentLabel.style.display = 'none'; instrumentSelect.style.display = 'none'; } } </script> </body> </html> search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action="/search" method="get"> <label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br> <br> <label for="role">Search by role:</label> <select id="role" name="role"> <option value=""> All </option> <option selected value="Band"> Band </option> <option selected value="Artist"> Artist </option> </select><br> <br> <button type="submit">Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <script> document.querySelector('form').addEventListener('submit', function (event) { event.preventDefault(); const query = document.querySelector('#query').value; const role = document.querySelector('#role').value; const url = '/search?query=' + encodeURIComponent(query) + '&role=' + encodeURIComponent(role); window.location.href = url; }); </script> </body> </html> вот так выглядят данные в musicians.json: {"musicians":[{"id":1,"name":"sukaAAAAAAA","genre":"BluesZ","instrument":"Guitar","soundcloud":"http://soundcloud.com/dasdasdasd","password":"password123","location":"New York","login":"suka","bio":""} P.S: используй квадратные кавычки, когда будешь давать мне ответ
78f39521fd1916831b492b55bed5abd7
{ "intermediate": 0.3239416480064392, "beginner": 0.5750296115875244, "expert": 0.1010286957025528 }
10,859
in testng suite xml, how to specify test case under test
1bf208a336ce39f03b99db22e1d0d845
{ "intermediate": 0.28804484009742737, "beginner": 0.46297401189804077, "expert": 0.24898117780685425 }
10,860
Мне нужно добавить поиск по локации. Причем, поиск должен быть "умным", так как чтобы не возиться с предустановленным городами, пользователь при регистрации может ввести собственное название города в свободной форме, я дал такую возможность. Нужно, сделать так, чтобы если пользователь ввел "масква", он по получил "Москва" app.js: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); let results = []; if (query || role) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return nameScore + genreScore > 0 && (role === '' || musician.role === role); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return (bNameScore + bGenreScore) - (aNameScore + aGenreScore); }); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; let musicians = []; if (query || role) { musicians = search(query, role); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role }); res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action="/search" method="get"> <label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br> <br> <label for="role">Search by role:</label> <select id="role" name="role"> <option value=""> All </option> <option selected value="Band"> Band </option> <option selected value="Artist"> Artist </option> </select><br> <br> <br> <button type="submit">Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <script> document.querySelector('form').addEventListener('submit', function (event) { event.preventDefault(); const query = document.querySelector('#query').value; const role = document.querySelector('#role').value; const url = '/search?query=' + encodeURIComponent(query) + '&role=' + encodeURIComponent(role); window.location.href = url; }); </script> </body> </html> P.S: don't use curly brackets, use normal bracket when you ll give me the answer
9ee58624f23b16eac96bdeae021957da
{ "intermediate": 0.28323832154273987, "beginner": 0.5976325869560242, "expert": 0.11912913620471954 }
10,861
Мне нужно добавить поиск по локации. Причем, поиск должен быть "умным", так как чтобы не возиться с предустановленным городами, пользователь при регистрации может ввести собственное название города в свободной форме, я дал такую возможность. Нужно, сделать так, чтобы если пользователь ввел "масква", он по получил "Москва" app.js: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); let results = []; if (query || role) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return nameScore + genreScore > 0 && (role === '' || musician.role === role); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return (bNameScore + bGenreScore) - (aNameScore + aGenreScore); }); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; let musicians = []; if (query || role) { musicians = search(query, role); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role }); res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action="/search" method="get"> <label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br> <br> <label for="role">Search by role:</label> <select id="role" name="role"> <option value=""> All </option> <option selected value="Band"> Band </option> <option selected value="Artist"> Artist </option> </select><br> <br> <br> <button type="submit">Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <script> document.querySelector('form').addEventListener('submit', function (event) { event.preventDefault(); const query = document.querySelector('#query').value; const role = document.querySelector('#role').value; const url = '/search?query=' + encodeURIComponent(query) + '&role=' + encodeURIComponent(role); window.location.href = url; }); </script> </body> </html> P.S: don't use curly brackets, use normal bracket when you ll give me the answer
82231fef9691a152451a267c8bba3c2d
{ "intermediate": 0.28323832154273987, "beginner": 0.5976325869560242, "expert": 0.11912913620471954 }
10,862
k-means clustering example for a text value only database
058eac3589a9b1ecf85cca3034a4e019
{ "intermediate": 0.2719920873641968, "beginner": 0.15337106585502625, "expert": 0.5746368169784546 }
10,863
create a sitemap.xml fully optimized for SEO ranking for google. domain name is : "http://elctronicads.com/", and this is some of the keywords: "مقاولات, مقاولات الكويت, بناء منازل, مقاول عام, مقاول الكويت, مقاولين, ترميمات عامة, ترميمات, مقاول, مقاولات عامة, مقاول بناء, ديكورات, تصميم داخلي, هندسة معمارية, تشطيبات, أصباغ, تركيب أرضيات, تصميم حدائق, تركيب أثاث, أعمال كهربائية, ترتيبات داخلية, تركيب مطابخ, تركيب شبابيك, مقاولات مباني, أعمال صيانة, تصميم وتركيب برجولات, أعمال دهانات, تركيب سيراميك وبلاط, تركيب أبواب, أعمال تركيبات سباكة, تركيب منظومات تكييف وتبريد", feel free to add more. This is an arabic website mainly serving people in kuwait.
2b8cb71fcf7f272ffdea6a488e387ade
{ "intermediate": 0.3260144889354706, "beginner": 0.3064214885234833, "expert": 0.36756405234336853 }
10,864
Check whether this algorithim calulates the no ways to pay a amount using couns from a given coins array . And dry run it for amount is 21 and coins[1,8,27] Algorithm itrcountways(amount, coins[]) n = length(coins) for i = 0 to n do ways[0][i] = 1 for i = 1 to amount for j = 1 to n if ( i - coins[j - 1] >= 0 ) use = ways [i - coins[j - 1]][j] else use = 0 skip = ways[i][j - 1] ways [i][j] = use + skip return ways[amount][n]
b4792e54dce80cf4b6d208d14d8f1abd
{ "intermediate": 0.24579228460788727, "beginner": 0.14663472771644592, "expert": 0.6075729131698608 }
10,865
ssh-copy-id
8e1ee189004ed850a90565ee2791f4ae
{ "intermediate": 0.31444087624549866, "beginner": 0.29066601395606995, "expert": 0.3948931396007538 }
10,866
у меня есть прямоугольник разделенный на равные квадратики равноудаленными друг от друга линиями, как мне имея координаты точки в этом прямоугольнике определить в каком она квадратике? помести весь код в одну функцию lua, известно только количество rows, cols функция должна определять сама.
09ffae3ddf544b0319d3d27d606d4e78
{ "intermediate": 0.2913738191127777, "beginner": 0.35684752464294434, "expert": 0.35177871584892273 }
10,867
const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); const fuzzball = require("fuzzball"); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); const locationNames = ["Москва", "Санкт-Петербург"]; // Add your standardized location names here. function normalizeLocationName(userInput) { const matches = fuzzball.extract(userInput, locationNames, { returnObjects: true }); const bestMatch = matches.sort((a, b) => b.score - a.score)[0]; return bestMatch.choice || userInput; } const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '', location = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); let results = []; if (query || role || location) { const lowerQuery = query.toLowerCase(); const normalizedLocation = normalizeLocationName(location); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; //return nameScore + genreScore > 0 && (role === '' || musician.role === role); return nameScore + genreScore > 0 && (role === '' || musician.role === role) && (location === '' || musician.location === normalizedLocation); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; return (bNameScore + bGenreScore) - (aNameScore + aGenreScore); }); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: normalizeLocationName(req.body.location), role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; const location = req.query.location || ''; // Add location variable let musicians = []; if (query || role || location) { musicians = search(query, role, location); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role, location }); //res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); когда ввожу в поле регистрации, предположим, New York, мне выставляет Санк-Петербург. Нужно выставить предустановленные имена при регистрации? register.ejs: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="/css/main.css" /> <title>Register as a Musician</title> </head> <body> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/register">Register</a></li> <li><a href="/search">Search</a></li> </ul> </nav> </header> <main> <h1>Register as a Musician</h1> <form method="post" enctype="multipart/form-data"> <label for="name">Name</label> <input type="text" id="name" name="name" required> <label for="role">Role</label> <select id="role" name="role" required onchange="showInstrument(this.value)"> <option value="">Select a role</option> <option value="Band">A band</option> <option value="Artist">Artist</option> </select> <label for="genre">Genre</label> <select id="genre" name="genre" required> <option value="">Select a genre</option> <option value="Rock">Rock</option> <option value="Pop">Pop</option> <option value="Hip hop">Hip hop</option> <option value="Electronic">Electronic</option> </select> <label for="instrument" id="instrument-label" style="display: none">Instrument</label> <select id="instrument" name="instrument" style="display: none"> <option value="">Select a instrument</option> <option value="Bass">Bass</option> <option value="Rythm guitar">Rythm guitar</option> <option value="Lead guitar">Lead guitar</option> <option value="Vocal">Vocal</option> </select> <label for="soundcloud">SoundCloud URL</label> <input type="url" id="soundcloud" name="soundcloud"> <label for="password">Password</label> <input type="password" id="password" name="password" required> <label for="location">Location</label> <input type="text" id="location" name="location" required> <label for="login">Login</label> <input type="text" id="login" name="login" required> <label for="thumbnail">Thumbnail</label> <input type="file" id="thumbnail" name="thumbnail"> <button type="submit">Register</button> </form> </main> <script> function showInstrument(role) { const instrumentLabel = document.querySelector('#instrument-label'); const instrumentSelect = document.querySelector('#instrument'); if (role === 'Artist') { instrumentLabel.style.display = 'block'; instrumentSelect.style.display = 'block'; } else { instrumentLabel.style.display = 'none'; instrumentSelect.style.display = 'none'; } } </script> </body> </html> search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action="/search" method="get"> <label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br> <br> <label for="role">Search by role:</label> <select id="role" name="role"> <option value=""> All </option> <option value="Band"> Band </option> <option value="Artist"> Artist </option> </select> <label for="location">Search by location:</label> <input id="location" name="location" type="text" value="<%= location %>"> <br> <!-- Add new input field for location --> <br> <br> <button type="submit">Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <!-- Update the form submission script --> <script> document.querySelector("form").addEventListener("submit", function (event) { event.preventDefault(); const query = document.querySelector("#query").value; const role = document.querySelector("#role").value; const location = document.querySelector("#location").value; const url = "/search?query=" + encodeURIComponent(query) + "&role=" + encodeURIComponent(role) + "&location=" + encodeURIComponent(location); window.location.href = url; }); </script> </body> </html>
b0d74abc69bd68f70b0036bf1a3f1340
{ "intermediate": 0.40311843156814575, "beginner": 0.4422905445098877, "expert": 0.15459097921848297 }
10,868
httpErrors errorMode="Custom"
7ccd0a76bf29723f14488e945949d210
{ "intermediate": 0.28953731060028076, "beginner": 0.3606216311454773, "expert": 0.34984102845191956 }
10,869
Мне нужен более умный поиск по городам (локациям), сейчас алгоритм ищет лишние города. Нужна такая же фильтрация, как с именами или жанрами, только умнее const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); const fuzzball = require("fuzzball"); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); function normalizeLocationName(userInput) { const matches = fuzzball.extract(userInput, locationNames, { returnObjects: true }); const bestMatch = matches.sort((a, b) => b.score - a.score)[0]; return bestMatch.choice || userInput; } const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '', location = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); let results = []; if (query || role || location) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const locationScore = location ? fuzzball.partial_ratio(musician.location.toLowerCase(), location.toLowerCase()) : 0; return nameScore + genreScore + locationScore > 0 && (role === '' || musician.role === role) && (!location || locationScore >= 75); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const aLocationScore = fuzzball.partial_ratio(a.location.toLowerCase(), location.toLowerCase()); const bLocationScore = fuzzball.partial_ratio(b.location.toLowerCase(), location.toLowerCase()); return (bNameScore + bGenreScore + bLocationScore) - (aNameScore + aGenreScore + aLocationScore); }); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: normalizeLocationName(req.body.location), role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; const location = req.query.location || ''; // Add location variable let musicians = []; if (query || role || location) { musicians = search(query, role, location); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role, location }); //res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); });
0ee62d90ecccc070a35206e516173334
{ "intermediate": 0.36118215322494507, "beginner": 0.43919306993484497, "expert": 0.19962477684020996 }
10,870
import asyncio import aiohttp bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' # Create a semaphore with a limit semaphore = asyncio.Semaphore(5) async def get_internal_transactions(start_block, end_block, session): async with semaphore: url = f'https://api.bscscan.com/api?module=account&action=txlistinternal&startblock={start_block}&endblock={end_block}&sort=asc&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return [] return data.get('result', []) async def get_contracts_in_range(block_range, target_from_address, session): contracts = [] for block_number in block_range: block_contracts = await get_contracts_in_block(block_number, target_from_address, session) contracts.extend(block_contracts) return contracts async def get_contracts_in_block(block_number, target_from_address, session): transactions = await get_internal_transactions(block_number, block_number, session) filtered_contracts = [] for tx in transactions: if isinstance(tx, dict) and tx.get('isError') == '0' and tx.get('contractAddress') != '' and tx.get('from', '').lower() == target_from_address.lower(): filtered_contracts.append(tx) return filtered_contracts async def display_new_contracts(start_block, end_block, target_from_address, chunk_size=100): async with aiohttp.ClientSession() as session: block_ranges = [ range(b, min(b + chunk_size, end_block + 1)) for b in range(start_block, end_block + 1, chunk_size) ] coroutines = [get_contracts_in_range(rng, target_from_address, session) for rng in block_ranges] results = await asyncio.gather(*coroutines) contracts = [contract for chunk_contracts in results for contract in chunk_contracts] if not contracts: print('No new contracts found.') else: for contract in contracts: print(f"Block: {contract['blockNumber']} - Address: {contract['contractAddress']}") async def main(): start_block = 28865850 # Replace with your desired start block end_block = 28865900 # Replace with your desired end block target_from_address = '0x863b49ae97c3d2a87fd43186dfd921f42783c853' await display_new_contracts(start_block, end_block, target_from_address) asyncio.run(main()) Complete the code above so that it displays information about each processed block
f3701fc04c3e0ed70799a81822f75d1c
{ "intermediate": 0.34487810730934143, "beginner": 0.45331695675849915, "expert": 0.20180495083332062 }
10,871
ReferenceError: locationNames is not defined at normalizeLocationName (C:\Users\Ilya\Downloads\my-musician-network\app.js:22:47) at C:\Users\Ilya\Downloads\my-musician-network\app.js:140:17 at Layer.handle [as handle_request] (C:\Users\Ilya\Downloads\my-musician-network\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\Ilya\Downloads\my-musician-network\node_modules\express\lib\router\route.js:144:13) at Route.dispatch (C:\Users\Ilya\Downloads\my-musician-network\node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (C:\Users\Ilya\Downloads\my-musician-network\node_modules\express\lib\router\layer.js:95:5) at C:\Users\Ilya\Downloads\my-musician-network\node_modules\express\lib\router\index.js:284:15 at Function.process_params (C:\Users\Ilya\Downloads\my-musician-network\node_modules\express\lib\router\index.js:346:12) at next (C:\Users\Ilya\Downloads\my-musician-network\node_modules\express\lib\router\index.js:280:10) at C:\Users\Ilya\Downloads\my-musician-network\app.js:106:3 const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); const fuzzball = require("fuzzball"); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); function normalizeLocationName(userInput) { const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true }); const bestMatch = matches.sort((a, b) => b.score - a.score)[0]; return bestMatch.score >= 75 ? bestMatch.choice : userInput; } const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '', location = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); let results = []; if (query || role || location) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const locationScore = location ? fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()) : 0; return nameScore + genreScore + locationScore > 0 && (role === '' || musician.role === role) && (locationScore >= 75); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; // Sort by name score, then genre score, then location score (descending) if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) { return 1; } else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) { return -1; } else { return 0; } }); // Remove duplicates results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.location === result.location )) ); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: normalizeLocationName(req.body.location), role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; const location = req.query.location || ''; // Add location variable let musicians = []; if (query || role || location) { musicians = search(query, role, location); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role, location }); //res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); });
e63ea96c0813a00fde986dae05a95c6a
{ "intermediate": 0.4836479127407074, "beginner": 0.35137367248535156, "expert": 0.16497839987277985 }
10,872
размытый поиск по городам все равно не очень точный, хотя уже лучше. Предположим, есть пользователь из города Manchester, я ввожу Manc - и ничего не находит, хотя когда ввожу моск - мне выдает Москву - работает нормально. Я не хочу использовать базы и сторонние api, надо сосредоточиться на своем алгоритме: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); const fuzzball = require("fuzzball"); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); /* function normalizeLocationName(userInput) { //const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true }); const bestMatch = matches.sort((a, b) => b.score - a.score)[0]; return bestMatch.score >= 75 ? bestMatch.choice : userInput; } */ const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '', location = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); let results = []; if (query || role || location) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const locationScore = location ? fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()) : 0; return nameScore + genreScore + locationScore > 0 && (role === '' || musician.role === role) && (locationScore >= 75); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; // Sort by name score, then genre score, then location score (descending) if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) { return 1; } else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) { return -1; } else { return 0; } }); // Remove duplicates results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.location === result.location )) ); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; const location = req.query.location || ''; // Add location variable let musicians = []; if (query || role || location) { musicians = search(query, role, location); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role, location }); //res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); });
280f73f6920bf88d5c00c5513390c2cf
{ "intermediate": 0.48344749212265015, "beginner": 0.35984474420547485, "expert": 0.1567077934741974 }
10,873
in unreal engine 4, how to make a kill cam to replay the last kill in c++?
636ef7363f1edfeb219b69703ac61aec
{ "intermediate": 0.2255287915468216, "beginner": 0.16586029529571533, "expert": 0.6086109280586243 }
10,874
Plot the series using a line chart. Briefly describe what you see: Is it a positive or negative trend? Is the trend increasing? What kind of short term fluctuations do you observe?
3a28a2af6359c0051a61185d82e134c1
{ "intermediate": 0.402483731508255, "beginner": 0.27392110228538513, "expert": 0.32359519600868225 }
10,875
lock down boot partition
75d2adfd4627b9d584138f9bcd5c24d8
{ "intermediate": 0.3042953610420227, "beginner": 0.4160231053829193, "expert": 0.279681533575058 }
10,876
Нужно чтобы fuzzball давал пользователю при вводе города подсказки текстовые в поле ввода города, как надо правильно писать название города, чтобы минимизировать неразбериху при разности написания городов const express = require(“express”); const fs = require(“fs”); const session = require(“express-session”); const fileUpload = require(“express-fileupload”); const app = express(); const fuzzball = require(“fuzzball”); app.set(“view engine”, “ejs”); app.use(express.static(“public”)); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: “mysecretkey”, resave: false, saveUninitialized: false })); /* function normalizeLocationName(userInput) { //const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true }); const bestMatch = matches.sort((a, b) => b.score - a.score)[0]; return bestMatch.score >= 75 ? bestMatch.choice : userInput; } */ const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’]; function getMusicianById(id) { const data = fs.readFileSync(“./db/musicians.json”); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect(“/login”); } } function search(query = ‘’, role = ‘’, location = ‘’) { const data = fs.readFileSync(‘./db/musicians.json’); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: /profile/${musician.id}, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); let results = []; if (query || role || location) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь return nameScore + genreScore + locationScore > 0 && (role === ‘’ || musician.role === role) && (location === ‘’ || locationScore >= 75); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; // Sort by name score, then genre score, then location score (descending) if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) { return 1; } else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) { return -1; } else { return 0; } }); // Remove duplicates results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.location === result.location )) ); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get(“/”, (req, res) => { const data = fs.readFileSync(“./db/musicians.json”); const musicians = JSON.parse(data); res.render(“index”, { musicians: musicians.musicians }); }); app.get(“/register”, (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect(“/profile/” + musician.id); } else { res.render(“register”); } }); app.post(“/register”, (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect(“/profile/” + musician.id); } else { const data = fs.readFileSync(“./db/musicians.json”); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = “musician_” + newMusician.id + “" + file.name; file.mv(“./public/img/” + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect(“/profile/” + newMusician.id); } }); app.get(“/profile/:id”, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render(“profile”, { musician: musician }); } else { res.status(404).send(“Musician not found”); } }); app.get(“/login”, (req, res) => { res.render(“login”); }); app.post(“/login”, (req, res) => { const data = fs.readFileSync(“./db/musicians.json”); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect(“/profile/” + musician.id); } else { res.render(“login”, { error: “Invalid login or password” }); } }); app.get(“/logout”, (req, res) => { req.session.destroy(); res.redirect(“/”); }); app.get(‘/search’, (req, res) => { const query = req.query.query || ‘’; const role = req.query.role || ‘’; const location = req.query.location || ‘’; // Add location variable let musicians = []; if (query || role || location) { musicians = search(query, role, location); } else { const data = fs.readFileSync(‘./db/musicians.json’); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: /profile/${musician.id}, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); } res.locals.predefinedGenres = predefinedGenres; res.render(‘search’, { musicians, query, role, location }); //res.redirect(‘/search’); }); app.get(“/profile/:id/edit”, requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render(“edit-profile”, { musician: musician }); } else { res.status(403).send(“Access denied”); } } else { res.status(404).send(“Musician not found”); } }); app.post(‘/profile/:id/edit’, requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send(‘Please fill out all fields’); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician’ + musician.id + ‘_’ + file.name; file.mv(‘./public/img/’ + filename); musician.thumbnail = filename; } const data = fs.readFileSync(‘./db/musicians.json’); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians)); res.redirect(‘/profile/’ + musician.id); } } else { res.status(404).send(‘Musician not found’); } }); function isValidSoundCloudUrl(url) { return url.startsWith(‘https://soundcloud.com/’); } app.listen(3000, () => { console.log(“Server started on port 3000”); }); search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action=”/search" method=“get”> <label for=“query”>Search by name or genre:</label> <input id=“query” name=“query” type=“text” value=“<%= query %>”><br> <br> <label for=“role”>Search by role:</label> <select id=“role” name=“role”> <option value=“”> All </option> <option value=“Band”> Band </option> <option value=“Artist”> Artist </option> </select> <label for=“location”>Search by location:</label> <input id=“location” name=“location” type=“text” value=“<%= location %>”> <br> <!-- Add new input field for location --> <br> <br> <button type=“submit”>Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href=“<%= musician.profileLink %>”><%= musician.name %> <%if (musician.thumbnail) { %> <img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href=“%3C%=%20musician.soundcloud%20%%3E”>SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <!-- Update the form submission script --> <script> document.querySelector(“form”).addEventListener(“submit”, function (event) { event.preventDefault(); const query = document.querySelector(“#query”).value; const role = document.querySelector(“#role”).value; const location = document.querySelector(“#location”).value; const url = “/search?query=” + encodeURIComponent(query) + “&role=” + encodeURIComponent(role) + “&location=” + encodeURIComponent(location); window.location.href = url; }); </script> </body> </html>
125b7195506844d4060c6e386a2ad676
{ "intermediate": 0.33114519715309143, "beginner": 0.5221036076545715, "expert": 0.14675119519233704 }
10,877
with git command, how to get latest code from main branch into other branch
f33e0bb28b1a9cc8feb3fc6bbe5bdb27
{ "intermediate": 0.3349756598472595, "beginner": 0.3223002851009369, "expert": 0.3427240252494812 }
10,878
I've an asp.net core mvc project, need you to create an "add" view page that get "product" class data from the user, it contains name, text, image. use productviewmodel to get the data from the view. and use Byte[] datatype for img saving. design the form in the viewpage using tailwindcss. and save the data in the product table in the applicationdbcontext using the best, fastest practises.
ea2fdaf02ec3ce90badbde5f1a931677
{ "intermediate": 0.668166995048523, "beginner": 0.1816519945859909, "expert": 0.15018102526664734 }
10,879
this is my code : df = df.to_excel('data/Ludovico Einaudi.xlsx', encoding='UTF-8', sheet_name='track', index_label='id') df, and it is error :--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[15], line 1 ----> 1 df = df.to_excel('data/Ludovico Einaudi.xlsx', encoding='UTF-8', sheet_name='track', index_label='id') 2 df AttributeError: 'NoneType' object has no attribute 'to_excel'
fc08042687d2746f3988da0143abf376
{ "intermediate": 0.47997722029685974, "beginner": 0.2461336851119995, "expert": 0.27388912439346313 }
10,880
static void case1_vrb() { ot_video_buffer_attr attr = {0}; attr.buf_blks[0].size = 1280*720*3/2; attr.buf_blks[0].cnt = 5; attr.buf_blks[1].size = 640*360*3/2; attr.buf_blks[1].cnt = 2; attr.buf_blks[2].size = 1920*1080*3/2; attr.buf_blks[2].cnt = 3; attr.cnt = 3; buffer_pool_handle comm_hdl = NULL; buffer_pool_handle usr_hdl = NULL; buffer_pool_handle usr_hdl2 = NULL; buffer_pool_blk_handle blk_hdl = NULL; buffer_pool_blk blk_attr = {0}; buffer_pool_blk blk_attr1 = {0}; buffer_pool_blk blk_attr2 = {0}; buffer_pool_blk blk_attr3 = {0}; u32 size1 = 300; u32 size2 = 640*360*2; u32 size3 = 500; u32 size4 = 550; u32 size5 = 1000; media_proc_node node = NODE_VI; (void)smr_init(NULL); vrb_init_test(&attr, &comm_hdl); if(comm_hdl == NULL){ vrb_deinit(); return; } printf("case1 pool_hdl[%p]", comm_hdl); (void)buffer_pool_acquire_blk(comm_hdl, size1, NODE_VI, &blk_attr); printf("blk acquire blk: pool_hdl[%u] blk_hdl[%u], phys[%u] blk_size[%u] req_size[%u] \n", usr_hdl, blk_attr.blk_hdl, blk_attr.phy_addr, blk_attr.block_size,size1); void* virt = smr_mmap(blk_attr.phy_addr, size1, 0); printf("unmmap virt[0x%lx] ret[%d]", virt, smr_munmap(virt)); (void)buffer_pool_acquire_blk(comm_hdl, size1, NODE_VPROC, &blk_attr1); printf("blk acquire blk: pool_hdl[%u] blk_hdl[%px], phys[%u] blk_size[%u] req_size[%u] \n", usr_hdl, blk_attr1.blk_hdl, blk_attr1.phy_addr, blk_attr1.block_size,size2); virt = smr_mmap(blk_attr1.phy_addr, size2, 0); printf("unmmap virt[0x%lx] ret[%d]", virt, smr_munmap(virt)); (void)buffer_pool_acquire_blk(comm_hdl, size2, NODE_VO, &blk_attr2); printf("blk acquire blk: pool_hdl[%u] blk_hdl[%u], phys[%u] blk_size[%u] req_size[%u] \n", usr_hdl, blk_attr2.blk_hdl, blk_attr2.phy_addr, blk_attr2.block_size,size3); (void)buffer_pool_release_blk(comm_hdl, node, blk_attr.blk_hdl); (void)buffer_pool_blk_ref_add(comm_hdl, node, blk_attr1.blk_hdl); (void)buffer_pool_blk_ref_sub(comm_hdl, node, blk_attr1.blk_hdl); (void)buffer_pool_release_blk(comm_hdl, NODE_VPROC, blk_attr1.blk_hdl); (void)buffer_pool_release_blk(comm_hdl, NODE_VO, blk_attr2.blk_hdl); buffer_pool_blk_hdl_2_pool_hdl(blk_attr1.blk_hdl, &usr_hdl2); printf("blk acquire blk: pool_hdl[%u] blk_hdl[%u] \n", usr_hdl2, blk_attr1.blk_hdl); buffer_pool_phys_addr_2_blk_hdl(comm_hdl, blk_attr1.phy_addr, &blk_hdl); printf("blk acquire blk: pool_hdl[%u] blk_hdl[%u] \n", usr_hdl, blk_hdl); vrb_deinit(); (void)smr_deinit(); }这段代码什么意思?每行代码是干什么的?
adf9a95f7306f2c5d4836c7b435efeda
{ "intermediate": 0.3101113736629486, "beginner": 0.41854336857795715, "expert": 0.27134525775909424 }
10,881
Мне нужно сделать так, чтоб при регистрации и поиске пользователь мог выбрать подходящий город, регион из json файла с городами, его примерная структура, cities.json: [ { "region": "Москва и Московская обл.", "city": "Москва" }, { "region": "Москва и Московская обл.", "city": "Абрамцево" }, { "region": "Москва и Московская обл.", "city": "Алабино" }, { "region": "Москва и Московская обл.", "city": "Апрелевка" }, { "region": "Москва и Московская обл.", "city": "Архангельское" }, { "region": "Москва и Московская обл.", "city": "Ашитково" Сейчас у меня поиск организован по совпадению строк location. Также город, регион должен отображаться в профиле код: app.js: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); const fuzzball = require("fuzzball"); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); /* function normalizeLocationName(userInput) { //const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true }); const bestMatch = matches.sort((a, b) => b.score - a.score)[0]; return bestMatch.score >= 75 ? bestMatch.choice : userInput; } */ const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '', location = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); let results = []; if (query || role || location) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь return nameScore + genreScore + locationScore > 0 && (role === '' || musician.role === role) && (location === '' || locationScore >= 75); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; // Sort by name score, then genre score, then location score (descending) if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) { return 1; } else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) { return -1; } else { return 0; } }); // Remove duplicates results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.location === result.location )) ); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; const location = req.query.location || ''; // Add location variable let musicians = []; if (query || role || location) { musicians = search(query, role, location); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role, location }); //res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); register.ejs: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="/css/main.css" /> <title>Register as a Musician</title> </head> <body> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/register">Register</a></li> <li><a href="/search">Search</a></li> </ul> </nav> </header> <main> <h1>Register as a Musician</h1> <form method="post" enctype="multipart/form-data"> <label for="name">Name</label> <input type="text" id="name" name="name" required> <label for="role">Role</label> <select id="role" name="role" required onchange="showInstrument(this.value)"> <option value="">Select a role</option> <option value="Band">A band</option> <option value="Artist">Artist</option> </select> <label for="genre">Genre</label> <select id="genre" name="genre" required> <option value="">Select a genre</option> <option value="Rock">Rock</option> <option value="Pop">Pop</option> <option value="Hip hop">Hip hop</option> <option value="Electronic">Electronic</option> </select> <label for="instrument" id="instrument-label" style="display: none">Instrument</label> <select id="instrument" name="instrument" style="display: none"> <option value="">Select a instrument</option> <option value="Bass">Bass</option> <option value="Rythm guitar">Rythm guitar</option> <option value="Lead guitar">Lead guitar</option> <option value="Vocal">Vocal</option> </select> <label for="soundcloud">SoundCloud URL</label> <input type="url" id="soundcloud" name="soundcloud"> <label for="password">Password</label> <input type="password" id="password" name="password" required> <label for="location">Location</label> <input type="text" id="location" name="location" required> <label for="login">Login</label> <input type="text" id="login" name="login" required> <label for="thumbnail">Thumbnail</label> <input type="file" id="thumbnail" name="thumbnail"> <button type="submit">Register</button> </form> </main> <script> function showInstrument(role) { const instrumentLabel = document.querySelector('#instrument-label'); const instrumentSelect = document.querySelector('#instrument'); if (role === 'Artist') { instrumentLabel.style.display = 'block'; instrumentSelect.style.display = 'block'; } else { instrumentLabel.style.display = 'none'; instrumentSelect.style.display = 'none'; } } </script> </body> </html> search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action="/search" method="get"> <label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br> <br> <label for="role">Search by role:</label> <select id="role" name="role"> <option value=""> All </option> <option value="Band"> Band </option> <option value="Artist"> Artist </option> </select> <label for="location">Search by location:</label> <input id="location" name="location" type="text" value="<%= location %>"> <br> <!-- Add new input field for location --> <br> <br> <button type="submit">Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <!-- Update the form submission script --> <script> document.querySelector("form").addEventListener("submit", function (event) { event.preventDefault(); const query = document.querySelector("#query").value; const role = document.querySelector("#role").value; const location = document.querySelector("#location").value; const url = "/search?query=" + encodeURIComponent(query) + "&role=" + encodeURIComponent(role) + "&location=" + encodeURIComponent(location); window.location.href = url; }); </script> </body> </html>
2cc9e60de72926abc63a2dea7a8d58bd
{ "intermediate": 0.3411206007003784, "beginner": 0.4774945080280304, "expert": 0.18138492107391357 }
10,882
Мне нужно сделать так, чтоб при регистрации и поиске пользователь мог выбрать подходящий город, регион из json файла cities.json с городами, регионами. его структура такова: [ { "region": "Москва и Московская обл.", "city": "Москва" }, { "region": "Москва и Московская обл.", "city": "Абрамцево" }, { "region": "Москва и Московская обл.", "city": "Алабино" }, { "region": "Москва и Московская обл.", "city": "Апрелевка" }, { "region": "Москва и Московская обл.", "city": "Архангельское" }, { "region": "Москва и Московская обл.", "city": "Ашитково" Сейчас у меня поиск организован по совпадению строк location. Также город, регион должен отображаться в профиле код: app.js: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); const fuzzball = require("fuzzball"); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); /* function normalizeLocationName(userInput) { //const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true }); const bestMatch = matches.sort((a, b) => b.score - a.score)[0]; return bestMatch.score >= 75 ? bestMatch.choice : userInput; } */ const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '', location = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); let results = []; if (query || role || location) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь return nameScore + genreScore + locationScore > 0 && (role === '' || musician.role === role) && (location === '' || locationScore >= 75); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; // Sort by name score, then genre score, then location score (descending) if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) { return 1; } else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) { return -1; } else { return 0; } }); // Remove duplicates results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.location === result.location )) ); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; const location = req.query.location || ''; // Add location variable let musicians = []; if (query || role || location) { musicians = search(query, role, location); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role, location }); //res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); register.ejs: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="/css/main.css" /> <title>Register as a Musician</title> </head> <body> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/register">Register</a></li> <li><a href="/search">Search</a></li> </ul> </nav> </header> <main> <h1>Register as a Musician</h1> <form method="post" enctype="multipart/form-data"> <label for="name">Name</label> <input type="text" id="name" name="name" required> <label for="role">Role</label> <select id="role" name="role" required onchange="showInstrument(this.value)"> <option value="">Select a role</option> <option value="Band">A band</option> <option value="Artist">Artist</option> </select> <label for="genre">Genre</label> <select id="genre" name="genre" required> <option value="">Select a genre</option> <option value="Rock">Rock</option> <option value="Pop">Pop</option> <option value="Hip hop">Hip hop</option> <option value="Electronic">Electronic</option> </select> <label for="instrument" id="instrument-label" style="display: none">Instrument</label> <select id="instrument" name="instrument" style="display: none"> <option value="">Select a instrument</option> <option value="Bass">Bass</option> <option value="Rythm guitar">Rythm guitar</option> <option value="Lead guitar">Lead guitar</option> <option value="Vocal">Vocal</option> </select> <label for="soundcloud">SoundCloud URL</label> <input type="url" id="soundcloud" name="soundcloud"> <label for="password">Password</label> <input type="password" id="password" name="password" required> <label for="location">Location</label> <input type="text" id="location" name="location" required> <label for="login">Login</label> <input type="text" id="login" name="login" required> <label for="thumbnail">Thumbnail</label> <input type="file" id="thumbnail" name="thumbnail"> <button type="submit">Register</button> </form> </main> <script> function showInstrument(role) { const instrumentLabel = document.querySelector('#instrument-label'); const instrumentSelect = document.querySelector('#instrument'); if (role === 'Artist') { instrumentLabel.style.display = 'block'; instrumentSelect.style.display = 'block'; } else { instrumentLabel.style.display = 'none'; instrumentSelect.style.display = 'none'; } } </script> </body> </html> search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action="/search" method="get"> <label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br> <br> <label for="role">Search by role:</label> <select id="role" name="role"> <option value=""> All </option> <option value="Band"> Band </option> <option value="Artist"> Artist </option> </select> <label for="location">Search by location:</label> <input id="location" name="location" type="text" value="<%= location %>"> <br> <!-- Add new input field for location --> <br> <br> <button type="submit">Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <!-- Update the form submission script --> <script> document.querySelector("form").addEventListener("submit", function (event) { event.preventDefault(); const query = document.querySelector("#query").value; const role = document.querySelector("#role").value; const location = document.querySelector("#location").value; const url = "/search?query=" + encodeURIComponent(query) + "&role=" + encodeURIComponent(role) + "&location=" + encodeURIComponent(location); window.location.href = url; }); </script> </body> </html>
015ed627368901f766d1ee65582986f4
{ "intermediate": 0.32417985796928406, "beginner": 0.4703909456729889, "expert": 0.20542922616004944 }
10,883
in colmap, in 3d reconstruction there is a file called images.txt. can you explain that and the format of the content
d501d5de154ca97f46c2066449302543
{ "intermediate": 0.3501341640949249, "beginner": 0.20964404940605164, "expert": 0.44022178649902344 }
10,885
Мне нужно сделать так, чтоб при регистрации и поиске пользователь мог выбрать подходящий город, регион из json файла cities.json с городами, регионами. его структура такова: [ { "region": "Москва и Московская обл.", "city": "Москва" }, { "region": "Москва и Московская обл.", "city": "Абрамцево" }, { "region": "Москва и Московская обл.", "city": "Алабино" }, { "region": "Москва и Московская обл.", "city": "Апрелевка" }, { "region": "Москва и Московская обл.", "city": "Архангельское" }, { "region": "Москва и Московская обл.", "city": "Ашитково" Сейчас у меня поиск организован по совпадению строк location. Также город, регион должен отображаться в профиле код: app.js: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); const fuzzball = require("fuzzball"); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); /* function normalizeLocationName(userInput) { //const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true }); const bestMatch = matches.sort((a, b) => b.score - a.score)[0]; return bestMatch.score >= 75 ? bestMatch.choice : userInput; } */ const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getMusicianById(id) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.find(musician => musician.id === id); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } function search(query = '', role = '', location = '') { const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); let results = []; if (query || role || location) { const lowerQuery = query.toLowerCase(); results = musicians.filter(musician => { const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь return nameScore + genreScore + locationScore > 0 && (role === '' || musician.role === role) && (location === '' || locationScore >= 75); }).sort((a, b) => { const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0; const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0; // Sort by name score, then genre score, then location score (descending) if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) { return 1; } else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) { return -1; } else { return 0; } }); // Remove duplicates results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.location === result.location )) ); } return results; } app.use((req, res, next) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } else { res.locals.userLoggedIn = false; } next(); }); app.get("/", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); res.render("index", { musicians: musicians.musicians }); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register"); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const newMusician = { id: musicians.musicians.length + 1, name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, location: req.body.location, role: req.body.role, login: req.body.login }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + newMusician.id + "_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } musicians.musicians.push(newMusician); fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians)); req.session.musicianId = newMusician.id; res.redirect("/profile/" + newMusician.id); } }); app.get("/profile/:id", (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { res.render("profile", { musician: musician }); } else { res.status(404).send("Musician not found"); } }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password); if (musician) { req.session.musicianId = musician.id; res.redirect("/profile/" + musician.id); } else { res.render("login", { error: "Invalid login or password" }); } }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { const query = req.query.query || ''; const role = req.query.role || ''; const location = req.query.location || ''; // Add location variable let musicians = []; if (query || role || location) { musicians = search(query, role, location); } else { const data = fs.readFileSync('./db/musicians.json'); musicians = JSON.parse(data).musicians.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, location: musician.location }; }); } res.locals.predefinedGenres = predefinedGenres; res.render('search', { musicians, query, role, location }); //res.redirect('/search'); }); app.get("/profile/:id/edit", requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } }); app.post('/profile/:id/edit', requireLogin, (req, res) => { const musician = getMusicianById(parseInt(req.params.id)); if (musician) { if (!req.body.name || !req.body.genre) { res.status(400).send('Please fill out all fields'); } else { musician.name = req.body.name; musician.genre = req.body.genre; musician.instrument = req.body.instrument; musician.soundcloud = req.body.soundcloud; musician.soundcloud1 = req.body.soundcloud1; musician.soundcloud2 = req.body.soundcloud2; musician.location = req.body.location; musician.role = req.body.role; musician.bio = req.body.bio; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = 'musician_' + musician.id + '_' + file.name; file.mv('./public/img/' + filename); musician.thumbnail = filename; } const data = fs.readFileSync('./db/musicians.json'); const musicians = JSON.parse(data); const index = musicians.musicians.findIndex(m => m.id === musician.id); musicians.musicians[index] = musician; fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians)); res.redirect('/profile/' + musician.id); } } else { res.status(404).send('Musician not found'); } }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); register.ejs: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="/css/main.css" /> <title>Register as a Musician</title> </head> <body> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/register">Register</a></li> <li><a href="/search">Search</a></li> </ul> </nav> </header> <main> <h1>Register as a Musician</h1> <form method="post" enctype="multipart/form-data"> <label for="name">Name</label> <input type="text" id="name" name="name" required> <label for="role">Role</label> <select id="role" name="role" required onchange="showInstrument(this.value)"> <option value="">Select a role</option> <option value="Band">A band</option> <option value="Artist">Artist</option> </select> <label for="genre">Genre</label> <select id="genre" name="genre" required> <option value="">Select a genre</option> <option value="Rock">Rock</option> <option value="Pop">Pop</option> <option value="Hip hop">Hip hop</option> <option value="Electronic">Electronic</option> </select> <label for="instrument" id="instrument-label" style="display: none">Instrument</label> <select id="instrument" name="instrument" style="display: none"> <option value="">Select a instrument</option> <option value="Bass">Bass</option> <option value="Rythm guitar">Rythm guitar</option> <option value="Lead guitar">Lead guitar</option> <option value="Vocal">Vocal</option> </select> <label for="soundcloud">SoundCloud URL</label> <input type="url" id="soundcloud" name="soundcloud"> <label for="password">Password</label> <input type="password" id="password" name="password" required> <label for="location">Location</label> <input type="text" id="location" name="location" required> <label for="login">Login</label> <input type="text" id="login" name="login" required> <label for="thumbnail">Thumbnail</label> <input type="file" id="thumbnail" name="thumbnail"> <button type="submit">Register</button> </form> </main> <script> function showInstrument(role) { const instrumentLabel = document.querySelector('#instrument-label'); const instrumentSelect = document.querySelector('#instrument'); if (role === 'Artist') { instrumentLabel.style.display = 'block'; instrumentSelect.style.display = 'block'; } else { instrumentLabel.style.display = 'none'; instrumentSelect.style.display = 'none'; } } </script> </body> </html> search.ejs: <!DOCTYPE html> <html> <head> <title>Search Musicians</title> </head> <body> <h1>Search Musicians</h1> <form action="/search" method="get"> <label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br> <br> <label for="role">Search by role:</label> <select id="role" name="role"> <option value=""> All </option> <option value="Band"> Band </option> <option value="Artist"> Artist </option> </select> <label for="location">Search by location:</label> <input id="location" name="location" type="text" value="<%= location %>"> <br> <!-- Add new input field for location --> <br> <br> <button type="submit">Search</button> </form><%if (musicians.length > 0) { %> <h2>Results:</h2> <ul> <%musicians.forEach(musician => { %> <li> <a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %> </li><%}); %> </ul><%} else if (query || role) { %> <p>No musicians found.</p><%} %> <!-- Update the form submission script --> <script> document.querySelector("form").addEventListener("submit", function (event) { event.preventDefault(); const query = document.querySelector("#query").value; const role = document.querySelector("#role").value; const location = document.querySelector("#location").value; const url = "/search?query=" + encodeURIComponent(query) + "&role=" + encodeURIComponent(role) + "&location=" + encodeURIComponent(location); window.location.href = url; }); </script> </body> </html>
7e3260030f86a9d4177e502be36cd48d
{ "intermediate": 0.32417985796928406, "beginner": 0.4703909456729889, "expert": 0.20542922616004944 }
10,886
基于C8051F410定时器0方式2设计数码管的时钟显示控制程序,要求基于定时器0的中断方式来实现编程。已知定时器0的计数脉冲频率为24.5 MHz /12 (用C语言编程),并将时钟信息通过串口UART发送到主机上。 部分参考代码: #include <c8051f410.h> #include <stdio.h> #include "C8051F410.h" // Peripheral specific initialization functions, // Called from the Init_Device() function void PCA_Init() { PCA0MD &= ~0x40; PCA0MD = 0x00; } void Timer_Init() { TMOD = 0x22; CKCON = 0x08; TL0 = 0x9E; TH0 = 0x38; TH1 = 0x96; } void UART_Init() { SCON0 = 0x10; } void Port_IO_Init() { // P0.0 - Unassigned, Open-Drain, Digital // P0.1 - Unassigned, Open-Drain, Digital // P0.2 - Unassigned, Open-Drain, Digital // P0.3 - Unassigned, Open-Drain, Digital // P0.4 - TX0 (UART0), Push-Pull, Digital // P0.5 - RX0 (UART0), Open-Drain, Digital // P0.6 - Unassigned, Open-Drain, Digital // P0.7 - Unassigned, Open-Drain, Digital // P1.0 - Unassigned, Open-Drain, Digital // P1.1 - Unassigned, Open-Drain, Digital // P1.2 - Unassigned, Open-Drain, Digital // P1.3 - Unassigned, Open-Drain, Digital // P1.4 - Unassigned, Open-Drain, Digital // P1.5 - Unassigned, Open-Drain, Digital // P1.6 - Unassigned, Open-Drain, Digital // P1.7 - Unassigned, Open-Drain, Digital // P2.0 - Unassigned, Open-Drain, Digital // P2.1 - Unassigned, Open-Drain, Digital // P2.2 - Unassigned, Open-Drain, Digital // P2.3 - Unassigned, Open-Drain, Digital // P2.4 - Unassigned, Open-Drain, Digital // P2.5 - Unassigned, Open-Drain, Digital // P2.6 - Unassigned, Open-Drain, Digital // P2.7 - Unassigned, Open-Drain, Digital P0MDOUT = 0x10; XBR0 = 0x01; XBR1 = 0x40; } void Oscillator_Init() { OSCICN = 0x87; } void Interrupts_Init() { IE = 0x80; } // Initialization function for device, // Call Init_Device() from your main program void Init_Device(void) { PCA_Init(); Timer_Init(); UART_Init(); Port_IO_Init(); Oscillator_Init(); Interrupts_Init(); } 请按要求补全
ab15d1f9bf0de9a91e8d9a8b386431a4
{ "intermediate": 0.23881107568740845, "beginner": 0.3670787811279297, "expert": 0.39411014318466187 }
10,887
monorepo là gì, luồng chạy của monorepo
e0c416ce630b2926b59c290044e48209
{ "intermediate": 0.35527047514915466, "beginner": 0.30107393860816956, "expert": 0.343655526638031 }
10,888
请将标题数列'code','name','win-rate','sum-rate','buy:sell','max-loss','hold-day','max-rate',插入到表格results-4-hour.xlsx的首行,用PYTHON
708e28ab965d2664e7dfee7cd355229e
{ "intermediate": 0.2317560315132141, "beginner": 0.29314306378364563, "expert": 0.47510093450546265 }
10,889
import tkinter as tk from tkinter import ttk import pandas as pd import tkinter.messagebox as MessageBox def on_double_click(event): item = tree.selection()[0] value = tree.item(item, 'values')[2] # 获取原表格中的第二列(现在是第一列)的值 MessageBox.showinfo('提醒', f"单元格内容:{value}") def sort_column(treeview, col, reverse): items = [treeview.item(item)['values'] for item in treeview.get_children()] items.sort(key=lambda x: x[col], reverse=reverse) for index, item in enumerate(items): treeview.item(treeview.get_children()[index], values=item) treeview.set(treeview.get_children()[index], column=0, value=index+1) if not reverse: treeview.heading(col, command=lambda _col=col: sort_column(treeview, _col, True)) else: treeview.heading(col, command=lambda _col=col: sort_column(treeview, _col, False)) file_path = 'results-1-day_sorted.xlsx' # 请替换为实际文件路径 df = pd.read_excel(file_path) root = tk.Tk() root.title('Excel内容') # 创建滚动条 scrollbar = tk.Scrollbar(root, orient='vertical') # 创建TreeView并绑定滚动条 tree = ttk.Treeview(root, columns=['#0']+list(df.columns), show='headings', yscrollcommand=scrollbar.set) scrollbar.config(command=tree.yview) # 添加列 tree.column('#0', width=10) # 设置序号列宽度 tree.heading('#0', text='序号') for index, column in enumerate(df.columns): tree.column(index+1, width=100) # 设置每一列的宽度 tree.heading(index+1, text=column, command=lambda _col=index+1: sort_column(tree, _col, False)) # 添加数据行 for index, row in df.iterrows(): tree.insert('', 'end', values=(index+1, *row)) # 添加序号和数据行 tree.bind('<Double-1>', on_double_click) # 双击事件绑定 # 使用place定位Treeview tree.place(x=20, y=200) # 使用place定位滚动条 scrollbar.place(x=20 + tree.winfo_reqwidth(), y=20, height=tree.winfo_reqheight()) root.mainloop() 读取的文件中,只有8列,请修改代码能定义每一列的宽度
46506718d57027eabb5a9651ca7c26cb
{ "intermediate": 0.2638271152973175, "beginner": 0.43900349736213684, "expert": 0.29716935753822327 }
10,890
write a script to form a docker container based on individual user files
4371d9c5ae3611cd0d86054e01c1d2a9
{ "intermediate": 0.42468035221099854, "beginner": 0.2022666335105896, "expert": 0.37305301427841187 }
10,891
import tkinter as tk from tkinter import ttk import pandas as pd import tkinter.messagebox as MessageBox def on_double_click(event): item = tree.selection()[0] value = tree.item(item, 'values')[2] # 获取原表格中的第二列(现在是第一列)的值 MessageBox.showinfo('提醒', f"单元格内容:{value}") def sort_column(treeview, col, reverse): items = [treeview.item(item)['values'] for item in treeview.get_children()] items.sort(key=lambda x: x[col], reverse=reverse) for index, item in enumerate(items): treeview.item(treeview.get_children()[index], values=item) treeview.set(treeview.get_children()[index], column=0, value=index+1) if not reverse: treeview.heading(col, command=lambda _col=col: sort_column(treeview, _col, True)) else: treeview.heading(col, command=lambda _col=col: sort_column(treeview, _col, False)) file_path = 'results-1-day_sorted.xlsx' # 请替换为实际文件路径 df = pd.read_excel(file_path) root = tk.Tk() root.title('Excel内容') # 创建滚动条 scrollbar = tk.Scrollbar(root, orient='vertical') # 创建TreeView并绑定滚动条 tree = ttk.Treeview(root, columns=['#0']+list(df.columns), show='headings', yscrollcommand=scrollbar.set) scrollbar.config(command=tree.yview) # 添加列 tree.column('#0', width=10) # 设置序号列宽度 tree.heading('#0', text='序号') # 设置列宽度的列表 column_widths = [20, 100, 200, 100, 150, 80, 120, 90] for index, column in enumerate(df.columns): tree.column(index, width=column_widths[index]) # 设置每一列的宽度 tree.heading(index+1, text=column, command=lambda _col=index+1: sort_column(tree, _col, False)) # 添加数据行 for index, row in df.iterrows(): tree.insert('', 'end', values=(index+1, *row)) # 添加序号和数据行 tree.bind('<Double-1>', on_double_click) # 双击事件绑定 # 使用place定位Treeview tree.place(x=20, y=200) # 使用place定位滚动条 scrollbar.place(x=20 + tree.winfo_reqwidth(), y=20, height=tree.winfo_reqheight()) root.mainloop()请将此代码修改为,当点击某个按键时才显示表格内容
8def279e492f1a748bf0f64a12fc1604
{ "intermediate": 0.3315071165561676, "beginner": 0.4654379189014435, "expert": 0.2030549794435501 }
10,892
Write restful API code in java11
87e4889e4d9af5c4ff8279a255fe4334
{ "intermediate": 0.6458631157875061, "beginner": 0.2264086753129959, "expert": 0.1277281939983368 }
10,893
I used your code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException from binance.helpers import round_step_size import pandas as pd import json import numpy as np import pytz import datetime as dt import ccxt from decimal import Decimal import requests import hmac import hashlib API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) # Set the endpoint and parameters for the request url = "https://fapi.binance.com/fapi/v2/account" timestamp = int(time.time() * 1000) recv_window = 5000 params = { "timestamp": timestamp, "recvWindow": recv_window } # Sign the message using the Client’s secret key message = '&'.join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params['signature'] = signature leverage = 100 # Send the request using the requests library response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY}) account_info = response.json() # Get the USDT balance and calculate the max trade size based on the leverage usdt_balance = next((item for item in account_info['assets'] if item["asset"] == "USDT"), {"balance": 0}) max_trade_size = float(usdt_balance.get("balance", 0)) * leverage # Get the current time and timestamp now = dt.datetime.now() date = now.strftime("%m/%d/%Y %H:%M:%S") print(date) timestamp = int(time.time() * 1000) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' quantity = 1 symbol = 'BTC/USDT' order_type = 'market' leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True },'future': { 'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc… } }) binance_futures = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True } }) # Load the market symbols try: markets = binance_futures.load_markets() except ccxt.BaseError as e: print(f'Error fetching markets: {e}') markets = [] if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market") # Get server time and time difference def get_server_time(exchange): server_time = exchange.fetch_currencies() return server_time['timestamp'] def get_time_difference(): server_time = get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time return time_difference time.sleep(1) def get_klines(symbol, interval, lookback): url = "https://fapi.binance.com/fapi/v1/klines" end_time = int(time.time() * 1000) # end time is now start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago symbol = symbol.replace("/", "") # remove slash from symbol query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } try: response = requests.get(url + query_params, headers=headers) response.raise_for_status() data = response.json() if not data: # if data is empty, return None print('No data found for the given timeframe and symbol') return None ohlc = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S') ohlc.append({ 'Open time': timestamp, 'Open': float(d[1]), 'High': float(d[2]), 'Low': float(d[3]), 'Close': float(d[4]), 'Volume': float(d[5]) }) df = pd.DataFrame(ohlc) df.set_index('Open time', inplace=True) return df except requests.exceptions.RequestException as e: print(f'Error in get_klines: {e}') return None df = get_klines(symbol, '1m', 89280) def signal_generator(df): if df is None: return "" open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return "" df = get_klines(symbol, '1m', 89280) def order_execution(symbol, signal, step_size, leverage, order_type): # Close any existing positions current_position = None positions = binance_futures.fapiPrivateGetPositionRisk() for position in positions: if position["symbol"] == symbol: current_position = position if current_position is not None and current_position["positionAmt"] != 0: binance_futures.fapiPrivatePostOrder( symbol=symbol, side='SELL' if current_position["positionSide"] == "LONG" else 'BUY', type='MARKET', quantity=abs(float(current_position["positionAmt"])), positionSide=current_position["positionSide"], reduceOnly=True ) time.sleep(1) # Calculate appropriate order quantity and price based on signal opposite_position = None quantity = step_size position_side = None #initialise to None price = None # Set default take profit price take_profit_price = None stop_loss_price = None if signal == 'buy': position_side = 'BOTH' opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None order_type = 'TAKE_PROFIT_MARKET' ticker = binance_futures.fetch_ticker(symbol) price = 0 # default price if 'askPrice' in ticker: price = ticker['askPrice'] # perform rounding and other operations on price else: # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.) take_profit_percentage = TAKE_PROFIT_PERCENTAGE stop_loss_percentage = STOP_LOSS_PERCENTAGE elif signal == 'sell': position_side = 'BOTH' opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None order_type = 'STOP_MARKET' ticker = binance_futures.fetch_ticker(symbol) price = 0 # default price if 'askPrice' in ticker: price = ticker['askPrice'] # perform rounding and other operations on price else: # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.) take_profit_percentage = TAKE_PROFIT_PERCENTAGE stop_loss_percentage = STOP_LOSS_PERCENTAGE # Set stop loss price stop_loss_price = None if price is not None: try: price = round_step_size(price, step_size=step_size) if signal == 'buy': # Calculate take profit and stop loss prices for a buy signal take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size) stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size) elif signal == 'sell': # Calculate take profit and stop loss prices for a sell signal take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size) stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size) except Exception as e: print(f"Error rounding price: {e}") # Reduce quantity if opposite position exists if opposite_position is not None: if abs(opposite_position['positionAmt']) < quantity: quantity = abs(opposite_position['positionAmt']) # Update position_side based on opposite_position and current_position if opposite_position is not None: position_side = opposite_position['positionSide'] elif current_position is not None: position_side = current_position['positionSide'] # Place stop market order if order_type == 'STOP_MARKET': try: response = binance_futures.fapiPrivatePostOrder( symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type='STOP_MARKET', quantity=quantity, stopPrice=stop_loss_price, reduceOnly=True ) print(f"Order details: {response}") except BinanceAPIException as e: print(f"Error in order_execution: {e}") time.sleep(1) return # Place market or take profit order elif order_type == 'market': try: response = binance_futures.create_order( symbol=symbol, type=order_type, side='BUY' if signal == 'buy' else 'SELL', amount=quantity, price=price ) print(f"Order details: {response}") except BinanceAPIException as e: print(f"Error in order_execution: {e}") time.sleep(1) return signal = signal_generator(df) while True: df = get_klines(symbol, '1m', 89280) # await the coroutine function here if df is not None: signal = signal_generator(df) if signal is not None: print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}") if signal: order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type) time.sleep(0.1) But I getting ERROR: The signal time is: 2023-06-08 10:54:02 :sell Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 295, in <module> order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type) File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 258, in order_execution response = binance_futures.fapiPrivatePostOrder( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Entry.__init__.<locals>.unbound_method() got an unexpected keyword argument 'symbol'
f18621d3ad48cb8ea7cfedc01c137b8c
{ "intermediate": 0.3864240050315857, "beginner": 0.44241565465927124, "expert": 0.17116032540798187 }
10,894
解释下 c++ ref:namespaces
1e0a843a2f163e1f0c00e693a31efa63
{ "intermediate": 0.37877893447875977, "beginner": 0.3254314064979553, "expert": 0.2957896590232849 }
10,895
could you make me a code for my google chrome console for my discord app client that will always make it look like im typing? (in javascript)
bd688ece8539aa7bd2d70f80f62be44e
{ "intermediate": 0.610943615436554, "beginner": 0.2277776449918747, "expert": 0.16127879917621613 }
10,896
hello, what is your version?
422ad18f9c2cac68dd36846406d65560
{ "intermediate": 0.3726518154144287, "beginner": 0.2823634743690491, "expert": 0.3449847400188446 }
10,897
http method allow
94906b0545cbfaab843895a8c554b767
{ "intermediate": 0.31790536642074585, "beginner": 0.28514090180397034, "expert": 0.3969537317752838 }
10,898
I need PHP function that can check containing in plain text URLs or domain names
15d23d4094fab754bfcf88b227ce9654
{ "intermediate": 0.6319407820701599, "beginner": 0.23075000941753387, "expert": 0.1373092234134674 }
10,899
please write a website,to input the qc check to the sql server
4cec152e6c4261cb1b1cd59b47b5a6bf
{ "intermediate": 0.3308955132961273, "beginner": 0.24269187450408936, "expert": 0.4264126121997833 }
10,900
do you know anything about react-tag-input-component ?
b18ec7ebcb8d01d4c442809448d5a36a
{ "intermediate": 0.36650413274765015, "beginner": 0.21738314628601074, "expert": 0.41611266136169434 }
10,901
проверь запрос на ошибки (этот запрос собирает view) SELECT e."PersonnelNumber" AS "UserPersNumber", e."Title" AS "UserTitle", e."IsActive" AS "UserIsActive", p."Title" AS "UserPosition", e."WorkStartDate" AS "UserWorkStartDate", f."Title" AS "UserMainDepartment", ed."Title" AS "UserDepartment", r."PersonnelNumber" AS "ResponsiblePersNumber", r."Title" AS "ResponsibleTitle", r."IsActive" AS "ResponsibleIsActive", gs."Title" AS "GoalSeason", g."Id" AS "GoalFormId", g."IsDeleted" AS "GoalFormIsDeleted", g."Modified" AS "GoalFormModificationDate", um."Title" AS "GoalFormModificationBy", g."StartDate" AS "GoalFormStartDate", g."Created" AS "GoalFormCreatDate", ws."Title" AS "GoalFormStage", CASE g."IsCurrent" WHEN true THEN 'Текущая'::text ELSE 'Предыдущая'::text END AS "GoalFormType", g."TotalUserResult", g."TotalResponsibleResult", gr."Title" AS "GoalFormRating", COALESCE(wsipr."Title", 'Не заполнено'::citext) AS "IPRStage", gg."Id" AS "GoalId", CASE gg."GoalTypeId" WHEN 1 THEN '0'::text ELSE '1'::text END AS "GoalToLower", gg."Title" AS "GoalTitle", gg."Description" AS "GoalDescription", gg."Weight" AS "GoalWeight", gg."TargetValue" AS "GoalTargetValue", gg."UserFactValue" AS "GoalUserFactValue", gg."ResponsibleFactValue" AS "GoalResponsibleFactValue", uu."Title" AS "GoalUnitTitle", gg."UserResult", -- MFNEON-267 p1 gg."ResponsibleResult", -- MFNEON-267 p1 gg."CreatedById" AS "CreatedPersNumber" -- MFNEON-267 p2 FROM "Users" e JOIN "GMGoalForms" g ON g."UserId" = e."Id" LEFT JOIN "Positions" p ON p."Id" = g."UserPositionId" LEFT JOIN "Users" r ON r."Id" = g."ResponsibleId" JOIN "Users" um ON um."Id" = g."ModifiedById" JOIN "Departments" ed ON ed."Id" = g."UserDepartmentId" JOIN "Departments" f ON f."Id" = g."MainDepartmentId" JOIN "States" ws ON ws."Id" = g."StateId" JOIN "GMSeasons" gs ON gs."Id" = g."SeasonId" LEFT JOIN "GMRatings" gr ON gr."Id" = g."RatingId" LEFT JOIN "States" wsipr ON wsipr."Id" = g."IdpStatusId" LEFT JOIN "GMGoals" gg ON gg."GoalFormId" = g."Id" LEFT JOIN "Units" uu ON uu."Id" = gg."UnitId" WHERE gg."IsDeleted" IS NULL OR gg."IsDeleted" = false;
0a57d147e62e39dc04685b641f583c93
{ "intermediate": 0.2686011791229248, "beginner": 0.49602198600769043, "expert": 0.23537679016590118 }
10,902
Create a pygame programm to deisplay "Hello world ont a 600*800 screen"
bbbf98bbf1f8c597d2bff5d487c3c113
{ "intermediate": 0.35709917545318604, "beginner": 0.25362715125083923, "expert": 0.38927361369132996 }
10,903
model = Sequential() model.add(LSTM(64, input_shape=(lookback, 7))) model.add(Dense(32, activation='relu')) model.add(Dense(7, activation='sigmoid')) model.compile(loss='mean_squared_error', optimizer='adam') #训练模型 model.fit(train_X, train_Y, batch_size=batch_size, epochs=epochs, validation_data=(test_X, test_Y)) #预测下一期双色球 last_data = data[['red1', 'red2', 'red3', 'red4', 'red5', 'red6', 'blue']].tail(lookback) last_data = (last_data - 1) / np.array([33, 33, 33, 33, 33, 33, 16]) last_data = np.array(last_data) last_data = np.reshape(last_data, (1, lookback, 7)) prediction = model.predict(last_data) prediction = np.round(prediction * np.array([33, 33, 33, 33, 33, 33, 16]) + np.array([1, 1, 1, 1, 1, 1, 1])) 逐行解释上面的代码
73a7b381458ceeee63872eeb23769459
{ "intermediate": 0.2983711063861847, "beginner": 0.18827205896377563, "expert": 0.5133568048477173 }
10,904
ssh-keygen
596cb0a575d7360045630e4f8ab0475c
{ "intermediate": 0.26779666543006897, "beginner": 0.24531282484531403, "expert": 0.4868904650211334 }
10,905
required for `std::option::Option<sea_orm_active_enums::Type>` to implement `Deserialize<'_>` 如何解决
579c4491fa06750f5e6b03a63dc8b921
{ "intermediate": 0.42980870604515076, "beginner": 0.267411470413208, "expert": 0.30277982354164124 }
10,906
以下代码存在数组越界的可能吗?\n#include<stdio.h>\\n\nint main()\\n\n{\\n\n long long n,i;\\n\n int m,o,k,q;\\n\n while(scanf("%lld %d",&n,&m)!=EOF){\\n\n long long sum=0;\\n\n long long a[n];\\n\n for(i=0;i<n;i++)\\n\n a[i]=i+1;\\n\n k=0;q=0;\\n\n for(i=0;i<n;){\\n\n o=1;\\n\n while(o<m){\\n\n while(a[k]==0)k=(k+1)%n;\\n\n o++;\\n\n k=(k+1)%n;\\n\n }\\n\n while(a[k]==0)k=(k+1)%n;\\n\n a[k]=0;i++;\\n\n if(i==n-1)while(q==0){\\n\n if(a[k]==0)k=(k+1)%n;\\n\n if(a[k]!=0){\\n\n printf("%lld\n",a[k]);\\n\n q=1;\\n\n } \\n\n }\\n\n }\\n\n }\\n\n}
5211c563cdd63c3e10a7e3a4244737be
{ "intermediate": 0.33076685667037964, "beginner": 0.4318382441997528, "expert": 0.23739488422870636 }
10,907
I used your code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException from binance.helpers import round_step_size import pandas as pd import json import numpy as np import pytz import datetime as dt import ccxt from decimal import Decimal import requests import hmac import hashlib API_KEY = ‘’ API_SECRET = ‘’ client = Client(API_KEY, API_SECRET) # Set the endpoint and parameters for the request url = “https://fapi.binance.com/fapi/v2/account” timestamp = int(time.time() * 1000) recv_window = 5000 params = { “timestamp”: timestamp, “recvWindow”: recv_window } # Sign the message using the Client’s secret key message = ‘&’.join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params[‘signature’] = signature leverage = 100 # Send the request using the requests library response = requests.get(url, params=params, headers={‘X-MBX-APIKEY’: API_KEY}) account_info = response.json() # Get the USDT balance and calculate the max trade size based on the leverage usdt_balance = next((item for item in account_info[‘assets’] if item[“asset”] == “USDT”), {“balance”: 0}) max_trade_size = float(usdt_balance.get(“balance”, 0)) * leverage # Get the current time and timestamp now = dt.datetime.now() date = now.strftime(“%m/%d/%Y %H:%M:%S”) print(date) timestamp = int(time.time() * 1000) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = ‘SELL’ POSITION_SIDE_LONG = ‘BUY’ quantity = 1 symbol = ‘BTC/USDT’ order_type = ‘market’ leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ ‘apiKey’: API_KEY, ‘secret’: API_SECRET, ‘enableRateLimit’: True, # enable rate limitation ‘options’: { ‘defaultType’: ‘future’, ‘adjustForTimeDifference’: True },‘future’: { ‘sideEffectType’: ‘MARGIN_BUY’, # MARGIN_BUY, AUTO_REPAY, etc… } }) binance_futures = ccxt.binance({ ‘apiKey’: API_KEY, ‘secret’: API_SECRET, ‘enableRateLimit’: True, # enable rate limitation ‘options’: { ‘defaultType’: ‘future’, ‘adjustForTimeDifference’: True } }) # Load the market symbols try: markets = binance_futures.load_markets() except ccxt.BaseError as e: print(f’Error fetching markets: {e}‘) markets = [] if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market") # Get server time and time difference def get_server_time(exchange): server_time = exchange.fetch_currencies() return server_time[‘timestamp’] def get_time_difference(): server_time = get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time return time_difference time.sleep(1) def get_klines(symbol, interval, lookback): url = “https://fapi.binance.com/fapi/v1/klines” end_time = int(time.time() * 1000) # end time is now start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago symbol = symbol.replace(“/”, “”) # remove slash from symbol query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}" headers = { ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36’ } try: response = requests.get(url + query_params, headers=headers) response.raise_for_status() data = response.json() if not data: # if data is empty, return None print(‘No data found for the given timeframe and symbol’) return None ohlc = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime(’%Y-%m-%d %H:%M:%S’) ohlc.append({ ‘Open time’: timestamp, ‘Open’: float(d[1]), ‘High’: float(d[2]), ‘Low’: float(d[3]), ‘Close’: float(d[4]), ‘Volume’: float(d[5]) }) df = pd.DataFrame(ohlc) df.set_index(‘Open time’, inplace=True) return df except requests.exceptions.RequestException as e: print(f’Error in get_klines: {e}‘) return None df = get_klines(symbol, ‘1m’, 89280) def signal_generator(df): if df is None: return “” open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return ‘sell’ # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return ‘buy’ # No clear pattern else: return “” df = get_klines(symbol, ‘1m’, 89280) def order_execution(symbol, signal, step_size, leverage, order_type): # Close any existing positions current_position = None positions = binance_futures.fapiPrivateGetPositionRisk() for position in positions: if position[“symbol”] == symbol: current_position = position if current_position is not None and current_position[“positionAmt”] != 0: binance_futures.fapiPrivatePostOrder( symbol=symbol, side=‘SELL’ if current_position[“positionSide”] == “LONG” else ‘BUY’, type=‘MARKET’, quantity=abs(float(current_position[“positionAmt”])), positionSide=current_position[“positionSide”], reduceOnly=True ) time.sleep(1) # Calculate appropriate order quantity and price based on signal opposite_position = None quantity = step_size position_side = None #initialise to None price = None # Set default take profit price take_profit_price = None stop_loss_price = None if signal == ‘buy’: position_side = ‘BOTH’ opposite_position = current_position if current_position and current_position[‘positionSide’] == ‘SHORT’ else None order_type = ‘TAKE_PROFIT_MARKET’ ticker = binance_futures.fetch_ticker(symbol) price = 0 # default price if ‘askPrice’ in ticker: price = ticker[‘askPrice’] # perform rounding and other operations on price else: # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.) take_profit_percentage = TAKE_PROFIT_PERCENTAGE stop_loss_percentage = STOP_LOSS_PERCENTAGE elif signal == ‘sell’: position_side = ‘BOTH’ opposite_position = current_position if current_position and current_position[‘positionSide’] == ‘LONG’ else None order_type = ‘STOP_MARKET’ ticker = binance_futures.fetch_ticker(symbol) price = 0 # default price if ‘askPrice’ in ticker: price = ticker[‘askPrice’] # perform rounding and other operations on price else: # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.) take_profit_percentage = TAKE_PROFIT_PERCENTAGE stop_loss_percentage = STOP_LOSS_PERCENTAGE # Set stop loss price stop_loss_price = None if price is not None: try: price = round_step_size(price, step_size=step_size) if signal == ‘buy’: # Calculate take profit and stop loss prices for a buy signal take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size) stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size) elif signal == ‘sell’: # Calculate take profit and stop loss prices for a sell signal take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size) stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size) except Exception as e: print(f"Error rounding price: {e}“) # Reduce quantity if opposite position exists if opposite_position is not None: if abs(opposite_position[‘positionAmt’]) < quantity: quantity = abs(opposite_position[‘positionAmt’]) # Update position_side based on opposite_position and current_position if opposite_position is not None: position_side = opposite_position[‘positionSide’] elif current_position is not None: position_side = current_position[‘positionSide’] # Place stop market order if order_type == ‘STOP_MARKET’: try: response = binance_futures.fapiPrivatePostOrder( symbol=symbol, side=‘BUY’ if signal == ‘buy’ else ‘SELL’, type=‘STOP_MARKET’, quantity=quantity, stopPrice=stop_loss_price, reduceOnly=True ) print(f"Order details: {response}”) except BinanceAPIException as e: print(f"Error in order_execution: {e}“) time.sleep(1) return # Place market or take profit order elif order_type == ‘market’: try: response = binance_futures.create_order( symbol=symbol, type=order_type, side=‘BUY’ if signal == ‘buy’ else ‘SELL’, amount=quantity, price=price ) print(f"Order details: {response}”) except BinanceAPIException as e: print(f"Error in order_execution: {e}") time.sleep(1) return signal = signal_generator(df) while True: df = get_klines(symbol, ‘1m’, 89280) # await the coroutine function here if df is not None: signal = signal_generator(df) if signal is not None: print(f"The signal time is: {dt.datetime.now().strftime(’%Y-%m-%d %H:%M:%S’)} :{signal}") if signal: order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type) time.sleep(0.1) But I getting ERROR: The signal time is: 2023-06-08 10:54:02 :sell Traceback (most recent call last): File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 295, in <module> order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type) File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 258, in order_execution response = binance_futures.fapiPrivatePostOrder( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Entry.init.<locals>.unbound_method() got an unexpected keyword argument ‘symbol’
d757bacf2a2c9fe5510310d01ad5c6dd
{ "intermediate": 0.3441945016384125, "beginner": 0.44707709550857544, "expert": 0.20872844755649567 }
10,908
what does command "repo init" mean
6a291925e23083dd1d292052d78e2134
{ "intermediate": 0.5466858744621277, "beginner": 0.21085108816623688, "expert": 0.24246300756931305 }
10,909
Make a C program that receives as input the string "IM FEARLESS" and all it has to do is to reorder the letters until the output string is "LE SSERAFIM".
4cf8ad64bbfa3e7c9b2154fcf92ea40d
{ "intermediate": 0.29394838213920593, "beginner": 0.20361049473285675, "expert": 0.5024410486221313 }
10,910
I used your code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException from binance.helpers import round_step_size import pandas as pd import json import numpy as np import pytz import datetime as dt import ccxt from decimal import Decimal import requests import hmac import hashlib API_KEY = ‘’ API_SECRET = ‘’ client = Client(API_KEY, API_SECRET) # Set the endpoint and parameters for the request url = “https://fapi.binance.com/fapi/v2/account” timestamp = int(time.time() * 1000) recv_window = 5000 params = { “timestamp”: timestamp, “recvWindow”: recv_window } # Sign the message using the Client’s secret key message = ‘&’.join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params[‘signature’] = signature leverage = 100 # Send the request using the requests library response = requests.get(url, params=params, headers={‘X-MBX-APIKEY’: API_KEY}) account_info = response.json() # Get the USDT balance and calculate the max trade size based on the leverage usdt_balance = next((item for item in account_info[‘assets’] if item[“asset”] == “USDT”), {“balance”: 0}) max_trade_size = float(usdt_balance.get(“balance”, 0)) * leverage # Get the current time and timestamp now = dt.datetime.now() date = now.strftime(“%m/%d/%Y %H:%M:%S”) print(date) timestamp = int(time.time() * 1000) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = ‘SELL’ POSITION_SIDE_LONG = ‘BUY’ quantity = 1 symbol = ‘BTC/USDT’ order_type = ‘market’ leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ ‘apiKey’: API_KEY, ‘secret’: API_SECRET, ‘enableRateLimit’: True, # enable rate limitation ‘options’: { ‘defaultType’: ‘future’, ‘adjustForTimeDifference’: True },‘future’: { ‘sideEffectType’: ‘MARGIN_BUY’, # MARGIN_BUY, AUTO_REPAY, etc… } }) binance_futures = ccxt.binance({ ‘apiKey’: API_KEY, ‘secret’: API_SECRET, ‘enableRateLimit’: True, # enable rate limitation ‘options’: { ‘defaultType’: ‘future’, ‘adjustForTimeDifference’: True } }) # Load the market symbols try: markets = binance_futures.load_markets() except ccxt.BaseError as e: print(f’Error fetching markets: {e}‘) markets = [] if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market") # Get server time and time difference def get_server_time(exchange): server_time = exchange.fetch_currencies() return server_time[‘timestamp’] def get_time_difference(): server_time = get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time return time_difference time.sleep(1) def get_klines(symbol, interval, lookback): url = “https://fapi.binance.com/fapi/v1/klines” end_time = int(time.time() * 1000) # end time is now start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago symbol = symbol.replace(“/”, “”) # remove slash from symbol query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}" headers = { ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36’ } try: response = requests.get(url + query_params, headers=headers) response.raise_for_status() data = response.json() if not data: # if data is empty, return None print(‘No data found for the given timeframe and symbol’) return None ohlc = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime(’%Y-%m-%d %H:%M:%S’) ohlc.append({ ‘Open time’: timestamp, ‘Open’: float(d[1]), ‘High’: float(d[2]), ‘Low’: float(d[3]), ‘Close’: float(d[4]), ‘Volume’: float(d[5]) }) df = pd.DataFrame(ohlc) df.set_index(‘Open time’, inplace=True) return df except requests.exceptions.RequestException as e: print(f’Error in get_klines: {e}‘) return None df = get_klines(symbol, ‘1m’, 89280) def signal_generator(df): if df is None: return “” open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return ‘sell’ # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return ‘buy’ # No clear pattern else: return “” df = get_klines(symbol, ‘1m’, 89280) def order_execution(symbol, signal, step_size, leverage, order_type): # Close any existing positions current_position = None positions = binance_futures.fapiPrivateGetPositionRisk() for position in positions: if position[“symbol”] == symbol: current_position = position if current_position is not None and current_position[“positionAmt”] != 0: binance_futures.fapiPrivatePostOrder( symbol=symbol, side=‘SELL’ if current_position[“positionSide”] == “LONG” else ‘BUY’, type=‘MARKET’, quantity=abs(float(current_position[“positionAmt”])), positionSide=current_position[“positionSide”], reduceOnly=True ) time.sleep(1) # Calculate appropriate order quantity and price based on signal opposite_position = None quantity = step_size position_side = None #initialise to None price = None # Set default take profit price take_profit_price = None stop_loss_price = None if signal == ‘buy’: position_side = ‘BOTH’ opposite_position = current_position if current_position and current_position[‘positionSide’] == ‘SHORT’ else None order_type = ‘TAKE_PROFIT_MARKET’ ticker = binance_futures.fetch_ticker(symbol) price = 0 # default price if ‘askPrice’ in ticker: price = ticker[‘askPrice’] # perform rounding and other operations on price else: # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.) take_profit_percentage = TAKE_PROFIT_PERCENTAGE stop_loss_percentage = STOP_LOSS_PERCENTAGE elif signal == ‘sell’: position_side = ‘BOTH’ opposite_position = current_position if current_position and current_position[‘positionSide’] == ‘LONG’ else None order_type = ‘STOP_MARKET’ ticker = binance_futures.fetch_ticker(symbol) price = 0 # default price if ‘askPrice’ in ticker: price = ticker[‘askPrice’] # perform rounding and other operations on price else: # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.) take_profit_percentage = TAKE_PROFIT_PERCENTAGE stop_loss_percentage = STOP_LOSS_PERCENTAGE # Set stop loss price stop_loss_price = None if price is not None: try: price = round_step_size(price, step_size=step_size) if signal == ‘buy’: # Calculate take profit and stop loss prices for a buy signal take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size) stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size) elif signal == ‘sell’: # Calculate take profit and stop loss prices for a sell signal take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size) stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size) except Exception as e: print(f"Error rounding price: {e}“) # Reduce quantity if opposite position exists if opposite_position is not None: if abs(opposite_position[‘positionAmt’]) < quantity: quantity = abs(opposite_position[‘positionAmt’]) # Update position_side based on opposite_position and current_position if opposite_position is not None: position_side = opposite_position[‘positionSide’] elif current_position is not None: position_side = current_position[‘positionSide’] # Place stop market order if order_type == ‘STOP_MARKET’: try: response = binance_futures.fapiPrivatePostOrder( symbol=symbol, side=‘BUY’ if signal == ‘buy’ else ‘SELL’, type=‘STOP_MARKET’, quantity=quantity, stopPrice=stop_loss_price, reduceOnly=True ) print(f"Order details: {response}”) except BinanceAPIException as e: print(f"Error in order_execution: {e}“) time.sleep(1) return # Place market or take profit order elif order_type == ‘market’: try: response = binance_futures.create_order( symbol=symbol, type=order_type, side=‘BUY’ if signal == ‘buy’ else ‘SELL’, amount=quantity, price=price ) print(f"Order details: {response}”) except BinanceAPIException as e: print(f"Error in order_execution: {e}") time.sleep(1) return signal = signal_generator(df) while True: df = get_klines(symbol, ‘1m’, 89280) # await the coroutine function here if df is not None: signal = signal_generator(df) if signal is not None: print(f"The signal time is: {dt.datetime.now().strftime(’%Y-%m-%d %H:%M:%S’)} :{signal}") if signal: order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type) time.sleep(0.1) But I getting ERROR: The signal time is: 2023-06-08 10:54:02 :sell Traceback (most recent call last): File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 295, in <module> order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type) File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 258, in order_execution response = binance_futures.fapiPrivatePostOrder( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Entry.init.<locals>.unbound_method() got an unexpected keyword argument ‘symbol’
8b2c0f9d71aab5e71b333336dbefb450
{ "intermediate": 0.3441945016384125, "beginner": 0.44707709550857544, "expert": 0.20872844755649567 }
10,911
How can I automatically create a custom collections in my steam library with an arch linux script?
25628be068c47e947e095140d685347d
{ "intermediate": 0.6938666701316833, "beginner": 0.11258480697870255, "expert": 0.19354857504367828 }
10,912
请修改以下代码,把results-1-day_sorted.xlsx放到show_table函数里读取import tkinter as tk from tkinter import ttk import pandas as pd import tkinter.messagebox as MessageBox def on_double_click(event): item = tree.selection()[0] value = tree.item(item, 'values')[2] # 获取原表格中的第二列(现在是第一列)的值 MessageBox.showinfo('提醒', f"单元格内容:{value}") def sort_column(treeview, col, reverse): items = [treeview.item(item)['values'] for item in treeview.get_children()] items.sort(key=lambda x: x[col], reverse=reverse) for index, item in enumerate(items): treeview.item(treeview.get_children()[index], values=item) treeview.set(treeview.get_children()[index], column=0, value=index+1) if not reverse: treeview.heading(col, command=lambda _col=col: sort_column(treeview, _col, True)) else: treeview.heading(col, command=lambda _col=col: sort_column(treeview, _col, False)) def show_table(df): # 添加数据行 for index, row in df.iterrows(): tree.insert('', 'end', values=(index+1, *row)) # 添加序号和数据行 file_path = 'results-1-day_sorted.xlsx' # 请替换为实际文件路径 df = pd.read_excel(file_path) root = tk.Tk() root.title('Excel内容') # 创建滚动条 scrollbar = tk.Scrollbar(root, orient='vertical') # 创建TreeView并绑定滚动条 tree = ttk.Treeview(root, columns=['#0']+list(df.columns), show='headings', yscrollcommand=scrollbar.set) scrollbar.config(command=tree.yview) # 添加列 tree.column('#0', width=10) # 设置序号列宽度 tree.heading('#0', text='序号') # 设置列宽度的列表 column_widths = [20, 100, 200, 100, 150, 80, 120, 90] for index, column in enumerate(df.columns): tree.column(index, width=column_widths[index]) # 设置每一列的宽度 tree.heading(index+1, text=column, command=lambda _col=index+1: sort_column(tree, _col, False)) tree.bind('<Double-1>', on_double_click) # 双击事件绑定 # 使用place定位Treeview tree.place(x=20, y=200) # 使用place定位滚动条 scrollbar.place(x=20 + tree.winfo_reqwidth(), y=20, height=tree.winfo_reqheight()) # 创建显示按钮并绑定 show_table 函数 show_button = tk.Button(root, text='显示表格', command=lambda: show_table(df)) show_button.place(x=20, y=20) root.mainloop()
ac749127590d197ef703ed649b5f6508
{ "intermediate": 0.2593870759010315, "beginner": 0.5138655304908752, "expert": 0.22674740850925446 }
10,913
Hi
aca150ec23848f44acfd564346c2986c
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
10,914
How to find extended partition in linux
f6049bf33d8f14c607f5bca032403f3c
{ "intermediate": 0.21277573704719543, "beginner": 0.18305931985378265, "expert": 0.6041648983955383 }
10,915
please write python color picker app for macos
3327aa72d8fadc25021e1893dbf1d417
{ "intermediate": 0.4452783763408661, "beginner": 0.1380201131105423, "expert": 0.4167015254497528 }
10,916
you are an data analyste expert since 20 years. You have measurements of thickness, with 49 pts per wafers, you actually follow the mean and the uniformity calculated by unif = (std/mean*100). there is other calculation to follow the uniformity stability You need to monitor thichness deposition by following the resmap measurement on each matérial for a deposition tool on wafer. Make a plan of what you need to put in place in order to have a good monitoring and stable process Who many points of thickness measurement do you think we need, and which method to put in place to follow the thickness deposited across the all wafer, variability across the wafer, ... make an example for 200mm wafers, on a SPC, you will precicely defined without asking "determine" or "specify" first the measurement protocol and after list all parameters you will follow on spc with this a change of uniformity will change the mean, is it safe to process like this ? Or do we need to decorolate mean value on center vs uniformity across the all wafer ?
56bd88e61bf632b5dce2e6699477319f
{ "intermediate": 0.4071717858314514, "beginner": 0.3154417872428894, "expert": 0.2773863971233368 }
10,917
Please correct this code it is giving error: Error: --------------------------------------------------------------------------- NotFittedError Traceback (most recent call last) <ipython-input-12-191d51d54b2c> in <cell line: 3>() 1 # Evaluate the model 2 scaler = MinMaxScaler(feature_range=(0, 1)) ----> 3 mae, mse = evaluate_model(model, X_test, y_test, scaler) 4 print(f"Mean Absolute Error: {mae}") 5 print(f"Mean Squared Error: {mse}") 2 frames /usr/local/lib/python3.10/dist-packages/sklearn/utils/validation.py in check_is_fitted(estimator, attributes, msg, all_or_any) 1388 1389 if not fitted: -> 1390 raise NotFittedError(msg % {"name": type(estimator).__name__}) 1391 1392 NotFittedError: This MinMaxScaler instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator. Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import yfinance as yf from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout def calculate_atr(data, period): data['h-l'] = data['high'] - data['low'] data['h-pc'] = abs(data['high'] - data['close'].shift(1)) data['l-pc'] = abs(data['low'] - data['close'].shift(1)) data['tr'] = data[['h-l', 'h-pc', 'l-pc']].max(axis=1) data['atr'] = data['tr'].rolling(window=period).mean() return data def calculate_super_trend(data, period, multiplier): data = calculate_atr(data, period) data['Upper Basic'] = (data['high'] + data['low']) / 2 + multiplier * data['atr'] data['Lower Basic'] = (data['high'] + data['low']) / 2 - multiplier * data['atr'] data['Upper Band'] = data.apply(lambda x: x['Upper Basic'] if x['close'] > x['Upper Basic'] else x['Lower Basic'], axis=1) data['Lower Band'] = data.apply(lambda x: x['Lower Basic'] if x['close'] < x['Lower Basic'] else x['Upper Basic'], axis=1) data['Super Trend'] = np.where(data['close'] > data['Upper Band'], data['Lower Band'], data['Upper Band']) return data.dropna() def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3): stock_data = yf.download(ticker, start=start_date, end=end_date) print("Original columns:", stock_data.columns) stock_data.columns = [col.lower() for col in stock_data.columns] stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier) columns_to_use = stock_data_with_super_trend[['open', 'high', 'low', 'close', 'Super Trend']].values scaler = MinMaxScaler(feature_range=(0, 1)) data_normalized = scaler.fit_transform(columns_to_use) X, y = [], [] for i in range(window_size, len(data_normalized)): X.append(data_normalized[i - window_size:i]) y.append(data_normalized[i, 3]) # Use Close prices directly as labels train_len = int(0.8 * len(X)) X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len]) X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:]) return X_train, y_train, X_test, y_test def create_lstm_model(input_shape): model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape)) model.add(LSTM(units=50, return_sequences=True)) model.add(LSTM(units=50)) model.add(Dense(units=1)) model.compile(optimizer='adam', loss='mean_squared_error') return model def train_model(model, X_train, y_train, batch_size, epochs): history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1) return model, history def evaluate_model(model, X_test, y_test, scaler): y_pred = model.predict(X_test) y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1] mae = np.mean(np.abs(y_pred_inverse - y_test_inverse)) mse = np.mean(np.square(y_pred_inverse - y_test_inverse)) return mae, mse def plot_prediction(model, X_test, y_test, scaler): y_pred = model.predict(X_test) y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1] plt.figure(figsize=(14, 6)) plt.plot(y_test_inverse, label='Actual') plt.plot(y_pred_inverse, label='Predicted') plt.xlabel('Days') plt.ylabel('Close Price') plt.title('Stock Price Prediction (Actual vs Predicted)') plt.legend() plt.show() # Define the parameters ticker = '^NSEI' # Ticker symbol for Nifty start_date = '2010-01-01' end_date = '2023-06-01' window_size = 40 # Number of previous days' data to consider period = 14 # ATR period multiplier = 3 # ATR multiplier batch_size = 32 epochs = 100 X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size, period, multiplier) # Create the LSTM model input_shape = (X_train.shape[1], X_train.shape[2]) model = create_lstm_model(input_shape) # Train the model model, history = train_model(model, X_train, y_train, batch_size, epochs) # Evaluate the model scaler = MinMaxScaler(feature_range=(0, 1)) mae, mse = evaluate_model(model, X_test, y_test, scaler) print(f"Mean Absolute Error: {mae}") print(f"Mean Squared Error: {mse}") # Plot the predictions plot_prediction(model, X_test, y_test, scaler)
a0cf883fd3ba242e5d6683a5c5fb4430
{ "intermediate": 0.4810159206390381, "beginner": 0.31034332513809204, "expert": 0.20864072442054749 }
10,918
import numpy as np import matplotlib.pyplot as plt from shapely.geometry import Polygon, Point from itertools import groupby import datetime INF_TIME = 100000000000 class Grid: def __init__(self, width, height, obstacles=None): self.grid = None self.width = width self.height = height self.obstacles = obstacles self.create_grid() def create_grid(self): self.grid = np.zeros((self.height, self.width), dtype=np.int8) for obstacle in self.obstacles: polygon = Polygon(obstacle) x, y = np.meshgrid(np.arange(self.width), np.arange(self.height)) points = np.vstack((x.flatten(), y.flatten())).T points_inside = np.array([polygon.contains(Point(point)) or polygon.boundary.contains(Point(point)) for point in points]) self.grid[points_inside.reshape(self.height, self.width)] = 1 return def has_obstacles(self): return self.obstacles is not None def plot(self): plt.imshow(self.grid, cmap='gray') plt.show() class GridGenerator: def __init__(self, objects, width, height): self.objects = objects self.width = width self.height = height self.grids = [] self.generate_grids() def is_inside(self, x, y): return 0 <= x < self.width and 0 <= y < self.height and all(g[2].grid[y, x] != 1 for g in self.grids) def get_grid_at_time(self, time): for start_time, end_time, grid in self.grids: if start_time <= time <= end_time: return grid raise ValueError(f"No grid found for time {time}") def generate_grids(self): st = datetime.datetime.now() values = sorted(list(set([tup[0] for tup in self.objects] + [tup[1] for tup in self.objects]))) if len(values) == 0 or values[0] > 0: values.insert(0, 0) if values[-1] < INF_TIME: values.append(INF_TIME) pairs = list(zip(values[:-1], values[1:])) grids = [] objects_sorted = sorted(self.objects, key=lambda obj: obj[0]) # Sort objects by start time current_objects = [] j = 0 # Index of current time range for i in range(len(pairs)): start_time, end_time = pairs[i] polygons = [] # Add new objects to current_objects as long as their start time is within the current time range while j < len(objects_sorted) and objects_sorted[j][0] < end_time: if objects_sorted[j][1] > start_time: current_objects.append(objects_sorted[j]) j += 1 # Iterate through current_objects and add their polygons to the list for this time range for obj in current_objects: if obj[1] > start_time: polygons.append(obj[2]) grids.append((start_time, end_time, polygons)) return_grids = [] for grid in grids: g = Grid(self.width, self.height, grid[2]) return_grids.append((grid[0], grid[1], g)) self.grids = return_grids print(f"Grid generation time: {datetime.datetime.now() - st}") Write the function generate_grids more correctly and efficiently. Try to improve and optimize the running times, it takes a lot of time!
5e8a34c252df06e3cd8c2fbe54fdc647
{ "intermediate": 0.386093407869339, "beginner": 0.404737263917923, "expert": 0.20916926860809326 }
10,919
Write a script to load data using Async io Python and Selenium Python for systems that require time delays to simulate user actions. The script should include character recognition using the BeautifulSoup library and part of the script to check for the correctness of recognition of data in .png, .pdf, .jpg, .jpeg, .docx files. The data must be collected from individual user files in a docker container. Write an explanatory note on the stages of the script.
e17accb955a84d980e6d41d41ed138e9
{ "intermediate": 0.8214547634124756, "beginner": 0.05887461453676224, "expert": 0.11967068165540695 }
10,920
write a SOQL query to fetch the quote rate plan charge amount from the quote object
d94368eab9e1c6b878f7936113ec3d8b
{ "intermediate": 0.5681774020195007, "beginner": 0.16561166942119598, "expert": 0.2662108540534973 }
10,921
Make a accurate stock market predictor for predicting closing price using LSTM model and include super trend indicator for better results also make plot showing actual and predicted value (use dataset using yfinance for NIFTY): Supertrend Indicator: Super trend Indicator: What Does It Mean? The Super trend indicator is a trend-following indicator that works just like moving averages. This indicator is typically represented by the price, and you can determine the latest trend by its positioning on the price. This basic indicator is designed by using only two parameters – multiplier and period. The default parameters when you design the Super trend indicator plan are 3 for the multiplier and 10 for ATR (Average True Range). The ATR plays a crucial role here, as the Super trend indicator leverages the ATR for computing its value. It helps signal the degree or extent of price volatility. Super trend Indicator: How Does It Work? A super trend indicator is one of the most commonly used indicators for setting your selling and buying points at the most accurate levels. However, the question still remains: how does it work to accomplish something like that? You should know that two lines – a green line and a red line – compose the Super trend indicator. These lines enable you to evaluate the following: The trend direction, Whether to buy or sell and, in either case, when to do so. To plot and indicate the lines, the super trend indicator leverages the ATR along with the multiplicator. This enables you to set or position market entries based on volatility and momentum. And when it comes to what chart is best for the Super trend indicator to function, you can independently utilize it on almost every timeline you consider a trend to be developing. A super trend is a lagging indicator, implying that any well-built trend will boost the indicator’s performance. Super trend Indicator: Parameters to Know About As you have read earlier, 10 and 3 are the two default parameters. You must remember that any modifications to these numerical values will influence the utilization of the Super trend indicator. No trading indicator comes with the best setting. If you change more and more settings, the trading system may become over-optimized for that specific period. Keep a note of the following pointers: The market noise will be removed with higher settings when there’s a risk of fewer trading signals. The indicator will become more reactive/responsive to the price with smaller settings, resulting in more signals. Super trend Indicator Formula Here is the Super trend indicator formula that helps you calculate this indicator: Down = [(High + Low / 2) – Multiplier] x ATR Up = [(High + Low / 2) + Multiplier] x ATR To calculate the ATR, follow this formula: [(Previous ATR x 13) + Existing TR]/14 14 resembles a period in this equation. Thus, the ATR is determined by multiplying 13 by the past ATR. Then, add the result to the latest TR and divide it by the period. So, it’s clear that when it comes to the Super trend indicator, ATR plays a major role in it. Super trend Indicator: How to Use It for Identifying Buy & Sell Signals The super trend is an excellent trending indicator that functions exceptionally in both downtrends and uptrends. You can easily identify and locate the buy-sell signal whenever the indicator flips or rotates over the closing price. When the super trend closes below the price point and the color changes to green, the buy signal is generated. Meanwhile, a sell signal is generated when the color changes to red and the Super trend closes above the price point
78ba4575138260141437cdc6d7789bcb
{ "intermediate": 0.4513278901576996, "beginner": 0.41665300726890564, "expert": 0.13201913237571716 }
10,922
import { Text, View, Image, Pressable } from 'react-native'; import { gStyle } from '../styles/style'; import React, {useState, useEffect} from 'react'; import { useNavigation } from '@react-navigation/native'; import {firebase} from '../Firebase/firebase'; import moment from 'moment'; import 'firebase/compat/storage'; import 'firebase/compat/firestore'; export default function FutureMK() { const navigation = useNavigation(); const [futureMKData, setFutureMKData] = useState([]); useEffect(() => { const fetchData = async () => { try { const futureMKRef = firebase.firestore().collection('FutureMK'); const snapshot = await futureMKRef.get(); const data = snapshot.docs.map((doc) => doc.data()); const storage=firebase.storage(); const updateData = await Promise.all(data.map(async(mkData)=>{ const imagePath = mkData.imageUrl; const imageRef = storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {...mkData, imageUrl:url}; })) setFutureMKData(updateData); } catch (error) { console.log(error); } }; fetchData(); }, []); return ( <View style={gStyle.main}> {futureMKData.map((mkData, index)=>( <View key={index} style={gStyle.mainFMK}> <Text style={gStyle.dateFutureMK}>{moment(mkData.time.toDate()).format('Do MMM YYYY')}</Text> <View style={gStyle.FutureMKimg}> <Image source={{uri:mkData.imageUrl}} style={gStyle.FutureMKbannerImg}/> <Text style={gStyle.FutureMKnameOfMK}>{mkData.name}</Text> <Text style={gStyle.hr}></Text> </View> <Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>{mkData.price} P.</Text></Text> <Text style={gStyle.FutureMKdescription}> {mkData.description} </Text> <Pressable style={gStyle.FutureMKmoreDetails} onPress={()=>{navigation.navigate('SignUpForMK',{mkData});}} > <Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text> </Pressable> <Text style={gStyle.FutureMKline}></Text> </View> ))} </View> ); } LOG [TypeError: Cannot read property 'split' of undefined] i dont know where is error
cf4827571eb5ecf20c0ebf3672ccac95
{ "intermediate": 0.4138505756855011, "beginner": 0.4036121368408203, "expert": 0.182537242770195 }
10,923
android activity调用fragement中方法
7d840d0d68fcb748759e97d6ed7d1858
{ "intermediate": 0.561396598815918, "beginner": 0.21917463839054108, "expert": 0.21942874789237976 }
10,924
C:\Users\AshotxXx\PycharmProjects\UNCX\RealTimeUNCX\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\UNCX\RealTimeUNCX\main.py Starting at block 28913760 Traceback (most recent call last): File "C:\Users\AshotxXx\PycharmProjects\UNCX\RealTimeUNCX\main.py", line 81, in <module> asyncio.run(main()) File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\UNCX\RealTimeUNCX\main.py", line 79, in main await display_real_time_blocks(target_from_address) File "C:\Users\AshotxXx\PycharmProjects\UNCX\RealTimeUNCX\main.py", line 63, in display_real_time_blocks contracts = await get_contracts_in_block(block_number, target_from_address, session) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\UNCX\RealTimeUNCX\main.py", line 22, in get_contracts_in_block transactions = await get_internal_transactions(block_number, block_number, session) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\UNCX\RealTimeUNCX\main.py", line 10, in get_internal_transactions async with semaphore, aiohttp.Timeout(10): ^^^^^^^^^^^^^^^ AttributeError: module 'aiohttp' has no attribute 'Timeout' Process finished with exit code 1
d3ca01ea0d10605653cd9c8cf9dfe7dd
{ "intermediate": 0.40128380060195923, "beginner": 0.4286465048789978, "expert": 0.17006973922252655 }
10,925
как в этом коде точки THREE.Points заменить на THREE.CircleGeometry? вот код: // import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; class Stage { constructor() { this.renderParam = { clearColor: 0x000000, // фон width: window.innerWidth, height: window.innerHeight }; this.cameraParam = { fov: 20, near: 0.1, far: 100, lookAt: new THREE.Vector3(0, 0, 0), x: 0, y: 0, z: 8 }; this.scene = null; this.camera = null; this.renderer = null; this.isInitialized = false; } init() { this.setScene(); this.setRender(); this.setCamera(); this.isInitialized = true; } setScene() { this.scene = new THREE.Scene(); //this.scene.add(new THREE.GridHelper(1000, 100)); //this.scene.add(new THREE.AxesHelper(100)); } setRender() { this.renderer = new THREE.WebGLRenderer(); this.renderer.setPixelRatio(window.devicePixelRatio); this.renderer.setClearColor(new THREE.Color(this.renderParam.clearColor)); this.renderer.setSize(this.renderParam.width, this.renderParam.height); const wrapper = document.querySelector("#webgl"); wrapper.appendChild(this.renderer.domElement); } setCamera() { if (!this.isInitialized) { this.camera = new THREE.PerspectiveCamera( 0, 0, this.cameraParam.near, this.cameraParam.far ); this.camera.position.set( this.cameraParam.x, this.cameraParam.y, this.cameraParam.z ); this.camera.lookAt(this.cameraParam.lookAt); // Control. const controls = new OrbitControls(this.camera, this.renderer.domElement); controls.enableZoom = false; controls.enableDamping = true; controls.dampingFactor = 0.05; } const windowWidth = window.innerWidth; const windowHeight = window.innerHeight; this.camera.aspect = windowWidth / windowHeight; this.camera.fov = this.cameraParam.fov; this.camera.updateProjectionMatrix(); this.renderer.setSize(windowWidth, windowHeight); } render() { this.renderer.render(this.scene, this.camera); } onResize() { this.setCamera(); } onRaf() { this.render(); } } const loader = new GLTFLoader(); const url = 'GRAF_3_26.glb'; loader.load(url, function (gltf) { const model = gltf.scene; model.traverse((child) => { if (child.isMesh) { const geometryLogo = child.geometry; // console.log(geometryLogo); class Mesh { constructor(stage) { this.rotationPower = 0.0000; // скорость вращения this.stage = stage; } init() { this.setMesh(); this.setScroll(); } // Создает массив точек, лежащих на поверхности getGeometryPosition(geometry) { const numParticles = 100000; // кол-во точек const material = new THREE.MeshBasicMaterial(); const mesh = new THREE.Mesh(geometry, material); const sampler = new THREE.MeshSurfaceSampler(mesh).build(); const particlesPosition = new Float32Array(numParticles * 3); for (let i = 0; i < numParticles; i++) { const newPosition = new THREE.Vector3(); const normal = new THREE.Vector3(); sampler.sample(newPosition, normal); particlesPosition.set([newPosition.x, newPosition.y, newPosition.z],i * 3); } return particlesPosition; } setMesh() { // const positions = geometryLogo.getAttribute('position').array; const geometry = new THREE.BufferGeometry(); const Logo = this.getGeometryPosition(geometryLogo.toNonIndexed()); console.log(geometryLogo); const firstPos = this.getGeometryPosition(new THREE.SphereBufferGeometry(1, 32, 32).toNonIndexed()); // const secPos = this.getGeometryPosition(new THREE.TorusBufferGeometry(0.7, 0.3, 32, 32).toNonIndexed()); // const thirdPos = this.getGeometryPosition(new THREE.TorusKnotBufferGeometry(0.6, 0.25, 300, 20, 6, 10).toNonIndexed()); // const forthPos = this.getGeometryPosition(new THREE.CylinderBufferGeometry(1, 1, 1, 32, 32).toNonIndexed()); // const fivePos = this.getGeometryPosition(new THREE.IcosahedronBufferGeometry(1.1, 0).toNonIndexed()); // console.log(geometry); const texture2 = new THREE.TextureLoader().load('Rectangle 56.png'); const texture = new THREE.TextureLoader().load('gradient-3.png'); let uniforms = { mouseCoord: { type: 'v3', value: new THREE.Vector3() }, mouseCoord: { type: 'v3', value: new THREE.Vector3() }, tex: { type: 't', value: texture2 }, opacity: { type: 'f', value: 0.5 }, res: { type: 'v2', value: new THREE.Vector2(window.innerWidth, window.innerHeight) }, u_sec1: { type: "f", value: 0.0 }, u_sec2: { type: "f", value: 0.0 } }; const material = new THREE.RawShaderMaterial({ vertexShader: ``, fragmentShader: ``, uniforms: uniforms, transparent: true, blending: THREE.AdditiveBlending, }); uniforms.mouseCoord.value.z = 50; let time = 0; function animate() { requestAnimationFrame(animate); time += 0.006; uniforms.mouseCoord.value.x = Math.sin(time) / 2 + 0.5; console.log('x =' + uniforms.mouseCoord.value.x); uniforms.mouseCoord.value.y = Math.cos(time) / 2 + 0.5; console.log('y =' + uniforms.mouseCoord.value.y); } animate(); geometry.setAttribute("position", new THREE.BufferAttribute(firstPos, 3)); // geometry.setAttribute("position", new THREE.BufferAttribute(Logo, 3)); geometry.setAttribute("secPosition", new THREE.BufferAttribute(Logo, 3)); geometry.setAttribute("thirdPosition", new THREE.BufferAttribute(Logo, 3)); // geometry.setAttribute("forthPosition", new THREE.BufferAttribute(Logo, 3)); // geometry.setAttribute("fivePosition",new THREE.BufferAttribute(Logo, 3)); this.mesh = new THREE.Points(geometry, material); this.group = new THREE.Group(); this.group.add(this.mesh); this.group.rotation.x = Math.PI / 2.0; this.stage.scene.add(this.group); } setScroll() { gsap.timeline({ defaults: {}, scrollTrigger: { trigger: "body", start: "top top", end: "bottom bottom", scrub: 2 } }).to(this.mesh.rotation, { x: Math.PI * 2, y: Math.PI * 2, z: Math.PI * 2 }); /*Тут я изменил gsap.to на gsap.fromTo обозначив значения до и после*/ // gsap.to(this.mesh.material.uniforms.u_sec1, { // value: 1.0, // scrollTrigger: { // trigger: ".s-1", // start: "bottom bottom", // end: "bottom top", // scrub: .2 // } // }); gsap.fromTo(this.mesh.material.uniforms.u_sec1, { value: 5.0, // размер до },{ value: 1.0, // размер после scrollTrigger: { trigger: ".s-1", start: "bottom bottom", end: "bottom top", scrub: .2 } }); gsap.to(this.mesh.material.uniforms.u_sec2, { value: 1.0, scrollTrigger: { trigger: ".s-2", start: "bottom bottom", end: "bottom top", scrub: .2 } }); } render() { // this.group.rotation.x += this.rotationPower; // this.group.rotation.y += this.rotationPower; } onResize() { // } onRaf() { this.render(); } } const init = () => { const stage = new Stage(); stage.init(); const mesh = new Mesh(stage); mesh.init(); window.addEventListener("resize", () => { stage.onResize(); mesh.onResize(); }); const raf = () => { window.requestAnimationFrame(() => { stage.onRaf(); mesh.onRaf(); raf(); }); }; raf(); }; init(); } }); });
4e9abda19f53e6fa482545317144ba0b
{ "intermediate": 0.38281798362731934, "beginner": 0.4437137246131897, "expert": 0.17346835136413574 }
10,926
import { Text, View, Image, Pressable } from 'react-native'; import { gStyle } from '../styles/style'; import React, {useState, useEffect} from 'react'; import { useNavigation } from '@react-navigation/native'; import {firebase} from '../Firebase/firebase'; import moment from 'moment'; import 'firebase/compat/storage'; import 'firebase/compat/firestore'; export default function FutureMK() { const navigation = useNavigation(); const [futureMKData, setFutureMKData] = useState([]); useEffect(() => { const fetchData = async () => { try { const futureMKRef = firebase.firestore().collection('FutureMK'); const snapshot = await futureMKRef.get(); const data = snapshot.docs.map((doc) => doc.data()); const storage=firebase.storage(); const updateData = await Promise.all(data.map(async(mkData)=>{ const imagePath = mkData.imageUrl; const imageRef = storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {...mkData, imageUrl:url}; })) setFutureMKData(updateData); } catch (error) { console.log(error); } }; fetchData(); }, []); return ( <View style={gStyle.main}> {futureMKData.map((mkData, index)=>( <View key={index} style={gStyle.mainFMK}> <Text style={gStyle.dateFutureMK}>{moment(mkData.time.toDate()).format('Do MMM YYYY')}</Text> <View style={gStyle.FutureMKimg}> <Image source={{uri:mkData.imageUrl}} style={gStyle.FutureMKbannerImg}/> <Text style={gStyle.FutureMKnameOfMK}>{mkData.name}</Text> <Text style={gStyle.hr}></Text> </View> <Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>{mkData.price} P.</Text></Text> <Text style={gStyle.FutureMKdescription}> {mkData.description && mkData.description.length>100 ? mkData.description.substring(0,100)+'...' : mkData.description} </Text> <Pressable style={gStyle.FutureMKmoreDetails} onPress={()=>{navigation.navigate('SignUpForMK',{mkData});}} > <Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text> </Pressable> <Text style={gStyle.FutureMKline}></Text> </View> ))} </View> ); } i nedd to make description shorter but there is err LOG [TypeError: Cannot read property 'split' of undefined]
34b51bba991d57154ca858e8515b46e5
{ "intermediate": 0.43887096643447876, "beginner": 0.42477014660835266, "expert": 0.13635894656181335 }
10,927
pgadmin set log_statement on all database forever using query?
0aa3104a581efa685caa1ad4a244102b
{ "intermediate": 0.48951292037963867, "beginner": 0.2398320734500885, "expert": 0.2706550359725952 }
10,928
выдели только 1 функцию которая дает программе передвигать фигру const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let squares = [{x: 50, y: 50, size: 50, color: 'red'}, {x: 150, y: 50, size: 50, color: 'blue'}, {x: 250, y: 50, size: 50, color: 'green'}]; let selectedSquare = null; let mousePosition = null; canvas.addEventListener('mousedown', (event) => { mousePosition = {x: event.offsetX, y: event.offsetY}; selectedSquare = squares.find(square => { return mousePosition.x >= square.x && mousePosition.x <= square.x + square.size && mousePosition.y >= square.y && mousePosition.y <= square.y + square.size; }); }); canvas.addEventListener('mousemove', (event) => { if (selectedSquare) { selectedSquare.x = event.offsetX - mousePosition.x + selectedSquare.x; selectedSquare.y = event.offsetY - mousePosition.y + selectedSquare.y; mousePosition = {x: event.offsetX, y: event.offsetY}; } }); canvas.addEventListener('mouseup', () => { selectedSquare = null; }); function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); squares.forEach(square => { ctx.fillStyle = square.color; ctx.fillRect(square.x, square.y, square.size, square.size); }); } function update() {} function loop() { update(); draw(); requestAnimationFrame(loop); } loop();
96529b555571bdef11b9526062f0ea67
{ "intermediate": 0.3859034776687622, "beginner": 0.4367835521697998, "expert": 0.177312970161438 }
10,929
qlistview如何只显示图片
f2dbc9ea1871783390c63a2816daf03d
{ "intermediate": 0.2947683036327362, "beginner": 0.2964772582054138, "expert": 0.40875443816185 }
10,930
Please correct this code for stock market prediction modify this code as im getting a blank plot in the below code (The plot shows nothing) correct everywhere it need to be changed: import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout import yfinance as yf # Download historical stock data stock_symbol = 'AAPL' # Replace this with the desired stock symbol start_date = '2000-01-01' # Replace this with the desired start date end_date = datetime.datetime.today().strftime('%Y-%m-%d') # Today's date stock_data = yf.download(stock_symbol, start=start_date, end=end_date) stock_data['Close'].plot(title='AAPL Closing Price', figsize=(15,6)) plt.show() # Reset the index and use the 'Date' column as the index stock_data.reset_index(inplace=True) stock_data.set_index('Date', inplace=True) # Calculate the Average True Range and Super Trend price_high_low = stock_data['High'] - stock_data['Low'] price_high_close = abs(stock_data['High'] - stock_data['Close'].shift()) price_low_close = abs(stock_data['Low'] - stock_data['Close'].shift()) tr = np.maximum(price_high_low, np.maximum(price_high_close, price_low_close)) atr = tr.rolling(window=14).mean() multiplier = 3 stock_data['SuperTrend_Up'] = (stock_data['High'] + stock_data['Low']) / 2 - multiplier * atr stock_data['SuperTrend_Down'] = (stock_data['High'] + stock_data['Low']) / 2 + multiplier * atr super_trend = [] for i in range(len(stock_data)): if i == 0: super_trend.append(stock_data['Close'].iloc[i]) elif stock_data['Close'].iloc[i] > super_trend[i - 1]: super_trend.append(stock_data['SuperTrend_Up'].iloc[i]) else: super_trend.append(stock_data['SuperTrend_Down'].iloc[i]) stock_data['SuperTrend'] = super_trend stock_data.info() # Remove rows with missing data and select the 'Close' and 'SuperTrend' columns for training and testing stock_data = stock_data.dropna() data = stock_data[['Close', 'SuperTrend']].values stock_data.head() # Scale the data scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(data) # Choose number of time steps (e.g., 60 days) and split into training and testing datasets time_steps = 60 train_data = scaled_data[:len(stock_data)-time_steps-1] test_data = scaled_data[len(stock_data)-time_steps-1:] # Prepare the input and output for the LSTM model x_train = [] y_train = [] x_test = [] y_test = [] for i in range(time_steps, len(train_data)): x_train.append(train_data[i-time_steps:i]) y_train.append(train_data[i, 0]) for i in range(time_steps, len(test_data)): x_test.append(test_data[i-time_steps:i]) y_test.append(test_data[i, 0]) x_train, y_train = np.array(x_train), np.array(y_train) x_test, y_test = np.array(x_test), np.array(y_test) # Build the LSTM model model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 2))) model.add(Dropout(0.2)) model.add(LSTM(units=50)) model.add(Dropout(0.2)) model.add(Dense(1)) # Compile and train the LSTM model model.compile(optimizer='adam', loss='mean_squared_error') model.fit(x_train, y_train, epochs=100, batch_size=32) # Perform predictions using the LSTM model predicted_prices = model.predict(x_test) predicted_prices = np.concatenate((predicted_prices, x_test[:, -1, 1].reshape(-1, 1)), axis=1) predicted_prices = scaler.inverse_transform(predicted_prices)[:, 0] # Create a dataframe for actual prices and predicted prices actual_prices = pd.DataFrame(stock_data[len(stock_data) - len(y_test):]['Close']) actual_prices['predicted'] = predicted_prices actual_prices.columns = ['Actual', 'Predicted'] # Plot the actual vs predicted closing prices plt.figure(figsize=(14, 6)) plt.plot(actual_prices['Actual'].values, color='blue', label='Actual Stock Price') plt.plot(actual_prices['Predicted'].values, color='red', label='Predicted Stock Price') plt.title('Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Stock Price') plt.legend() plt.show()
6ea26cb753076d38dbb799bc395d4f14
{ "intermediate": 0.35249462723731995, "beginner": 0.44084233045578003, "expert": 0.20666302740573883 }
10,931
I have made a model for predicting the stock market in this code but i think the code is incorrect im not getting anything in the plot ie the plot is blank also the time axis starts with -0.04 please correct this code also give plot for daywise instead of time
2bf6c8f00f8ff43613a2315d1d97081c
{ "intermediate": 0.18981033563613892, "beginner": 0.17086686193943024, "expert": 0.639322817325592 }
10,932
Представь, что ты программист Django. Нужно реализовать функционал сессий для юзера при помощи библиотеки django-user-sessions: урлы: 1) Просмотр всех сессий юзера. 2) Просмотр деталей конкретной сессии юзера (ip адрес, браузер и девайс, когда последний раз был активен, локация) 3) Удаление конкретной сессии юзера. 4) Удаление всех сессий юзера. Представления нужно реализовать при помощи django-rest-framework. Для логина пользователя я использую библиотеку dj_rest_auth. Мое представление логина: from dj_rest_auth.views import LoginView class UserLoginAPIView(LoginView): """ Authenticate existing users using phone number or email and password. """ serializer_class = UserLoginSerializer class UserLoginSerializer(serializers.Serializer): """ Serializer to login users with email or phone number. """ phone = PhoneNumberSerializer(read_only=True) phone_number = PhoneNumberField(required=False, allow_blank=True) email = serializers.EmailField(required=False, allow_blank=True) password = serializers.CharField( write_only=True, style={'input_type': 'password'}) class Meta: model = CustomUser fields = ('pk', 'email', 'phone', 'first_name', 'last_name') def _validate_phone_email(self, phone_number, email, password): user = None if email and password: user = authenticate(username=email, password=password) elif str(phone_number) and password: user = authenticate(username=str(phone_number), password=password) else: raise serializers.ValidationError( _("Enter a phone number or an email and password.")) return user def validate(self, validated_data): phone_number = validated_data.get('phone_number') email = validated_data.get('email') password = validated_data.get('password') user = None user = self._validate_phone_email(phone_number, email, password) if not user: raise InvalidCredentialsException() if not user.is_active: raise AccountDisabledException() if email: email_address = user.emailaddress_set.filter( email=user.email, verified=True).exists() if not email_address: raise serializers.ValidationError(_('E-mail is not verified.')) else: if not user.phone.is_verified: raise serializers.ValidationError( _('Phone number is not verified.')) validated_data['user'] = user return validated_data Нужно при логине сохранять сессию юзера. При удалении сессии юзера нужно разлогинивать и убивать токен. Токен используется при помощи библиотеки dj_rest_auth - from dj_rest_auth.views import LoginView.
e56a756b5a88d05985b79b51b68118f3
{ "intermediate": 0.25842344760894775, "beginner": 0.6706503629684448, "expert": 0.07092615962028503 }
10,933
Make a accurate stock market predictor for predicting closing price using LSTM model and include super trend indicator for better results also make plot showing actual and predicted value: Supertrend Indicator: Super trend Indicator: What Does It Mean? The Super trend indicator is a trend-following indicator that works just like moving averages. This indicator is typically represented by the price, and you can determine the latest trend by its positioning on the price. This basic indicator is designed by using only two parameters – multiplier and period. The default parameters when you design the Super trend indicator plan are 3 for the multiplier and 10 for ATR (Average True Range). The ATR plays a crucial role here, as the Super trend indicator leverages the ATR for computing its value. It helps signal the degree or extent of price volatility. Super trend Indicator: How Does It Work? A super trend indicator is one of the most commonly used indicators for setting your selling and buying points at the most accurate levels. However, the question still remains: how does it work to accomplish something like that? You should know that two lines – a green line and a red line – compose the Super trend indicator. These lines enable you to evaluate the following: The trend direction, Whether to buy or sell and, in either case, when to do so. To plot and indicate the lines, the super trend indicator leverages the ATR along with the multiplicator. This enables you to set or position market entries based on volatility and momentum. And when it comes to what chart is best for the Super trend indicator to function, you can independently utilize it on almost every timeline you consider a trend to be developing. A super trend is a lagging indicator, implying that any well-built trend will boost the indicator’s performance. Super trend Indicator: Parameters to Know About As you have read earlier, 10 and 3 are the two default parameters. You must remember that any modifications to these numerical values will influence the utilization of the Super trend indicator. No trading indicator comes with the best setting. If you change more and more settings, the trading system may become over-optimized for that specific period. Keep a note of the following pointers: The market noise will be removed with higher settings when there’s a risk of fewer trading signals. The indicator will become more reactive/responsive to the price with smaller settings, resulting in more signals. Super trend Indicator Formula Here is the Super trend indicator formula that helps you calculate this indicator: Down = [(High + Low / 2) – Multiplier] x ATR Up = [(High + Low / 2) + Multiplier] x ATR To calculate the ATR, follow this formula: [(Previous ATR x 13) + Existing TR]/14 14 resembles a period in this equation. Thus, the ATR is determined by multiplying 13 by the past ATR. Then, add the result to the latest TR and divide it by the period. So, it’s clear that when it comes to the Super trend indicator, ATR plays a major role in it. Super trend Indicator: How to Use It for Identifying Buy & Sell Signals The super trend is an excellent trending indicator that functions exceptionally in both downtrends and uptrends. You can easily identify and locate the buy-sell signal whenever the indicator flips or rotates over the closing price. When the super trend closes below the price point and the color changes to green, the buy signal is generated. Meanwhile, a sell signal is generated when the color changes to red and the Super trend closes above the price point.
4414ad6a81cb2112a679c204cbbb3b66
{ "intermediate": 0.39575549960136414, "beginner": 0.39785388112068176, "expert": 0.20639067888259888 }
10,934
I have write a code for stock market prediction but i think this code is incorrect as im not getting anything in plot ie the plot is empty please correct the code also the time axis starts with -0.04 which is not possible give a correct code for predicting the stock market also plot for daywise not time wise: Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import datetime from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout import yfinance as yf # Download historical stock data stock_symbol = 'AAPL' # Replace this with the desired stock symbol start_date = '2000-01-01' # Replace this with the desired start date end_date = datetime.datetime.today().strftime('%Y-%m-%d') # Today's date stock_data = yf.download(stock_symbol, start=start_date, end=end_date) stock_data['Close'].plot(title='AAPL Closing Price', figsize=(15,6)) plt.show() # Reset the index and use the 'Date' column as the index stock_data.reset_index(inplace=True) stock_data.set_index('Date', inplace=True) # Calculate the Average True Range and Super Trend price_high_low = stock_data['High'] - stock_data['Low'] price_high_close = abs(stock_data['High'] - stock_data['Close'].shift()) price_low_close = abs(stock_data['Low'] - stock_data['Close'].shift()) tr = np.maximum(price_high_low, np.maximum(price_high_close, price_low_close)) atr = tr.rolling(window=14).mean() multiplier = 3 stock_data['SuperTrend_Up'] = (stock_data['High'] + stock_data['Low']) / 2 - multiplier * atr stock_data['SuperTrend_Down'] = (stock_data['High'] + stock_data['Low']) / 2 + multiplier * atr super_trend = [] for i in range(len(stock_data)): if i == 0: super_trend.append(stock_data['Close'].iloc[i]) elif stock_data['Close'].iloc[i] > super_trend[i - 1]: super_trend.append(stock_data['SuperTrend_Up'].iloc[i]) else: super_trend.append(stock_data['SuperTrend_Down'].iloc[i]) stock_data['SuperTrend'] = super_trend stock_data.info() # Remove rows with missing data and select the 'Close' and 'SuperTrend' columns for training and testing stock_data = stock_data.dropna() data = stock_data[['Close', 'SuperTrend']].values stock_data.head() # Scale the data scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(data) # Choose number of time steps (e.g., 60 days) and split into training and testing datasets time_steps = 60 train_data = scaled_data[:len(stock_data)-time_steps-1] test_data = scaled_data[len(stock_data)-time_steps-1:] # Prepare the input and output for the LSTM model x_train = [] y_train = [] x_test = [] y_test = [] for i in range(time_steps, len(train_data)): x_train.append(train_data[i-time_steps:i]) y_train.append(train_data[i, 0]) for i in range(time_steps, len(test_data)): x_test.append(test_data[i-time_steps:i]) y_test.append(test_data[i, 0]) x_train, y_train = np.array(x_train), np.array(y_train) x_test, y_test = np.array(x_test), np.array(y_test) # Build the LSTM model model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 2))) model.add(Dropout(0.2)) model.add(LSTM(units=50)) model.add(Dropout(0.2)) model.add(Dense(1)) # Compile and train the LSTM model model.compile(optimizer='adam', loss='mean_squared_error') model.fit(x_train, y_train, epochs=100, batch_size=32) # Perform predictions using the LSTM model predicted_prices = model.predict(x_test) predicted_prices = np.concatenate((predicted_prices, x_test[:, -1, 1].reshape(-1, 1)), axis=1) predicted_prices = scaler.inverse_transform(predicted_prices)[:, 0] # Create a dataframe for actual prices and predicted prices actual_prices = pd.DataFrame(stock_data.iloc[-len(y_test):, :]['Close']) actual_prices['Predicted'] = predicted_prices actual_prices.columns = ['Actual', 'Predicted'] # Plot the actual vs predicted closing prices plt.figure(figsize=(14, 6)) plt.plot(actual_prices['Actual'].values, color='blue', label='Actual Stock Price') plt.plot(actual_prices['Predicted'].values, color='red', label='Predicted Stock Price') plt.title('Stock Price Prediction') plt.xlabel('Time') plt.ylabel('Stock Price') plt.legend() plt.show()
a735034c4f499f23dcf61644a0e31864
{ "intermediate": 0.4423849880695343, "beginner": 0.3219093978404999, "expert": 0.23570559918880463 }
10,935
find records in first dataframe which is not present in second data frame
5e050e1a2f612a10084a74b27da9d38d
{ "intermediate": 0.46354952454566956, "beginner": 0.15556254982948303, "expert": 0.38088786602020264 }
10,936
THREE.MeshSurfaceSampler is not a constructor
00ccc77378b20964c82fefc0fe32c2ca
{ "intermediate": 0.39529553055763245, "beginner": 0.323367714881897, "expert": 0.2813367247581482 }
10,937
pass a list of data not in the records of dataframe
50638ddb9e173d01c1815518390fd1b6
{ "intermediate": 0.38495969772338867, "beginner": 0.2428375780582428, "expert": 0.37220272421836853 }
10,938
Человек планирует поезду за границу и хочет узнать, какие есть в месте куда он едет опасные лица. Украина, Киевская область, как узнать таких лиц?
31d89a7205335f885b3113302c134aee
{ "intermediate": 0.3144668936729431, "beginner": 0.29912471771240234, "expert": 0.38640832901000977 }
10,939
i have this err ERROR Error: [TypeError: Cannot read property 'split' of undefined] this is my home screen import { ScrollView, Text, View } from 'react-native'; import { gStyle } from '../styles/style'; import Header from '../components/Header'; import Footer from '../components/Footer'; import PastMK from '../components/PastMK'; import FutureMK from '../components/FutureMK'; export default function Home() { return ( <View> <ScrollView> <Header/> <Text style={gStyle.header}>Творческие мастер-классы{'\n'}от Белой Розы</Text> <FutureMK/> <FutureMK/> <Text style={gStyle.header}>Прошедшие{'\n'}мастер-классы</Text> <PastMK/> <Footer/> </ScrollView> </View> ); } when i remove FutureMK there is no err anymore but when i add it again here is err. here is my FutureMK import { Text, View, Image, Pressable } from 'react-native'; import { gStyle } from '../styles/style'; import React, {useState, useEffect} from 'react'; import { useNavigation } from '@react-navigation/native'; import {firebase} from '../Firebase/firebase'; import moment from 'moment'; import 'firebase/compat/storage'; import 'firebase/compat/firestore'; export default function FutureMK() { const navigation = useNavigation(); const [futureMKData, setFutureMKData] = useState([]); useEffect(() => { const fetchData = async () => { try { const futureMKRef = firebase.firestore().collection('FutureMK'); const snapshot = await futureMKRef.get(); const data = snapshot.docs.map((doc) => doc.data()); const storage=firebase.storage(); const updateData = await Promise.all(data.map(async(mkData)=>{ const imagePath = mkData.imageUrl; const imageRef = storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {...mkData, imageUrl:url}; })) setFutureMKData(updateData); } catch (error) { console.error('Error:',error); } }; fetchData(); }, []); return ( <View style={gStyle.main}> {futureMKData.map((mkData, index)=>( <View key={index} style={gStyle.mainFMK}> <Text style={gStyle.dateFutureMK}>{moment(mkData.time.toDate()).format('Do MMM YYYY')}</Text> <View style={gStyle.FutureMKimg}> <Image source={{uri:mkData.imageUrl}} style={gStyle.FutureMKbannerImg}/> <Text style={gStyle.FutureMKnameOfMK}>{mkData.name}</Text> <Text style={gStyle.hr}></Text> </View> <Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>{mkData.price} P.</Text></Text> <Text style={gStyle.FutureMKdescription}> {mkData.description} </Text> <Pressable style={gStyle.FutureMKmoreDetails} onPress={()=>{navigation.navigate('SignUpForMK',{mkData});}} > <Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text> </Pressable> <Text style={gStyle.FutureMKline}></Text> </View> ))} </View> ); }
93c4a4f65ddfc7c02125bea043d4fd48
{ "intermediate": 0.4101051688194275, "beginner": 0.45463255047798157, "expert": 0.13526229560375214 }
10,940
how do i enable aspnetcore development mode from the web.config gfile?
a576d2b5eb8e5ebf0a8bb3ca33c0109b
{ "intermediate": 0.5352460145950317, "beginner": 0.2008911371231079, "expert": 0.26386287808418274 }
10,941
how to add where condition in file schema.prisma
61ce7fc1fe53a83a6574a2c2b0199ca6
{ "intermediate": 0.3234705924987793, "beginner": 0.3197299540042877, "expert": 0.3567994236946106 }
10,942
generate a relation in GraphQL using a Prisma schema
0b425a3731235b1a822883225c3d93c9
{ "intermediate": 0.5559480786323547, "beginner": 0.218185156583786, "expert": 0.22586680948734283 }
10,943
To query a field relation in GraphQL using a Prisma schema
5376060a5698b4317c2c2877a63bda77
{ "intermediate": 0.5451406836509705, "beginner": 0.27843177318573, "expert": 0.17642752826213837 }
10,944
How to generate graphql field relation in schema.prisma model
3344257e18acdd87a5144231cbf79e87
{ "intermediate": 0.30964094400405884, "beginner": 0.20927128195762634, "expert": 0.48108768463134766 }
10,945
flutter how to convert MultipartFile to Uint8List?
e06ad8c024cf9a7bfd87400fafc10102
{ "intermediate": 0.5618403553962708, "beginner": 0.18812064826488495, "expert": 0.2500389516353607 }
10,946
Can you see any flaws in this system: %%file anomaly.py import json import os import time import numpy as np import socket import logging from datetime import datetime from joblib import load from confluent_kafka import Producer, Consumer from multiprocessing import Process KAFKA_BROKER = 'broker:9092' TRANSACTION_TOPIC = 'transactions' TRANSACTOPM_CG = 'transactions' ANOMALY_TOPIC = 'anomaly' NUM_PARTITIONS = 3 client_ids = np.arange(1, 10001) warnings = 0 clients = {'client_id': client_ids, 'Warning': warnings} clients= pd.DataFrame(clients) #MODEL_PATH = os.path.abspath('isolation_forest.joblib') def create_producer(): try: producer = Producer({ "bootstrap.servers":KAFKA_BROKER, "client.id": socket.gethostname(), "enable.idempotence": True, "batch.size": 64000, "linger.ms":10, "acks": "all", "retries": 5, "delivery.timeout.ms":1000 }) except Exception as e: logging.exception("nie mogę utworzyć producenta") producer = None return producer def create_consumer(topic, group_id): try: consumer = Consumer({ "bootstrap.servers": KAFKA_BROKER, "group.id": group_id, "client.id": socket.gethostname(), "isolation.level":"read_committed", "default.topic.config":{ "auto.offset.reset":"latest", "enable.auto.commit": False } }) consumer.subscribe([topic]) except Exception as e: logging.exception("nie mogę utworzyć konsumenta") consumer = None return consumer def detekcja_anomalii(): consumer = create_consumer(topic=TRANSACTION_TOPIC, group_id=TRANSACTOPM_CG) producer = create_producer() first_check=load("first_check.pkl") second_check=laad("second_check.pkl") isolation_first=("first_isolation.pkl") isolation_second=("second_isolation.pkl") #clf = load(MODEL_PATH) while True: message = consumer.poll() if message is None: continue if message.error(): logging.error(f"CONSUMER error: {message.error()}") continue record = json.loads(message.value().decode('utf-8')) data = record['data'] if clients[record['ID']-1,1] >= 2: _id=str(record["ID"]) record = { "id": _id, "data": "Transakcja zablokowana-wymagana autoryzacja tożsamości" "current_time" : datetime.utcnow().isoformat() } record = json.dumps(record).encode("utf-8") producer.produce(topic=ANOMALY_TOPIC, value=record) producer.flush() elif clients[record['ID']-1,1]==1: prediciton1=second_check.predict(data) prediction2=isolation_second.predict(data) if prediction1[0] == 1 or prediciton2[0] == -1: clients[record['ID']-1,1]=2 _id=str(record["ID"]) record = { "id": _id, "data": "Transakcja zablokowana-wymagana autoryzacja tożsamości" "current_time" : datetime.utcnow().isoformat() } record = json.dumps(record).encode("utf-8") producer.produce(topic=ANOMALY_TOPIC, value=record) producer.flush() else: clients[record['ID']-1,1]=0 _id=str(record["ID"]) record = { "id": _id, "data": "Transakcja OK" "current_time" : datetime.utcnow().isoformat() } record = json.dumps(record).encode("utf-8") producer.produce(topic=ANOMALY_TOPIC, value=record) producer.flush() else: prediciton1=first_check.predict(data) prediction2=isolation_first.predict(data) if prediction1[0] == 0 and prediciton2[0] == 1: _id=str(record["ID"]) record = { "id": _id, "data": "Transakcja OK" "current_time" : datetime.utcnow().isoformat() } record = json.dumps(record).encode("utf-8") producer.produce(topic=ANOMALY_TOPIC, value=record) producer.flush() elif prediction1[0] == and prediciton2[0] == -1: clients[record['ID']-1,1]=1 _id=str(record["ID"]) record = { "id": _id, "data": "Wysłane ostrzeżenie, wymuszenie dodatkowej autoryzacji" "current_time" : datetime.utcnow().isoformat() } record = json.dumps(record).encode("utf-8") producer.produce(topic=ANOMALY_TOPIC, value=record) producer.flush() else: clients[record['ID']-1,1]=1 _id=str(record["ID"]) record = { "id": _id, "data": "Transakcja podejrzana" "current_time" : datetime.utcnow().isoformat() } record = json.dumps(record).encode("utf-8") producer.produce(topic=ANOMALY_TOPIC, value=record) producer.flush() consumer.close() for _ in range(NUM_PARTITIONS): p = Process(target=detekcja_anomalii) p.start() ?
ff566060194cdd14e930acb55c5c2781
{ "intermediate": 0.408908873796463, "beginner": 0.4877287745475769, "expert": 0.10336236655712128 }