row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
11,448
подсказки с городами работает в index.ejs, но не работает в profile.ejs: index.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" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" /> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <title>Home</title> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/">My Musician Site</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home</a> </li> <% if (userLoggedIn) { %> <li class="nav-item"> <a class="nav-link" href="/profile/<%= musician.id %>">Hello, <%= username %></a> </li> <li class="nav-item"> <a class="nav-link" href="/logout">Logout</a> </li> <% } else { %> <li class="nav-item"> <a class="nav-link" href="/register">Register</a> </li> <li class="nav-item"> <a class="nav-link" href="/login">Login</a> </li> <% } %> </ul> </div> </nav> </header> <main class="container mt-5"> <div class="row"> <div class="col-md-8"> <!-- добавляет форму с поиском музыкантом --> <form method="get" action="/search"> <div class="form-group"> <label for="query">Search by name or genre:</label> <div class="input-group"> <input id="query" name="query" type="text" class="form-control" value="<%= query %>"> <div class="input-group-append"> <button type="submit" class="btn btn-primary">Search</button> </div> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="role">Search by role:</label> <select id="role" name="role" class="form-control"> <option value=""> All </option> <option value="Band"> Band </option> <option value="Artist"> Artist </option> </select> </div> <div class="form-group col-md-4"> <label for="genre">Search by genre:</label> <select id="genre" name="genre" class="form-control"> <option value=""> All </option> <option value="Rock"> Rock </option> <option value="Pop"> Pop </option> </select> </div> <div class="form-group col-md-4"> <label for="city">Search by location:</label> <input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value=""> </div> </div> </form> <%if (musicians.length > 0) { %> <h2 class="mt-5">Results:</h2> <ul class="list-unstyled"> <% musicians.forEach(musician => { %> <li class="media my-4"> <a href="/profile/<%= musician.id %>"> <img src="/img/<%= musician.thumbnail || 'avatar.jpg'%>" class="mr-3" alt="Musician profile picture"> </a> <div class="media-body"> <h5 class="mt-0 mb-1"><a href="/profile/<%= musician.id %>"><%= musician.name %></h5></a> <p><strong>Role:</strong> <%= musician.role %></p> <p><strong>Genre:</strong> <%= musician.genre %></p> <p><strong>Location:</strong> <%= musician.city %></p> <p><strong>Available for gigs:</strong> <%= musician.availableForGigs ? 'Yes' : 'No' %></p> </div> </li> <% }) %> </ul> <% } else { %> <h2 class="mt-5">No results found</h2> <% } %> </div> <div class="col-md-4"> <h2>About this site</h2> <p>Welcome to My Musician Site! This is a platform for musicians to connect with each other and find potential bandmates or collaborators. You can search for musicians by name, location, role, and genre. If you're a musician yourself, make sure to create a profile so others can find you too!</p> <p>If you have any questions or feedback, please don't hesitate to contact us at <a href="mailto:contact@mymusiciansite.com">contact@mymusiciansite.com</a>.</p> </div> </div> </main> <script src="/jquery/jquery.min.js"></script> <script src="/jquery-ui/jquery-ui.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1r RibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script> $("#city").autocomplete({ source: '/autocomplete/cities', minLength: 1, }); const queryInput = document.querySelector("#query"); const roleInput = document.querySelector("#role"); const cityInput = document.querySelector("#city"); queryInput.value = "<%= query %>"; roleInput.value = "<%= role %>"; cityInput.value = cityInput.getAttribute('data-value'); const query = queryInput.value; const role = roleInput.value; const city = cityInput.value; </script> </body> </html> profile.ejs: <!DOCTYPE html> <html> <head> <title><%= musician.name %> - Musician Profile</title> <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" /> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <!-- Popper.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Bootstrap JS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <!-- Custom CSS --> <link rel="stylesheet" href="/css/main.css" /> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"> <img src="/img/<%= musician.thumbnail || 'avatar.jpg' %>" alt="<%= musician.name %>" width="200" height="200"> </div> <div class="col-md-8"> <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.city %></p> <p><strong>Bio:</strong> <%= musician.bio %></p> <% if (musician.soundcloud) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (musician.soundcloud1) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (userLoggedIn && username === musician.name) { %> <button type="button" class="btn btn-primary mt-3 mb-3" data-toggle="modal" data-target="#edit-profile-modal">Edit Profile</button> <div id="edit-profile-modal" class="modal fade"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Edit Profile</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<%= musician.name %>" class="form-control"> </div> <div class="form-group"> <label for="role">Role:</label> <select id="role" name="role" class="form-control"> <option value="">Select a role</option> <option value="Band" <%= musician.role === 'Band' ? 'selected' : '' %>>Band</option> <option value="Artist" <%= musician.role === 'Artist' ? 'selected' : '' %>>Artist</option> </select> </div> <div class="form-group"> <label for="genre">Genre:</label> <select id="genre" name="genre" class="form-control"> <option value="">Select a genre</option> <option value="Rock" <%= musician.genre === 'Rock' ? 'selected' : '' %>>Rock</option> <option value="Pop" <%= musician.genre === 'Pop' ? 'selected' : '' %>>Pop</option> <option value="Hip-hop" <%= musician.genre === 'Hip-hop' ? 'selected' : '' %>>Hip-hop</option> <option value="Jazz" <%= musician.genre === 'Jazz' ? 'selected' : '' %>>Jazz</option> <option value="Electronic" <%= musician.genre === 'Electronic' ? 'selected' : '' %>>Electronic</option> <option value="Classical" <%= musician.genre === 'Classical' ? 'selected' : '' %>>Classical</option> </select> </div> <% if (musician.role === 'Artist') { %> <div class="form-group"> <label for="instrument">Instrument:</label> <input type="text" id="instrument" name="instrument" value="<%= musician.instrument || '' %>" class="form-control"> </div> <% } %> <div class="form-group"> <label for="city">Location:</label> <input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="" class="form-control"> </div> <div class="form-group"> <label for="bio">Bio:</label> <textarea id="bio" name="bio" class="form-control"><%= musician.bio %></textarea> </div> <div class="form-group"> <label for="thumbnail">Thumbnail:</label> <input type="file" id="thumbnail" name="thumbnail" accept="image/*" class="form-control-file"> </div> <div class="form-group"> <label for="soundcloud">Soundcloud Track:</label> <input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud || '' %>" class="form-control"> </div> <div class="form-group"> <label for="soundcloud1">Soundcloud Track 2:</label> <input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 || '' %>" class="form-control"> </div> <button type="submit" class="btn btn-primary">Save Changes</button> </form> </div> </div> </div> </div> <% } %> </div> </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> <script> $("#city").autocomplete({ source: '/autocomplete/cities', minLength: 1, }); const queryInput = document.querySelector("#query"); const roleInput = document.querySelector("#role"); const cityInput = document.querySelector("#city"); queryInput.value = "<%= query %>"; roleInput.value = "<%= role %>"; cityInput.value = cityInput.getAttribute('data-value'); const query = queryInput.value; const role = roleInput.value; const city = cityInput.value; </script> </body> </html> 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"); const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'music', // замените на свой логин password: 'password', // замените на свой пароль database: 'music' // замените на свою базу данных }); connection.connect((err) => { if (err) { console.error('Ошибка подключения к базе данных: ', err); } else { console.log('Подключение к базе данных успешно'); } }); 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 citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8")); //const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; function getLastNRegisteredMusicians(N) { const data = fs.readFileSync("./db/musicians.json"); const musicians = JSON.parse(data); return musicians.musicians.slice(-3); } 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 = '', city = '', genre = '') { 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, city: musician.city }; }); let results = []; if (query || role || city || genre) { 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) && (city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim())) && (genre === "" || musician.genre.toLowerCase() === genre.toLowerCase()) ); }).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.city === result.city )) ); } 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); const lastRegisteredMusicians = getLastNRegisteredMusicians(5); res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:''}); }); app.get("/autocomplete/cities", async (req, res) => { const searchString = req.query.term; connection.query( "SELECT city FROM mytable WHERE city LIKE ?", [searchString + '%'], (error, results, fields) => { if (error) { console.error("Ошибка выполнения запроса: ", error); res.status(500).send("Ошибка выполнения запроса"); } else { const cities = results.map(row => row.city); res.json(cities); } } ); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musician.id); } else { res.render("register", { citiesAndRegions, city:'' }); } }); 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, role: req.body.role, city: req.body.city, 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; } const found = citiesAndRegions.find( ({ city }) => city === req.body.city.toLowerCase() ); // Если найдено - сохраняем город и регион, если нет - оставляем только город if (found) { newMusician.city = found.city; newMusician.region = found.region; } else { newMusician.city = req.body.city; newMusician.region = ""; } 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, city:'', query:'', role:'' }); } 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 city = req.query.city || ''; const genre = req.query.genre || ''; let musicians = []; if (query || role || city || genre) { musicians = search(query, role, city, genre); } 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, city: musician.city }; }); } //res.locals.predefinedGenres = predefinedGenres; app.locals.JSON = JSON; res.render('search', { musicians, query, role, city, genre, citiesAndRegions}); //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.city = req.body.city; 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"); });
4cbcc01a498a86e6293d55e88a45cc50
{ "intermediate": 0.3036119043827057, "beginner": 0.4253382980823517, "expert": 0.2710497975349426 }
11,449
show me a construction estimating app in python code
5d0ec4ecbb2463d17c85b04e465c9bb5
{ "intermediate": 0.4997878968715668, "beginner": 0.14237920939922333, "expert": 0.3578329086303711 }
11,450
Подсказка с городами работает в index.ejs, но не работает в модальном окне в profile.ejs: index.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" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" /> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <title>Home</title> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/">My Musician Site</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home</a> </li> <% if (userLoggedIn) { %> <li class="nav-item"> <a class="nav-link" href="/profile/<%= musician.id %>">Hello, <%= username %></a> </li> <li class="nav-item"> <a class="nav-link" href="/logout">Logout</a> </li> <% } else { %> <li class="nav-item"> <a class="nav-link" href="/register">Register</a> </li> <li class="nav-item"> <a class="nav-link" href="/login">Login</a> </li> <% } %> </ul> </div> </nav> </header> <main class="container mt-5"> <div class="row"> <div class="col-md-8"> <!-- добавляет форму с поиском музыкантом --> <form method="get" action="/search"> <div class="form-group"> <label for="query">Search by name or genre:</label> <div class="input-group"> <input id="query" name="query" type="text" class="form-control" value="<%= query %>"> <div class="input-group-append"> <button type="submit" class="btn btn-primary">Search</button> </div> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="role">Search by role:</label> <select id="role" name="role" class="form-control"> <option value=""> All </option> <option value="Band"> Band </option> <option value="Artist"> Artist </option> </select> </div> <div class="form-group col-md-4"> <label for="genre">Search by genre:</label> <select id="genre" name="genre" class="form-control"> <option value=""> All </option> <option value="Rock"> Rock </option> <option value="Pop"> Pop </option> </select> </div> <div class="form-group col-md-4"> <label for="city">Search by location:</label> <input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value=""> </div> </div> </form> <%if (musicians.length > 0) { %> <h2 class="mt-5">Results:</h2> <ul class="list-unstyled"> <% musicians.forEach(musician => { %> <li class="media my-4"> <a href="/profile/<%= musician.id %>"> <img src="/img/<%= musician.thumbnail || 'avatar.jpg'%>" class="mr-3" alt="Musician profile picture"> </a> <div class="media-body"> <h5 class="mt-0 mb-1"><a href="/profile/<%= musician.id %>"><%= musician.name %></h5></a> <p><strong>Role:</strong> <%= musician.role %></p> <p><strong>Genre:</strong> <%= musician.genre %></p> <p><strong>Location:</strong> <%= musician.city %></p> <p><strong>Available for gigs:</strong> <%= musician.availableForGigs ? 'Yes' : 'No' %></p> </div> </li> <% }) %> </ul> <% } else { %> <h2 class="mt-5">No results found</h2> <% } %> </div> <div class="col-md-4"> <h2>About this site</h2> <p>Welcome to My Musician Site! This is a platform for musicians to connect with each other and find potential bandmates or collaborators. You can search for musicians by name, location, role, and genre. If you're a musician yourself, make sure to create a profile so others can find you too!</p> <p>If you have any questions or feedback, please don't hesitate to contact us at <a href="mailto:contact@mymusiciansite.com">contact@mymusiciansite.com</a>.</p> </div> </div> </main> <script src="/jquery/jquery.min.js"></script> <script src="/jquery-ui/jquery-ui.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1r RibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script> $("#city").autocomplete({ source: '/autocomplete/cities', minLength: 1, }); const queryInput = document.querySelector("#query"); const roleInput = document.querySelector("#role"); const cityInput = document.querySelector("#city"); queryInput.value = "<%= query %>"; roleInput.value = "<%= role %>"; cityInput.value = cityInput.getAttribute('data-value'); const query = queryInput.value; const role = roleInput.value; const city = cityInput.value; </script> </body> </html> profile.ejs: <!DOCTYPE html> <html> <head> <title><%= musician.name %> - Musician Profile</title> <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" /> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <!-- Popper.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Bootstrap JS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <!-- Custom CSS --> <link rel="stylesheet" href="/css/main.css" /> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"> <img src="/img/<%= musician.thumbnail || 'avatar.jpg' %>" alt="<%= musician.name %>" width="200" height="200"> </div> <div class="col-md-8"> <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.city %></p> <p><strong>Bio:</strong> <%= musician.bio %></p> <% if (musician.soundcloud) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (musician.soundcloud1) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (userLoggedIn && username === musician.name) { %> <button type="button" class="btn btn-primary mt-3 mb-3" data-toggle="modal" data-target="#edit-profile-modal">Edit Profile</button> <div id="edit-profile-modal" class="modal fade"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Edit Profile</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<%= musician.name %>" class="form-control"> </div> <div class="form-group"> <label for="role">Role:</label> <select id="role" name="role" class="form-control"> <option value="">Select a role</option> <option value="Band" <%= musician.role === 'Band' ? 'selected' : '' %>>Band</option> <option value="Artist" <%= musician.role === 'Artist' ? 'selected' : '' %>>Artist</option> </select> </div> <div class="form-group"> <label for="genre">Genre:</label> <select id="genre" name="genre" class="form-control"> <option value="">Select a genre</option> <option value="Rock" <%= musician.genre === 'Rock' ? 'selected' : '' %>>Rock</option> <option value="Pop" <%= musician.genre === 'Pop' ? 'selected' : '' %>>Pop</option> <option value="Hip-hop" <%= musician.genre === 'Hip-hop' ? 'selected' : '' %>>Hip-hop</option> <option value="Jazz" <%= musician.genre === 'Jazz' ? 'selected' : '' %>>Jazz</option> <option value="Electronic" <%= musician.genre === 'Electronic' ? 'selected' : '' %>>Electronic</option> <option value="Classical" <%= musician.genre === 'Classical' ? 'selected' : '' %>>Classical</option> </select> </div> <% if (musician.role === 'Artist') { %> <div class="form-group"> <label for="instrument">Instrument:</label> <input type="text" id="instrument" name="instrument" value="<%= musician.instrument || '' %>" class="form-control"> </div> <% } %> <div class="form-group"> <label for="city">Location:</label> <input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="" class="form-control"> </div> <div class="form-group"> <label for="bio">Bio:</label> <textarea id="bio" name="bio" class="form-control"><%= musician.bio %></textarea> </div> <div class="form-group"> <label for="thumbnail">Thumbnail:</label> <input type="file" id="thumbnail" name="thumbnail" accept="image/*" class="form-control-file"> </div> <div class="form-group"> <label for="soundcloud">Soundcloud Track:</label> <input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud || '' %>" class="form-control"> </div> <div class="form-group"> <label for="soundcloud1">Soundcloud Track 2:</label> <input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 || '' %>" class="form-control"> </div> <button type="submit" class="btn btn-primary">Save Changes</button> </form> </div> </div> </div> </div> <% } %> </div> </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> <script> $("input[name='city']").autocomplete({ source: '/autocomplete/cities', minLength: 1, }); const queryInput = document.querySelector("#query"); const roleInput = document.querySelector("#role"); const cityInput = document.querySelector("input[name='city']"); queryInput.value = "<%= query %>"; roleInput.value = "<%= role %>"; cityInput.value = cityInput.getAttribute('data-value'); const query = queryInput.value; const role = roleInput.value; const city = cityInput.value; </script> </body> </html> раньше я пробовал селектор #city, но это не помогает. Города находятся как бы за модальным окном
1cd17012f4b61f44b545633ee7da6802
{ "intermediate": 0.31331387162208557, "beginner": 0.5033556818962097, "expert": 0.18333041667938232 }
11,451
Подсказка с городами работает в index.ejs, но не работает в модальном окне в profile.ejs: index.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" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" /> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <title>Home</title> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/">My Musician Site</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home</a> </li> <% if (userLoggedIn) { %> <li class="nav-item"> <a class="nav-link" href="/profile/<%= musician.id %>">Hello, <%= username %></a> </li> <li class="nav-item"> <a class="nav-link" href="/logout">Logout</a> </li> <% } else { %> <li class="nav-item"> <a class="nav-link" href="/register">Register</a> </li> <li class="nav-item"> <a class="nav-link" href="/login">Login</a> </li> <% } %> </ul> </div> </nav> </header> <main class="container mt-5"> <div class="row"> <div class="col-md-8"> <!-- добавляет форму с поиском музыкантом --> <form method="get" action="/search"> <div class="form-group"> <label for="query">Search by name or genre:</label> <div class="input-group"> <input id="query" name="query" type="text" class="form-control" value="<%= query %>"> <div class="input-group-append"> <button type="submit" class="btn btn-primary">Search</button> </div> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="role">Search by role:</label> <select id="role" name="role" class="form-control"> <option value=""> All </option> <option value="Band"> Band </option> <option value="Artist"> Artist </option> </select> </div> <div class="form-group col-md-4"> <label for="genre">Search by genre:</label> <select id="genre" name="genre" class="form-control"> <option value=""> All </option> <option value="Rock"> Rock </option> <option value="Pop"> Pop </option> </select> </div> <div class="form-group col-md-4"> <label for="city">Search by location:</label> <input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value=""> </div> </div> </form> <%if (musicians.length > 0) { %> <h2 class="mt-5">Results:</h2> <ul class="list-unstyled"> <% musicians.forEach(musician => { %> <li class="media my-4"> <a href="/profile/<%= musician.id %>"> <img src="/img/<%= musician.thumbnail || 'avatar.jpg'%>" class="mr-3" alt="Musician profile picture"> </a> <div class="media-body"> <h5 class="mt-0 mb-1"><a href="/profile/<%= musician.id %>"><%= musician.name %></h5></a> <p><strong>Role:</strong> <%= musician.role %></p> <p><strong>Genre:</strong> <%= musician.genre %></p> <p><strong>Location:</strong> <%= musician.city %></p> <p><strong>Available for gigs:</strong> <%= musician.availableForGigs ? 'Yes' : 'No' %></p> </div> </li> <% }) %> </ul> <% } else { %> <h2 class="mt-5">No results found</h2> <% } %> </div> <div class="col-md-4"> <h2>About this site</h2> <p>Welcome to My Musician Site! This is a platform for musicians to connect with each other and find potential bandmates or collaborators. You can search for musicians by name, location, role, and genre. If you're a musician yourself, make sure to create a profile so others can find you too!</p> <p>If you have any questions or feedback, please don't hesitate to contact us at <a href="mailto:contact@mymusiciansite.com">contact@mymusiciansite.com</a>.</p> </div> </div> </main> <script src="/jquery/jquery.min.js"></script> <script src="/jquery-ui/jquery-ui.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1r RibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script> $("#city").autocomplete({ source: '/autocomplete/cities', minLength: 1, }); const queryInput = document.querySelector("#query"); const roleInput = document.querySelector("#role"); const cityInput = document.querySelector("#city"); queryInput.value = "<%= query %>"; roleInput.value = "<%= role %>"; cityInput.value = cityInput.getAttribute('data-value'); const query = queryInput.value; const role = roleInput.value; const city = cityInput.value; </script> </body> </html> profile.ejs: <!DOCTYPE html> <html> <head> <title><%= musician.name %> - Musician Profile</title> <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" /> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <!-- Popper.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Bootstrap JS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <!-- Custom CSS --> <link rel="stylesheet" href="/css/main.css" /> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"> <img src="/img/<%= musician.thumbnail || 'avatar.jpg' %>" alt="<%= musician.name %>" width="200" height="200"> </div> <div class="col-md-8"> <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.city %></p> <p><strong>Bio:</strong> <%= musician.bio %></p> <% if (musician.soundcloud) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (musician.soundcloud1) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (userLoggedIn && username === musician.name) { %> <button type="button" class="btn btn-primary mt-3 mb-3" data-toggle="modal" data-target="#edit-profile-modal">Edit Profile</button> <div id="edit-profile-modal" class="modal fade"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Edit Profile</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<%= musician.name %>" class="form-control"> </div> <div class="form-group"> <label for="role">Role:</label> <select id="role" name="role" class="form-control"> <option value="">Select a role</option> <option value="Band" <%= musician.role === 'Band' ? 'selected' : '' %>>Band</option> <option value="Artist" <%= musician.role === 'Artist' ? 'selected' : '' %>>Artist</option> </select> </div> <div class="form-group"> <label for="genre">Genre:</label> <select id="genre" name="genre" class="form-control"> <option value="">Select a genre</option> <option value="Rock" <%= musician.genre === 'Rock' ? 'selected' : '' %>>Rock</option> <option value="Pop" <%= musician.genre === 'Pop' ? 'selected' : '' %>>Pop</option> <option value="Hip-hop" <%= musician.genre === 'Hip-hop' ? 'selected' : '' %>>Hip-hop</option> <option value="Jazz" <%= musician.genre === 'Jazz' ? 'selected' : '' %>>Jazz</option> <option value="Electronic" <%= musician.genre === 'Electronic' ? 'selected' : '' %>>Electronic</option> <option value="Classical" <%= musician.genre === 'Classical' ? 'selected' : '' %>>Classical</option> </select> </div> <% if (musician.role === 'Artist') { %> <div class="form-group"> <label for="instrument">Instrument:</label> <input type="text" id="instrument" name="instrument" value="<%= musician.instrument || '' %>" class="form-control"> </div> <% } %> <div class="form-group"> <label for="city">Location:</label> <input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="" class="form-control"> </div> <div class="form-group"> <label for="bio">Bio:</label> <textarea id="bio" name="bio" class="form-control"><%= musician.bio %></textarea> </div> <div class="form-group"> <label for="thumbnail">Thumbnail:</label> <input type="file" id="thumbnail" name="thumbnail" accept="image/*" class="form-control-file"> </div> <div class="form-group"> <label for="soundcloud">Soundcloud Track:</label> <input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud || '' %>" class="form-control"> </div> <div class="form-group"> <label for="soundcloud1">Soundcloud Track 2:</label> <input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 || '' %>" class="form-control"> </div> <button type="submit" class="btn btn-primary">Save Changes</button> </form> </div> </div> </div> </div> <% } %> </div> </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> <script> $("input[name='city']").autocomplete({ source: '/autocomplete/cities', minLength: 1, }); const queryInput = document.querySelector("#query"); const roleInput = document.querySelector("#role"); const cityInput = document.querySelector("input[name='city']"); queryInput.value = "<%= query %>"; roleInput.value = "<%= role %>"; cityInput.value = cityInput.getAttribute('data-value'); const query = queryInput.value; const role = roleInput.value; const city = cityInput.value; </script> </body> </html>
32985205af8f0d32ead0ea461b4fb5f4
{ "intermediate": 0.31331387162208557, "beginner": 0.5033556818962097, "expert": 0.18333041667938232 }
11,452
please explain every line seperately
7aea06282f526c79511636743ecc3586
{ "intermediate": 0.3107471764087677, "beginner": 0.4861895740032196, "expert": 0.20306317508220673 }
11,453
QT 6.3.2. Windows 10 (64bit). Драйвер в QT для БД установлен SQLite, как её шифровать?
f7bad9695e055c8d5101e45c2a71bfaf
{ "intermediate": 0.39589792490005493, "beginner": 0.4410535991191864, "expert": 0.16304844617843628 }
11,454
Подсказка с городами не работает в модальном окне в profile.ejs: <!DOCTYPE html> <html> <head> <title><%= musician.name %> - Musician Profile</title> <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" /> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <!-- Popper.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Bootstrap JS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <!-- Custom CSS --> <link rel="stylesheet" href="/css/main.css" /> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"> <img src="/img/<%= musician.thumbnail || 'avatar.jpg' %>" alt="<%= musician.name %>" width="200" height="200"> </div> <div class="col-md-8"> <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.city %></p> <p><strong>Bio:</strong> <%= musician.bio %></p> <% if (musician.soundcloud) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (musician.soundcloud1) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (userLoggedIn && username === musician.name) { %> <button type="button" class="btn btn-primary mt-3 mb-3" data-toggle="modal" data-target="#edit-profile-modal">Edit Profile</button> <div id="edit-profile-modal" class="modal fade"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Edit Profile</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<%= musician.name %>" class="form-control"> </div> <div class="form-group"> <label for="role">Role:</label> <select id="role" name="role" class="form-control"> <option value="">Select a role</option> <option value="Band" <%= musician.role === 'Band' ? 'selected' : '' %>>Band</option> <option value="Artist" <%= musician.role === 'Artist' ? 'selected' : '' %>>Artist</option> </select> </div> <div class="form-group"> <label for="genre">Genre:</label> <select id="genre" name="genre" class="form-control"> <option value="">Select a genre</option> <option value="Rock" <%= musician.genre === 'Rock' ? 'selected' : '' %>>Rock</option> <option value="Pop" <%= musician.genre === 'Pop' ? 'selected' : '' %>>Pop</option> <option value="Hip-hop" <%= musician.genre === 'Hip-hop' ? 'selected' : '' %>>Hip-hop</option> <option value="Jazz" <%= musician.genre === 'Jazz' ? 'selected' : '' %>>Jazz</option> <option value="Electronic" <%= musician.genre === 'Electronic' ? 'selected' : '' %>>Electronic</option> <option value="Classical" <%= musician.genre === 'Classical' ? 'selected' : '' %>>Classical</option> </select> </div> <% if (musician.role === 'Artist') { %> <div class="form-group"> <label for="instrument">Instrument:</label> <input type="text" id="instrument" name="instrument" value="<%= musician.instrument || '' %>" class="form-control"> </div> <% } %> <div class="form-group"> <label for="city">Location:</label> <input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="" class="form-control"> </div> <div class="form-group"> <label for="bio">Bio:</label> <textarea id="bio" name="bio" class="form-control"><%= musician.bio %></textarea> </div> <div class="form-group"> <label for="thumbnail">Thumbnail:</label> <input type="file" id="thumbnail" name="thumbnail" accept="image/*" class="form-control-file"> </div> <div class="form-group"> <label for="soundcloud">Soundcloud Track:</label> <input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud || '' %>" class="form-control"> </div> <div class="form-group"> <label for="soundcloud1">Soundcloud Track 2:</label> <input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 || '' %>" class="form-control"> </div> <button type="submit" class="btn btn-primary">Save Changes</button> </form> </div> </div> </div> </div> <% } %> </div> </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> <script> btn.onclick = function() { modal.style.display = "block"; initAutocomplete(); } function initAutocomplete() { $("input[name='city']").autocomplete({ source: '/autocomplete/cities', minLength: 1, }); } const queryInput = document.querySelector("#query"); const roleInput = document.querySelector("#role"); const cityInput = document.querySelector("input[name='city']"); queryInput.value = "<%= query %>"; roleInput.value = "<%= role %>"; cityInput.value = cityInput.getAttribute('data-value'); const query = queryInput.value; const role = roleInput.value; const city = cityInput.value; </script> </body> </html>
4527eda93bca843f6e28a929f2f89acc
{ "intermediate": 0.1873592734336853, "beginner": 0.6690133213996887, "expert": 0.14362744987010956 }
11,455
Подсказка с городами не работает в модальном окне в profile.ejs: <!DOCTYPE html> <html> <head> <title><%= musician.name %> - Musician Profile</title> <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" /> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <!-- Popper.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Bootstrap JS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <!-- Custom CSS --> <link rel="stylesheet" href="/css/main.css" /> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"> <img src="/img/<%= musician.thumbnail || 'avatar.jpg' %>" alt="<%= musician.name %>" width="200" height="200"> </div> <div class="col-md-8"> <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.city %></p> <p><strong>Bio:</strong> <%= musician.bio %></p> <% if (musician.soundcloud) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (musician.soundcloud1) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (userLoggedIn && username === musician.name) { %> <button type="button" class="btn btn-primary mt-3 mb-3" data-toggle="modal" data-target="#edit-profile-modal">Edit Profile</button> <div id="edit-profile-modal" class="modal fade"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Edit Profile</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<%= musician.name %>" class="form-control"> </div> <div class="form-group"> <label for="role">Role:</label> <select id="role" name="role" class="form-control"> <option value="">Select a role</option> <option value="Band" <%= musician.role === 'Band' ? 'selected' : '' %>>Band</option> <option value="Artist" <%= musician.role === 'Artist' ? 'selected' : '' %>>Artist</option> </select> </div> <div class="form-group"> <label for="genre">Genre:</label> <select id="genre" name="genre" class="form-control"> <option value="">Select a genre</option> <option value="Rock" <%= musician.genre === 'Rock' ? 'selected' : '' %>>Rock</option> <option value="Pop" <%= musician.genre === 'Pop' ? 'selected' : '' %>>Pop</option> <option value="Hip-hop" <%= musician.genre === 'Hip-hop' ? 'selected' : '' %>>Hip-hop</option> <option value="Jazz" <%= musician.genre === 'Jazz' ? 'selected' : '' %>>Jazz</option> <option value="Electronic" <%= musician.genre === 'Electronic' ? 'selected' : '' %>>Electronic</option> <option value="Classical" <%= musician.genre === 'Classical' ? 'selected' : '' %>>Classical</option> </select> </div> <% if (musician.role === 'Artist') { %> <div class="form-group"> <label for="instrument">Instrument:</label> <input type="text" id="instrument" name="instrument" value="<%= musician.instrument || '' %>" class="form-control"> </div> <% } %> <div class="form-group"> <label for="city">Location:</label> <input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="" class="form-control"> </div> <div class="form-group"> <label for="bio">Bio:</label> <textarea id="bio" name="bio" class="form-control"><%= musician.bio %></textarea> </div> <div class="form-group"> <label for="thumbnail">Thumbnail:</label> <input type="file" id="thumbnail" name="thumbnail" accept="image/*" class="form-control-file"> </div> <div class="form-group"> <label for="soundcloud">Soundcloud Track:</label> <input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud || '' %>" class="form-control"> </div> <div class="form-group"> <label for="soundcloud1">Soundcloud Track 2:</label> <input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 || '' %>" class="form-control"> </div> <button type="submit" class="btn btn-primary">Save Changes</button> </form> </div> </div> </div> </div> <% } %> </div> </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> <script> btn.onclick = function() { modal.style.display = "block"; initAutocomplete(); } function initAutocomplete() { $("input[name='city']").autocomplete({ source: '/autocomplete/cities', minLength: 1, }); } const queryInput = document.querySelector("#query"); const roleInput = document.querySelector("#role"); const cityInput = document.querySelector("input[name='city']"); queryInput.value = "<%= query %>"; roleInput.value = "<%= role %>"; cityInput.value = cityInput.getAttribute('data-value'); const query = queryInput.value; const role = roleInput.value; const city = cityInput.value; </script> </body> </html>
9593ad7967d84b8bdc4d436c839e4fc7
{ "intermediate": 0.2283104807138443, "beginner": 0.6675398945808411, "expert": 0.10414963215589523 }
11,456
I have my Database Systems Lab exam tomorrow. help me revise MSSQL syntax.
898968823d6eedc2c05b4a3dd6c8ee7c
{ "intermediate": 0.13769572973251343, "beginner": 0.778226912021637, "expert": 0.0840773656964302 }
11,457
Подсказка с городами не работает в модальном окне в profile.ejs: <!DOCTYPE html> <html> <head> <title><%= musician.name %> - Musician Profile</title> <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" /> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <!-- Popper.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Bootstrap JS --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <!-- Custom CSS --> <link rel="stylesheet" href="/css/main.css" /> </head> <body> <div class="container"> <div class="row"> <div class="col-md-3"> <img src="/img/<%= musician.thumbnail || 'avatar.jpg' %>" alt="<%= musician.name %>" width="200" height="200"> </div> <div class="col-md-8"> <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.city %></p> <p><strong>Bio:</strong> <%= musician.bio %></p> <% if (musician.soundcloud) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (musician.soundcloud1) { %> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" 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> </div> <% } %> <% if (userLoggedIn && username === musician.name) { %> <button type="button" class="btn btn-primary mt-3 mb-3" data-toggle="modal" data-target="#edit-profile-modal">Edit Profile</button> <div id="edit-profile-modal" class="modal fade"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Edit Profile</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="name">Name:</label> <input type="text" id="name" name="name" value="<%= musician.name %>" class="form-control"> </div> <div class="form-group"> <label for="role">Role:</label> <select id="role" name="role" class="form-control"> <option value="">Select a role</option> <option value="Band" <%= musician.role === 'Band' ? 'selected' : '' %>>Band</option> <option value="Artist" <%= musician.role === 'Artist' ? 'selected' : '' %>>Artist</option> </select> </div> <div class="form-group"> <label for="genre">Genre:</label> <select id="genre" name="genre" class="form-control"> <option value="">Select a genre</option> <option value="Rock" <%= musician.genre === 'Rock' ? 'selected' : '' %>>Rock</option> <option value="Pop" <%= musician.genre === 'Pop' ? 'selected' : '' %>>Pop</option> <option value="Hip-hop" <%= musician.genre === 'Hip-hop' ? 'selected' : '' %>>Hip-hop</option> <option value="Jazz" <%= musician.genre === 'Jazz' ? 'selected' : '' %>>Jazz</option> <option value="Electronic" <%= musician.genre === 'Electronic' ? 'selected' : '' %>>Electronic</option> <option value="Classical" <%= musician.genre === 'Classical' ? 'selected' : '' %>>Classical</option> </select> </div> <% if (musician.role === 'Artist') { %> <div class="form-group"> <label for="instrument">Instrument:</label> <input type="text" id="instrument" name="instrument" value="<%= musician.instrument || '' %>" class="form-control"> </div> <% } %> <div class="form-group"> <label for="city">Location:</label> <input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="" class="form-control"> </div> <div class="form-group"> <label for="bio">Bio:</label> <textarea id="bio" name="bio" class="form-control"><%= musician.bio %></textarea> </div> <div class="form-group"> <label for="thumbnail">Thumbnail:</label> <input type="file" id="thumbnail" name="thumbnail" accept="image/*" class="form-control-file"> </div> <div class="form-group"> <label for="soundcloud">Soundcloud Track:</label> <input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud || '' %>" class="form-control"> </div> <div class="form-group"> <label for="soundcloud1">Soundcloud Track 2:</label> <input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 || '' %>" class="form-control"> </div> <button type="submit" class="btn btn-primary">Save Changes</button> </form> </div> </div> </div> </div> <% } %> </div> </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> <script> btn.onclick = function() { modal.style.display = "block"; initAutocomplete(); } function initAutocomplete() { $("input[name='city']").autocomplete({ source: '/autocomplete/cities', minLength: 1, }); } const queryInput = document.querySelector("#query"); const roleInput = document.querySelector("#role"); const cityInput = document.querySelector("input[name='city']"); queryInput.value = "<%= query %>"; roleInput.value = "<%= role %>"; cityInput.value = cityInput.getAttribute('data-value'); const query = queryInput.value; const role = roleInput.value; const city = cityInput.value; </script> </body> </html>
12ac015545c68b5341e5c4fcc4e70826
{ "intermediate": 0.2283104807138443, "beginner": 0.6675398945808411, "expert": 0.10414963215589523 }
11,458
import scipy.stats df= df[['pizza_name','cook_time']] df_filtered = df.groupby('pizza_name').filter(lambda x: len(x) > 100) grouped = df_filtered.groupby('pizza_name') mean = grouped.mean()['cook_time'] std = grouped.std()['cook_time'] alpha = 0.05 t = scipy.stats.t.ppf(1 - alpha/2, len(df_filtered) - 1) CI = t * std / np.sqrt(len(df_filtered)) upper_bound = mean + CI max_CI_pizza = upper_bound.idxmax() print(f"Пицца с самой высокой верхней границей доверительного интервала: {max_CI_pizza}") Зачем мы пишем в коде эту строку grouped
4c2097549f52e8bc22ea83ea47a88692
{ "intermediate": 0.22426097095012665, "beginner": 0.470112681388855, "expert": 0.30562636256217957 }
11,459
#pragma once #include <cstdint> #include <unordered_map> #include <unordered_set> #include <vector> #include <bitset> #include <memory> #include <typeinfo> #include "Archetype.h" #include "EventBus.h" #include "System.h" #include "ComponentMask.h" using ArchetypeId = std::vector<int>; using EntityId = uint32_t; class SystemBase; class ECS { private: using SystemsArrayMap = std::unordered_map<std::uint8_t, std::vector<SystemBase*>>; using ComponentTypeIdBaseMap = std::unordered_map<size_t, ComponentBase*>; struct Record { Archetype* archetype; size_t index; }; using EntityArchetypeMap = std::unordered_map<size_t, Record>; using ArchetypesArray = std::vector<Archetype*>; using ComponentMasks = std::unordered_map<size_t, ComponentMask>; public: explicit ECS(); ~ECS(); void Update(const std::uint8_t layer, const std::uint32_t delta); void RegisterEntity(const EntityId entityId); void DestroyEntity(const EntityId entityId); template <class C> void RegisterComponent(); template <class C> const bool IsComponentRegistered() const; template<class C, typename... Args> C* AddComponent(const EntityId entityId, Args&&... args); template<class C> void RemoveComponent(const EntityId entityId); template<class C> C* GetComponent(const EntityId entityId); const bool HasComponent(const EntityId entityId, size_t compTypeId) const; template<class C> size_t GetComponentTypeId(); template<class C> const bool HasComponent(const EntityId entityId); void RegisterSystem(const std::uint8_t& layer, SystemBase* system); void UnregisterSystem(const std::uint8_t& layer, SystemBase* system); template<class... Cs> std::vector<size_t> GetEntitiesWithComponents(); Archetype* GetArchetype(const ComponentMask& componentMask); EntityId GetNewId(); std::shared_ptr<EventBus> GetEventBus() { return eventBus_; } private: std::shared_ptr<EventBus> eventBus_; EntityId entityIdCounter; SystemsArrayMap systems; EntityArchetypeMap entityArchetypeMap; ArchetypesArray archetypes; ComponentMasks componentMasks; ComponentTypeIdBaseMap componentMap; template<class C, typename... Args> C* TransferComponentsAndAdd(const EntityId entityId, Archetype* newArchetype, Archetype* oldArchetype, Args&&... args); template<class C> void TransferComponentsAndRemove(size_t entityIndex, Archetype* oldArchetype, Archetype* newArchetype); size_t GetEntityIndex(const Archetype* archetype, EntityId entityId); void UpdateRecord(EntityId entityId, Archetype* archetype, Record& record); void UpdateEntitiesInArchetypes(Archetype* oldArchetype, Archetype* newArchetype, EntityId entityId); size_t FindCurrentSize(Archetype* archetype, size_t ComponentTypeIndex, size_t index); void Reallocate(const size_t newComponentDataSize, Archetype* archetype, size_t index); void MoveComponentData(const ComponentBase* componentBase, Archetype* fromArch, Archetype* toArch, size_t fromIndex, size_t toIndex, size_t fromEntityIndex, size_t toEntityIndex); void TransferComponentData(const size_t compTypeIndex, Archetype* fromArch, Archetype* toArch, size_t i, size_t j, size_t entityIndex); void SwapComponentData(const size_t compTypeIndex, Archetype* arch, size_t index, size_t entityIndex); void RemoveAndAllocateComponentData(const size_t compTypeIndex, Archetype* fromArchetype, Archetype* toArchetype, size_t i, size_t j, size_t entityIndex); }; template<class C> void ECS::RegisterComponent() { size_t componentTypeId = Component<C>::GetTypeID(); if (componentMap.contains(componentTypeId)) return; // can't re-register a type componentMap.emplace(componentTypeId, new Component<C>); }; template<class C> const bool ECS::IsComponentRegistered() const { size_t componentTypeId = Component<C>::GetTypeID(); return (componentMap.contains(componentTypeId)); } template<class C, typename... Args> C* ECS::AddComponent(const EntityId entityId, Args&&... args) { // 1. Get the component type ID and check if the component already exists for the entity auto newComponentID = GetTypeID<C>(); if (HasComponent(entityId, newComponentID)) { return nullptr; } // 2. Update the component mask for the entity and get the new archetype componentMasks[entityId].AddComponent(newComponentID); Archetype* newArchetype = GetArchetype(componentMasks[entityId]); // 3. Get and store the record of the entity Record& record = entityArchetypeMap[entityId]; Archetype* oldArchetype = record.archetype; C* newComponent = nullptr; // 4. If the entity has existing components, transfer or add the new component if (oldArchetype) { newComponent = TransferComponentsAndAdd<C>(entityId, newArchetype, oldArchetype, C(std::forward<Args>(args)...)); } // 5. If the entity has no existing components, allocate and add the new component else { size_t currentSize = FindCurrentSize(newArchetype, newComponentID, 0); newComponent = new (&newArchetype->componentData[0][currentSize]) C(std::forward<Args>(args)...); //newComponent = AllocateAndAddComponent<C>(newArchetype, std::forward<Args>(args)...); } // 6. Update the record and return the new component UpdateRecord(entityId, newArchetype, record); return newComponent; } template<class C> void ECS::RemoveComponent(const EntityId entityId) { auto componentID = GetTypeID<C>(); if (!IsComponentRegistered<C>() || !HasComponent(entityId, componentID)) { return; } componentMasks[entityId].RemoveComponent(componentID); Record& record = entityArchetypeMap[entityId]; Archetype* oldArchetype = record.archetype; if (!oldArchetype) { return; } Archetype* newArchetype = GetArchetype(componentMasks[entityId]); size_t entityIndex = GetEntityIndex(oldArchetype, entityId); TransferComponentsAndRemove<C>(entityIndex, oldArchetype, newArchetype); UpdateRecord(entityId, newArchetype, record); } template<class C> C* ECS::GetComponent(const EntityId entityId) { size_t componentTypeId = Component<C>::GetTypeID(); if (!HasComponent(entityId, componentTypeId)) { return nullptr; // Component doesn't exist for the entity } const Archetype* archetype = entityArchetypeMap[entityId].archetype; if (!archetype) { return nullptr; // Archetype doesn't exist for the entity } size_t componentIndex = archetype->componentMask.ReturnArchetypeIndex(componentTypeId); auto entityIterator = std::find( archetype->entityIds.begin(), archetype->entityIds.end(), entityId ); if (entityIterator == archetype->entityIds.end()) { return nullptr; } size_t entityIndex = entityIterator - archetype->entityIds.begin(); size_t componentSize = componentMap[componentTypeId]->GetSize(); C* component = reinterpret_cast<C*>(&archetype->componentData[componentIndex][entityIndex * componentSize]); return component; } template<class C> size_t ECS::GetComponentTypeId() { auto newComponentId = Component<C>::GetTypeID(); return newComponentId; } template<class C> const bool ECS::HasComponent(const EntityId entityId) { return (componentMasks[entityId]).HasComponent(Component<C>::GetTypeID()); } template<class... Cs> std::vector<size_t> ECS::GetEntitiesWithComponents() { std::vector<size_t> entities; ComponentMask mask; ((mask.AddComponent(Component<Cs>::GetTypeID())), ...); for (const auto& [entityId, record] : entityArchetypeMap) { const Archetype* archetype = record.archetype; if (!archetype) { continue; } const ComponentMask& entityMask = componentMasks[entityId]; if (mask.IsSubsetOf(entityMask)) { entities.push_back(entityId); } } return entities; } template<class C, typename... Args> C* ECS::TransferComponentsAndAdd(const EntityId entityId, Archetype* newArchetype, Archetype* oldArchetype, Args&&... args) { auto newComponentMask = newArchetype->componentMask; auto oldComponentMask = oldArchetype->componentMask; C* newComponent = nullptr; size_t entityIndex = GetEntityIndex(oldArchetype, entityId); for (size_t i = 0, fromIndex = 0, toIndex = 0; i < newComponentMask.Size() - 1; ++i) { if (newComponentMask.HasComponent(i)) { size_t currentSize = FindCurrentSize(newArchetype, i, toIndex); if (oldComponentMask.HasComponent(i)) { TransferComponentData(i, oldArchetype, newArchetype, fromIndex, toIndex, entityIndex); ++fromIndex; } else { newComponent = new (&newArchetype->componentData[toIndex][currentSize]) C(std::forward<Args>(args)...); } toIndex++; } } UpdateEntitiesInArchetypes(oldArchetype, newArchetype, entityId); return newComponent; } template<class C> void ECS::TransferComponentsAndRemove(size_t entityIndex, Archetype* oldArchetype, Archetype* newArchetype) { auto oldComponentMask = oldArchetype->componentMask; auto newComponentMask = newArchetype->componentMask; for (size_t i = 0, fromIndex = 0, toIndex = 0; i < oldComponentMask.Size(); ++i) { if (oldComponentMask.HasComponent(i)) { if (newComponentMask.HasComponent(i)) { RemoveAndAllocateComponentData(i, oldArchetype, newArchetype, fromIndex, toIndex, entityIndex); toIndex++; } else { SwapComponentData(i, oldArchetype, toIndex, entityIndex); } fromIndex++; } } std::iter_swap(oldArchetype->entityIds.begin() + entityIndex, oldArchetype->entityIds.end() - 1); oldArchetype->entityIds.pop_back(); } #include "ECS.h" ECS::ECS() : entityIdCounter(1), eventBus_(std::make_shared<EventBus>()) {} ECS::~ECS() { // Clean up dynamically allocated memory and resources for (auto& archetype : archetypes) { delete archetype; } for (auto& component : componentMap) { delete component.second; } for (auto& systemLayer : systems) { for (auto& system : systemLayer.second) { delete system; } } } void ECS::Update(const std::uint8_t layer, const std::uint32_t delta) { for (SystemBase* system : systems[layer]) { const ComponentMask& key = system->GetComponentMask(); for (Archetype* archetype : archetypes) { const ComponentMask& archetypeMask = archetype->componentMask; if (key.IsSubsetOf(archetypeMask)) { system->Update(delta, archetype); } } } } void ECS::RegisterEntity(const EntityId entityId) { entityArchetypeMap[entityId] = Record(nullptr, 0); } void ECS::DestroyEntity(const EntityId entityId) { if (!entityArchetypeMap.contains(entityId)) return; // Entity doesn't exist Record& record = entityArchetypeMap[entityId]; Archetype* oldArchetype = record.archetype; if (!oldArchetype) { entityArchetypeMap.erase(entityId); return; } ComponentMask oldComponentMask = oldArchetype->componentMask; size_t entityIndex = record.index; size_t lastEntityIndex = oldArchetype->entityIds.size() - 1; // Move each component data to the end of the archetype's component data for (size_t i = 0; i < oldComponentMask.Size(); ++i) { if (oldComponentMask.HasComponent(i)) { const ComponentBase* const componentBase = componentMap[i]; if (componentBase == nullptr) continue; size_t componentDataSize = componentBase->GetSize(); auto* componentData = &oldArchetype->componentData[i][entityIndex * componentDataSize]; auto* lastComponentData = &oldArchetype->componentData[i][lastEntityIndex * componentDataSize]; //Move the last entity's component data to the position of the entity being removed componentBase->MoveData(lastComponentData, componentData); //Destroy the component data of the entity being removed componentBase->DestroyData(componentData); } } // Swap the entity being removed with the last entity in the archetype std::swap(oldArchetype->entityIds[entityIndex], oldArchetype->entityIds[lastEntityIndex]); // Pop the last entity from the archetype oldArchetype->entityIds.pop_back(); // Update the entity's record in the entityArchetypeMap record.index = oldArchetype->entityIds.size() - 1; record.archetype = oldArchetype; // If the archetype is empty after removing the entity, remove it from the entityArchetypeMap if (oldArchetype->entityIds.empty()) { entityArchetypeMap.erase(entityId); } } const bool ECS::HasComponent(const EntityId entityId, size_t compTypeId) const { auto iter = componentMasks.find(entityId); if (iter != componentMasks.end()) { return iter->second.HasComponent(compTypeId); } return false; } void ECS::RegisterSystem(const std::uint8_t& layer, SystemBase* system) { systems[layer].push_back(system); } void ECS::UnregisterSystem(const std::uint8_t& layer, SystemBase* system) { auto systemsArrayIt = systems.find(layer); if (systemsArrayIt != systems.end()) { std::vector<SystemBase*>& systemsArray = systemsArrayIt->second; auto systemIt = std::find(systemsArray.begin(), systemsArray.end(), system); if (systemIt != systemsArray.end()) { systemsArray.erase(systemIt); } } } Archetype* ECS::GetArchetype(const ComponentMask& compMask) { for (Archetype* archetype : archetypes) { if (archetype->componentMask.IsExactMatch(compMask)) { return archetype; } } Archetype* newArchetype = new Archetype; newArchetype->componentMask = compMask; for (size_t i = 0; i < compMask.Size(); ++i) { if (compMask.HasComponent(i)) { size_t componentSize = componentMap[i]->GetSize(); newArchetype->componentData.push_back(new unsigned char[componentSize]); newArchetype->componentDataSize.push_back(componentSize); } } archetypes.push_back(newArchetype); return newArchetype; } EntityId ECS::GetNewId() { return entityIdCounter++; }; size_t ECS::GetEntityIndex(const Archetype* archetype, EntityId entityId) { return std::find( archetype->entityIds.begin(), archetype->entityIds.end() - 1, entityId ) - archetype->entityIds.begin(); } void ECS::UpdateRecord(EntityId entityId, Archetype* archetype, Record& record) { archetype->entityIds.push_back(entityId); record.index = archetype->entityIds.size() - 1; record.archetype = archetype; } void ECS::UpdateEntitiesInArchetypes(Archetype* oldArchetype, Archetype* newArchetype, EntityId entityId) { auto lastEntity = oldArchetype->entityIds.size() - 1; auto entityIndex = GetEntityIndex(oldArchetype, entityId); if (!oldArchetype->entityIds.empty() && entityIndex < oldArchetype->entityIds.size()) { std::iter_swap(oldArchetype->entityIds.begin() + entityIndex, oldArchetype->entityIds.begin() + lastEntity); for (std::size_t i = 0, j = 0, index = 0; i < oldArchetype->componentMask.Size() - 1; ++i) { if (oldArchetype->componentMask.HasComponent(i)) { const ComponentBase* const componentBase = componentMap[i]; SwapComponentData(i, oldArchetype, index, entityIndex); ++index; } } // swap the entity leaving the archetype with the one at the end of the list before deleting the leaving entity by popping oldArchetype->entityIds.pop_back(); } } size_t ECS::FindCurrentSize(Archetype* archetype, size_t ComponentTypeIndex, size_t index) { const ComponentBase* componentBase = componentMap[ComponentTypeIndex]; const std::size_t& newCompDataSize = componentBase->GetSize(); std::size_t currentSize = archetype->entityIds.size() * newCompDataSize; std::size_t newSize = currentSize + newCompDataSize; if (newSize > archetype->componentDataSize[index]) { Reallocate(newCompDataSize, archetype, index); } return currentSize; } void ECS::Reallocate(const size_t newComponentDataSize, Archetype* archetype, size_t index) { const ComponentBase* compbase = componentMap[index]; archetype->componentDataSize[index] *= 2; archetype->componentDataSize[index] += newComponentDataSize; unsigned char* newData = new unsigned char[archetype->componentDataSize[index]]; for (auto e = 0; e < archetype->entityIds.size(); ++e) { compbase->MoveData(&archetype->componentData[index][e * newComponentDataSize], &newData[e * newComponentDataSize]); compbase->DestroyData(&archetype->componentData[index][e * newComponentDataSize]); } delete[] archetype->componentData[index]; archetype->componentData[index] = newData; } void ECS::MoveComponentData(const ComponentBase* componentBase, Archetype* fromArch, Archetype* toArch, size_t fromIndex, size_t toIndex, size_t fromEntityIndex, size_t toEntityIndex) { //const ComponentBase* componentBase = componentMap[compTypeIndex]; const std::size_t componentSize = componentBase->GetSize(); componentBase->MoveData(&fromArch->componentData[fromIndex][fromEntityIndex * componentSize], &toArch->componentData[toIndex][toEntityIndex * componentSize]); componentBase->DestroyData(&fromArch->componentData[fromIndex][fromEntityIndex * componentSize]); } void ECS::TransferComponentData(const size_t compTypeIndex, Archetype* fromArch, Archetype* toArch, size_t i, size_t j, size_t entityIndex) { const ComponentBase* componentBase = componentMap[compTypeIndex]; MoveComponentData(componentBase, fromArch, toArch, i, j, entityIndex, toArch->entityIds.size()); } void ECS::SwapComponentData(const size_t compTypeIndex, Archetype* arch, size_t toIndex, size_t entityIndex) { const auto lastEntity = arch->entityIds.size() - 1; const ComponentBase* componentBase = componentMap[compTypeIndex]; MoveComponentData(componentBase, arch, arch, toIndex, toIndex, lastEntity, entityIndex); //const ComponentBase* componentBase = componentMap[compTypeIndex]; //const std::size_t componentSize = componentBase->GetSize(); // //const auto lastEntity = arch->entityIds.size() - 1; // //componentBase->MoveData(&arch->componentData[index][lastEntity * componentSize], // &arch->componentData[index][entityIndex * componentSize]); //componentBase->DestroyData(&arch->componentData[index][lastEntity * componentSize]); } void ECS::RemoveAndAllocateComponentData(const size_t compTypeIndex, Archetype* fromArchetype, Archetype* toArchetype, size_t i, size_t j, size_t entityIndex) { const ComponentBase* const componentBase = componentMap[compTypeIndex]; const std::size_t componentDataSize = componentBase->GetSize(); size_t currentSize = FindCurrentSize(toArchetype, compTypeIndex, j); const size_t lastEntity = fromArchetype->entityIds.size() - 1; componentBase->MoveData(&fromArchetype->componentData[i][entityIndex * componentDataSize], &toArchetype->componentData[j][currentSize]); if (entityIndex != lastEntity) { componentBase->MoveData(&fromArchetype->componentData[i][lastEntity * componentDataSize], &fromArchetype->componentData[i][entityIndex * componentDataSize]); } componentBase->DestroyData(&fromArchetype->componentData[i][lastEntity * componentDataSize]); } Is there a way to create a subclass/helper class that can handle the reallocate/transfer/component management?
0fdfeff99c36ce871c314b3064105e97
{ "intermediate": 0.35279417037963867, "beginner": 0.46088194847106934, "expert": 0.186323881149292 }
11,460
update this code to contain secret client google api fun getDriveService() : Drive?{ GoogleSignIn.getLastSignedInAccount(this)?.let { googleAccount -> val credential = GoogleAccountCredential.usingOAuth2( this, listOf(DriveScopes.DRIVE_FILE) ) credential.selectedAccount = googleAccount.account!! return Drive.Builder( AndroidHttp.newCompatibleTransport(), JacksonFactory.getDefaultInstance(), credential ) .setApplicationName(getString(R.string.app_name)) .build() } return null } kotlin
e462ed7b0c0d02b649729fbdd2fd18f2
{ "intermediate": 0.4557567238807678, "beginner": 0.36625489592552185, "expert": 0.17798829078674316 }
11,461
how to pass metadata from few files with tables to here class PostgresqlManager: def __init__(self): self.engine = create_async_engine(settings.database_url()) self.metadata = Base.metadata self.Session = async_sessionmaker[AsyncSession](self.engine, expire_on_commit=False) async def create_tables(self): async with self.engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) print(Base.metadata.tables.keys())
3b7f35d5f71500c142963a9b7c874f8b
{ "intermediate": 0.5792517066001892, "beginner": 0.3391030430793762, "expert": 0.08164528757333755 }
11,462
let binding = format!("a\tb"); how to get b?
d1ba975f087e4c863ef6a30ff3050099
{ "intermediate": 0.4053996503353119, "beginner": 0.35224494338035583, "expert": 0.2423553168773651 }
11,463
package sample.demo; import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.geometry.Orientation; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.fxml.FXML; import javafx.scene.control.Label; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import javafx.stage.Stage; public class Emp_Student_Controller extends Configs implements Initializable { @FXML private ResourceBundle resources; @FXML private URL location; @FXML private TableView<Student> table; @FXML private TableColumn<Student,String> s_tbl1; @FXML private TableColumn<Student,String> s_tbl10; @FXML private TableColumn<Student,String> s_tbl11; @FXML private TableColumn<Student,String> s_tbl12; @FXML private TableColumn<Student,String> s_tbl2; @FXML private TableColumn<Student,String> s_tbl3; @FXML private TableColumn<Student,String> s_tbl4; @FXML private TableColumn<Student,String> s_tbl5; @FXML private TableColumn<Student,String> s_tbl6; @FXML private TableColumn<Student,String> s_tbl7; @FXML private TableColumn<Student,String> s_tbl8; @FXML private TableColumn<Student,String> s_tbl9; @FXML private ScrollBar scroll; @FXML private Button st_btn_add; @FXML private Button st_btn_delete; @FXML private Button st_btn_update; @FXML private TextField std_f1; @FXML private TextField std_f10; @FXML private TextField std_f11; @FXML private TextField std_f12; @FXML private TextField std_f2; @FXML private TextField std_f3; @FXML private TextField std_f4; @FXML private TextField std_f5; @FXML private TextField std_f6; @FXML private TextField std_f7; @FXML private TextField std_f8; @FXML private TextField std_f9; @FXML private Text std_txt1; @FXML private Text std_txt10; @FXML private Text std_txt11; @FXML private Text std_txt12; @FXML private Text std_txt2; @FXML private Text std_txt3; @FXML private Text std_txt4; @FXML private Text std_txt5; @FXML private Text std_txt6; @FXML private Text std_txt7; @FXML private Text std_txt8; @FXML private Text std_txt9; @FXML private Button emp_st_back_btn; @FXML void Add(ActionEvent event) { String users_id, users_name,users_group_id,users_date,users_address,users_doc_id,users_grade,users_speciality_id,users_form, users_enter,users_graduation,users_payment_method; users_name = std_f2.getText(); users_group_id= std_f3.getText(); users_date= std_f4.getText(); users_address=std_f5.getText() ; users_doc_id=std_f6.getText() ; users_grade=std_f7.getText() ; users_speciality_id=std_f8.getText() ; users_form= std_f9.getText(); users_enter=std_f10.getText() ; users_graduation=std_f11.getText() ; users_payment_method=std_f12.getText(); try { pst = con.prepareStatement("INSERT INTO students.студенты(id_studenta,st_name,id_gruppy,st_birth_date," + "st_address,st_doc_id,st_grade,id_spetsialnosti,st_study_form,st_enter_year," + "st_graduation_year,st_payment_method)VALUES(?,?,?,?,?,?,?,?,?,?,?)"); pst.setString(1, users_name); pst.setString(2, users_group_id); pst.setString(3, users_date); pst.setString(4, users_address); pst.setString(5, users_doc_id); pst.setString(6, users_grade); pst.setString(7, users_speciality_id); pst.setString(8, users_form); pst.setString(9, users_enter); pst.setString(10, users_graduation); pst.setString(11, users_payment_method); pst.executeUpdate(); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Student Registration"); alert.setHeaderText("Student Registration"); alert.setContentText("Record Added!"); alert.showAndWait(); table(); std_f2.setText(""); std_f3.setText(""); std_f4.setText(""); std_f5.setText(""); std_f6.setText(""); std_f7.setText(""); std_f8.setText(""); std_f9.setText(""); std_f10.setText(""); std_f11.setText(""); std_f12.setText(""); std_f2.requestFocus(); } catch (SQLException ex) { Logger.getLogger(Emp_Student_Controller.class.getName()).log(Level.SEVERE, null, ex); } } public void table() { Connect(); ObservableList<Student> students = FXCollections.observableArrayList(); try { pst = con.prepareStatement("select id_studenta,st_name,id_gruppy,st_birth_date," + "st_address,st_doc_id,st_grade,id_spetsialnosti,st_study_form,st_enter_year,st_graduation_year,st_payment_method from students.студенты"); ResultSet rs = pst.executeQuery(); { while (rs.next()) { Student st = new Student(); st.setUsers_id(rs.getString("id_studenta")); st.setUsers_name(rs.getString("st_name")); st.setUsers_group_id(rs.getString("id_gruppy")); st.setUsers_date(rs.getString("st_birth_date")); st.setUsers_address(rs.getString("st_address")); st.setUsers_doc_id(rs.getString("st_doc_id")); st.setUsers_grade(rs.getString("st_grade")); st.setUsers_speciality_id(rs.getString("id_spetsialnosti")); st.setUsers_form(rs.getString("st_study_form")); st.setUsers_enter(rs.getString("st_enter_year")); st.setUsers_graduation(rs.getString("st_graduation_year")); st.setUsers_payment_method(rs.getString("st_payment_method")); students.add(st); } } table.setItems(students); s_tbl1.setCellValueFactory(f -> f.getValue().users_idProperty()); s_tbl2.setCellValueFactory(f -> f.getValue().users_nameProperty()); s_tbl3.setCellValueFactory(f -> f.getValue().users_group_idProperty()); s_tbl4.setCellValueFactory(f -> f.getValue().users_dateProperty()); s_tbl5.setCellValueFactory(f -> f.getValue().users_addressProperty()); s_tbl6.setCellValueFactory(f -> f.getValue().users_doc_idProperty()); s_tbl7.setCellValueFactory(f -> f.getValue().users_gradeProperty()); s_tbl8.setCellValueFactory(f -> f.getValue().users_speciality_idProperty()); s_tbl9.setCellValueFactory(f -> f.getValue().users_formProperty()); s_tbl10.setCellValueFactory(f -> f.getValue().users_enterProperty()); s_tbl11.setCellValueFactory(f -> f.getValue().users_graduationProperty()); s_tbl11.setCellValueFactory(f -> f.getValue().users_payment_methodProperty()); } catch (SQLException ex) { Logger.getLogger(Emp_Student_Controller.class.getName()).log(Level.SEVERE, null, ex); } table.setRowFactory( tv -> { TableRow<Student> myRow = new TableRow<>(); myRow.setOnMouseClicked (event -> { if (event.getClickCount() == 1 && (!myRow.isEmpty())) { myIndex = table.getSelectionModel().getSelectedIndex(); id = Integer.parseInt(String.valueOf(table.getItems().get(myIndex).getUsers_id())); std_f2.setText(table.getItems().get(myIndex).getUsers_name()); std_f3.setText(table.getItems().get(myIndex).getUsers_group_id()); std_f4.setText(table.getItems().get(myIndex).getUsers_date()); std_f5.setText(table.getItems().get(myIndex).getUsers_address()); std_f6.setText(table.getItems().get(myIndex).getUsers_doc_id()); std_f7.setText(table.getItems().get(myIndex).getUsers_grade()); std_f8.setText(table.getItems().get(myIndex).getUsers_speciality_id()); std_f9.setText(table.getItems().get(myIndex).getUsers_form()); std_f10.setText(table.getItems().get(myIndex).getUsers_enter()); std_f11.setText(table.getItems().get(myIndex).getUsers_graduation()); std_f12.setText(table.getItems().get(myIndex).getUsers_payment_method()); } }); return myRow; }); } @FXML void Delete(ActionEvent event) { myIndex = table.getSelectionModel().getSelectedIndex(); id = Integer.parseInt(String.valueOf(table.getItems().get(myIndex).getUsers_id())); try { pst = con.prepareStatement("delete from students.студенты where id = ? "); pst.setInt(1, id); pst.executeUpdate(); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Student Registration"); alert.setHeaderText("Student Registration"); alert.setContentText("Deleted!"); alert.showAndWait(); table(); } catch (SQLException ex) { Logger.getLogger(Emp_Student_Controller.class.getName()).log(Level.SEVERE, null, ex); } } @FXML void Update(ActionEvent event) { String users_name,users_group_id,users_date,users_address,users_doc_id,users_grade,users_speciality_id,users_form, users_enter,users_graduation,users_payment_method; ; myIndex = table.getSelectionModel().getSelectedIndex(); id = Integer.parseInt(String.valueOf(table.getItems().get(myIndex).getUsers_id())); users_name = std_f2.getText(); users_group_id= std_f3.getText(); users_date= std_f4.getText(); users_address=std_f5.getText() ; users_doc_id=std_f6.getText() ; users_grade=std_f7.getText() ; users_speciality_id=std_f8.getText() ; users_form= std_f9.getText(); users_enter=std_f10.getText() ; users_graduation=std_f11.getText() ; users_payment_method=std_f12.getText(); try { pst = con.prepareStatement("update students.студенты " + "set users_name= ?,users_group_id= ? ,users_date = ?,users_address=?,users_doc_id=?," + "users_grade=?,users_speciality_id=?," + "users_form=?,users_enter=?,users_graduation=?,users_payment_method=? where id = ? "); pst.setString(1, users_name); pst.setString(2, users_group_id); pst.setString(3, users_date); pst.setString(4, users_address); pst.setString(5, users_doc_id); pst.setString(6, users_grade); pst.setString(7, users_speciality_id); pst.setString(8, users_form); pst.setString(9, users_enter); pst.setString(10, users_graduation); pst.setString(11, users_payment_method); pst.setInt(12,id); pst.executeUpdate(); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Student Registration"); alert.setHeaderText("Student Registration"); alert.setContentText("Updated!"); alert.showAndWait(); table(); } catch (SQLException ex) { Logger.getLogger(Emp_Student_Controller.class.getName()).log(Level.SEVERE, null, ex); } } Connection con; PreparedStatement pst; int myIndex; int id; public void Connect () { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/students",dbUser,dbPass); } catch (ClassNotFoundException ex) { } catch (SQLException ex) { ex.printStackTrace(); } } @Override public void initialize(URL url, ResourceBundle rb) { initialize_back(); scrolling(); Connect(); table(); } @FXML public void initialize_back() { emp_st_back_btn.setOnAction(event -> { emp_st_back_btn.getScene().getWindow().hide(); FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("second-view.fxml")); try { loader.load(); } catch (IOException e) { throw new RuntimeException(e); } Parent root = loader.getRoot(); Stage stage = new Stage(); stage.setScene(new Scene(root)); stage.showAndWait(); stage.setResizable(false); } ); } @FXML private void scrolling(Stage stage){ BorderPane borderPane = new BorderPane(); ScrollBar scrollBarV= new ScrollBar(); scrollBarV.setOrientation(Orientation.VERTICAL ); ScrollBar scrollBarH= new ScrollBar(); Pane pane=new Pane(); pane.getChildren().add(table); borderPane.setCenter(pane); borderPane.setBottom(scrollBarH); borderPane.setRight(scrollBarV); Scene scene = new Scene(borderPane,1138,347); stage.setScene(scene); stage.show(); } } what's wrong in my controller, why scrollbar doesn't work, and I cant see table columns, how to correct this code
fee0f0c97c8436c39e3d3965b0036eea
{ "intermediate": 0.3129384517669678, "beginner": 0.37639525532722473, "expert": 0.3106662631034851 }
11,464
i want you to make an activity diagram about this info as plantUML the student need to login or register then the website suggest a course then the student will have the ability to post or see the course group or browse the course then the website check if the user joined or not if the student didnt joined then he can enter his information if yes he will have the ability to write about it and join the group then the student info will be sent to the ADMIN and his student ID and name will be sent to the instructer
3cb546e23dc81f75de9d65a1ebc0a835
{ "intermediate": 0.30668511986732483, "beginner": 0.4071178436279297, "expert": 0.2861970067024231 }
11,465
Hii I'm using react native
4524efb26ab9de7fbfad5fd738e4e545
{ "intermediate": 0.5162209868431091, "beginner": 0.24966126680374146, "expert": 0.2341177761554718 }
11,466
In react native I want to navigate to current page and clear the whole page and then create data according to what I want…
f0397e28d9f28fcbcaf1f29b763cd1fa
{ "intermediate": 0.7445575594902039, "beginner": 0.08332402259111404, "expert": 0.17211845517158508 }
11,467
import requests import time API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' TARGET_ADDRESS = '0x81D3Df8b6a3e0fe27C3d44D06fC0E8c32d28FDfA' START_BLOCK = 28980230 RPC_API_URL = 'https://bsc-dataseed.binance.org/' def get_latest_block_number(rpc_api_url): data = { 'jsonrpc': '2.0', 'id': 1, 'method': 'eth_blockNumber', 'params': [], } response = requests.post(rpc_api_url, json=data) if response.status_code == 200: result = response.json() block_number_hex = result.get('result') return int(block_number_hex, 16) if block_number_hex else None return None def get_transactions_from_block(api_key, target_address, start_block, end_block): url = f'https://api.bscscan.com/api?module=account&action=txlist&address={target_address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() return result['result'] if result['status'] == '1' else None return None def process_blocks(start_block, target_address, api_key, rpc_api_url): last_processed_block = start_block while True: latest_block = get_latest_block_number(rpc_api_url) if latest_block is None: print('Error getting latest block number') time.sleep(10) continue for block_number in range(last_processed_block, latest_block + 1): print(f'Processing block {block_number}') transactions = get_transactions_from_block(api_key, target_address, start_block=block_number, end_block=block_number) if transactions: hashes = [tx['hash'] for tx in transactions] for txn_hash in hashes: print(txn_hash) # Use a delay to avoid overloading the server time.sleep(1) last_processed_block = latest_block + 1 # Check for new blocks every minute time.sleep(5) process_blocks(START_BLOCK, TARGET_ADDRESS, API_KEY, RPC_API_URL) This code returns the transaction hash from the page you want. Token address transactions are at https://bscscan.com/token/0x81d3df8b6a3e0fe27c3d44d06fc0e8c32d28fdfa Fix the code so that it looks for transactions on this page
6e5b53f4731cde36348983b8e771f6a7
{ "intermediate": 0.3750518560409546, "beginner": 0.3750722110271454, "expert": 0.24987593293190002 }
11,468
import requests API_KEY = ‘CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS’ def get_first_zero_tx_block(api_key, contract_address): url = f’https://api.bscscan.com/api?module=account&action=txlist&address={contract_address}&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() if result[‘status’] == ‘1’ and result[‘result’]: zero_transactions = [tx for tx in result[‘result’] if tx[‘value’] == ‘0’] sorted_zero_transactions = sorted(zero_transactions, key=lambda x: int(x[‘blockNumber’])) first_zero_transaction = sorted_zero_transactions[0] if sorted_zero_transactions else None if first_zero_transaction: return int(first_zero_transaction[‘blockNumber’]), first_zero_transaction[‘hash’] return None, None if name == “main”: contract_address = input("Enter contract address: “) first_zero_tx_block, first_zero_tx_hash = get_first_zero_tx_block(API_KEY, contract_address) if first_zero_tx_block: print(f"The first zero transaction related to contract {contract_address} occurred at block number {first_zero_tx_block}, transaction hash: {first_zero_tx_hash}.”) else: print(“No zero transaction found related to the given contract address.”) The code above outputs zero, i.e. first transaction on the wrong page. The block number of the first transaction must be determined at https://bscscan.com/token/0x81d3df8b6a3e0fe27c3d44d06fc0e8c32d28fdfa
92f98d6464a3f6abfee177ac4b109368
{ "intermediate": 0.424631804227829, "beginner": 0.41371017694473267, "expert": 0.16165803372859955 }
11,469
import “./App.scss”; import Navbar from “./components/Navbar”; import Sidebar from “./components/Sidebar”; import Home from “./pages/Home”; import { Routes, Route, Outlet, Link } from “react-router-dom”; import UserList from “./pages/UserList”; function App() { return ( <Routes> <Navbar /> <div className=“mainContainer”> <Sidebar /> <Route path=“/” element={<Home />} /> <Route path=“/users” element={<UserList />} /> </div> </Routes> ); } export default App; [Navbar] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>
e9e18cfb3863f313b47a8645151594f2
{ "intermediate": 0.32627901434898376, "beginner": 0.4735650420188904, "expert": 0.20015594363212585 }
11,470
# Выводит номер блока, в котором был создан контракт import requests API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' def get_first_zero_tx_block(api_key, contract_address): url = f'https://api.bscscan.com/api?module=account&action=txlist&address={contract_address}&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() if result['status'] == '1' and result['result']: zero_transactions = [tx for tx in result['result'] if tx['value'] == '0'] sorted_zero_transactions = sorted(zero_transactions, key=lambda x: int(x['blockNumber'])) first_zero_transaction = sorted_zero_transactions[0] if sorted_zero_transactions else None if first_zero_transaction: return int(first_zero_transaction['blockNumber']), first_zero_transaction['hash'] return None, None if __name__ == "__main__": contract_address = input("Enter contract address: ") first_zero_tx_block, first_zero_tx_hash = get_first_zero_tx_block(API_KEY, contract_address) if first_zero_tx_block: print(f"The first zero transaction related to contract {contract_address} occurred at block number {first_zero_tx_block}, transaction hash: {first_zero_tx_hash}.") else: print("No zero transaction found related to the given contract address.") This code returns the transaction block number from the page that is not needed. Token address transactions are at https://bscscan.com/token/0x81d3df8b6a3e0fe27c3d44d06fc0e8c32d28fdfa Transaction hash 0xf1e548f63281601cc43c622a6e7b1c04254387e06c13763c1089d6250e2d0b54 Block number 28980155 Fix the code so that it looks for transactions on this page, finds this hash and displays the block number
e3b1332fad67ac98845752de1f14a783
{ "intermediate": 0.4646618962287903, "beginner": 0.27716299891471863, "expert": 0.25817516446113586 }
11,471
create simple chat server using nodejs and ps1
d27793e3b376c218fe48b0454c0f835d
{ "intermediate": 0.4131343960762024, "beginner": 0.2902919352054596, "expert": 0.2965737283229828 }
11,472
how to make a picture stay in the top left corner of a webpage using css
1e330cf5ff2c50b2bd0c55573cdbfc90
{ "intermediate": 0.3788869082927704, "beginner": 0.3336712419986725, "expert": 0.28744184970855713 }
11,473
# Выводит хэши всех транзакций указанного токена в реальном времени # Нужно указать с какого блока начинается обработка import requests import time API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' TARGET_ADDRESS = '0xa6C2d7788830E5ef286db79295C533F402Cca734' START_BLOCK = 28980230 RPC_API_URL = 'https://bsc-dataseed.binance.org/' def get_latest_block_number(rpc_api_url): data = { 'jsonrpc': '2.0', 'id': 1, 'method': 'eth_blockNumber', 'params': [], } response = requests.post(rpc_api_url, json=data) if response.status_code == 200: result = response.json() block_number_hex = result.get('result') return int(block_number_hex, 16) if block_number_hex else None return None def get_transactions_from_block(api_key, target_address, start_block, end_block): url = f'https://api.bscscan.com/api?module=account&action=txlist&address={target_address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() return result['result'] if result['status'] == '1' else None return None def process_blocks(start_block, target_address, api_key, rpc_api_url): last_processed_block = start_block while True: latest_block = get_latest_block_number(rpc_api_url) if latest_block is None: print('Error getting latest block number') time.sleep(10) continue for block_number in range(last_processed_block, latest_block + 1): print(f'Processing block {block_number}') transactions = get_transactions_from_block(api_key, target_address, start_block=block_number, end_block=block_number) if transactions: hashes = [tx['hash'] for tx in transactions] for txn_hash in hashes: print(txn_hash) # Use a delay to avoid overloading the server time.sleep(1) last_processed_block = latest_block + 1 # Check for new blocks every minute time.sleep(5) process_blocks(START_BLOCK, TARGET_ADDRESS, API_KEY, RPC_API_URL) Change the code above to get its method id instead of the hash of the transaction "0xe8e33700": "Add Liquidity", "0xf305d719": "Add Liquidity ETH", "0xeaaed442": "Add Liquidity BNB", "0x4bb278f3": "finalize", "0x8a8c523c": "Enable Trading", "0xc9567bf9": "Open Trading" "0x07279357": "Lock", "0x6167aa61": "Lock Tokens", "0x8af416f6": "Lock LP Token", "0x715018a6": "renounceOwnership", "0xa57e3141": "Replay Lock
048f9bef3004bfb294c26d704b4706b5
{ "intermediate": 0.306763619184494, "beginner": 0.48415327072143555, "expert": 0.20908313989639282 }
11,474
# Выводит хэши всех транзакций указанного токена в реальном времени # Нужно указать с какого блока начинается обработка import requests import time API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' TARGET_ADDRESS = '0xa6C2d7788830E5ef286db79295C533F402Cca734' START_BLOCK = 28980230 RPC_API_URL = 'https://bsc-dataseed.binance.org/' def get_latest_block_number(rpc_api_url): data = { 'jsonrpc': '2.0', 'id': 1, 'method': 'eth_blockNumber', 'params': [], } response = requests.post(rpc_api_url, json=data) if response.status_code == 200: result = response.json() block_number_hex = result.get('result') return int(block_number_hex, 16) if block_number_hex else None return None def get_transactions_from_block(api_key, target_address, start_block, end_block): url = f'https://api.bscscan.com/api?module=account&action=txlist&address={target_address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() return result['result'] if result['status'] == '1' else None return None def process_blocks(start_block, target_address, api_key, rpc_api_url): last_processed_block = start_block while True: latest_block = get_latest_block_number(rpc_api_url) if latest_block is None: print('Error getting latest block number') time.sleep(10) continue for block_number in range(last_processed_block, latest_block + 1): print(f'Processing block {block_number}') transactions = get_transactions_from_block(api_key, target_address, start_block=block_number, end_block=block_number) if transactions: hashes = [tx['hash'] for tx in transactions] for txn_hash in hashes: print(txn_hash) # Use a delay to avoid overloading the server time.sleep(1) last_processed_block = latest_block + 1 # Check for new blocks every minute time.sleep(5) process_blocks(START_BLOCK, TARGET_ADDRESS, API_KEY, RPC_API_URL) Modify the code above to get the method ids that are present in transactions related to the address "0xe8e33700": "Add Liquidity", "0xf305d719": "Add Liquidity ETH", "0xeaaed442": "Add Liquidity BNB", "0x4bb278f3": "finalize", "0x8a8c523c": "Enable Trading", "0xc9567bf9": "Open Trading" "0x07279357": "Lock", "0x6167aa61": "Lock Tokens", "0x8af416f6": "Lock LP Token", "0x715018a6": "renounceOwnership", "0xa57e3141": "Replay Lock
ddae273442bdda9f019c39ef28b77abb
{ "intermediate": 0.306763619184494, "beginner": 0.48415327072143555, "expert": 0.20908313989639282 }
11,475
Any suggestions for this implementation? Any changes for this? #pragma once #include <unordered_map> #include "Archetype.h" class ComponentManager { private: using ComponentTypeIdBaseMap = std::unordered_map<size_t, ComponentBase*>; public: ComponentManager(const ComponentTypeIdBaseMap& componentMap) : componentMap_(componentMap) {} void TransferComponentData(size_t compTypeId, Archetype* fromArch, Archetype* toArch, size_t i, size_t j, size_t entityIndex); void SwapComponentData(size_t compTypeId, Archetype* arch, size_t toIndex, size_t entityIndex); void RemoveAndAllocateComponentData(size_t compTypeId, Archetype* fromArchetype, Archetype* toArchetype, size_t i, size_t j, size_t entityIndex); size_t FindCurrentSize(size_t compTypeId, Archetype* archetype, size_t index); private: const ComponentTypeIdBaseMap& componentMap_; void Reallocate(size_t compTypeId, size_t newComponentDataSize, Archetype* archetype, size_t index); void MoveComponentData(size_t compTypeId, Archetype* fromArch, Archetype* toArch, size_t fromIndex, size_t toIndex, size_t fromEntityIndex, size_t toEntityIndex); const ComponentBase* getComponentBase(size_t compTypeId) const { auto it = componentMap_.find(compTypeId); if (it != componentMap_.end()) { return it->second; } return nullptr; } }; #include "ComponentManager.h" void ComponentManager::Reallocate(size_t compTypeId, const size_t newComponentDataSize, Archetype* archetype, size_t index) { const ComponentBase* componentBase = getComponentBase(compTypeId); const std::size_t componentDataSize = componentBase->GetSize(); archetype->componentDataSize[index] *= 2; archetype->componentDataSize[index] += newComponentDataSize; unsigned char* newData = new unsigned char[archetype->componentDataSize[index]]; for (auto e = 0; e < archetype->entityIds.size(); ++e) { componentBase->MoveData(&archetype->componentData[index][e * newComponentDataSize], &newData[e * newComponentDataSize]); componentBase->DestroyData(&archetype->componentData[index][e * newComponentDataSize]); } delete[] archetype->componentData[index]; archetype->componentData[index] = newData; } void ComponentManager::TransferComponentData(size_t compTypeId, Archetype* fromArch, Archetype* toArch, size_t i, size_t j, size_t entityIndex) { MoveComponentData(compTypeId, fromArch, toArch, i, j, entityIndex, toArch->entityIds.size()); } void ComponentManager::SwapComponentData(size_t compTypeId, Archetype* arch, size_t toIndex, size_t entityIndex) { const auto lastEntity = arch->entityIds.size() - 1; MoveComponentData(compTypeId, arch, arch, toIndex, toIndex, lastEntity, entityIndex); } void ComponentManager::RemoveAndAllocateComponentData(size_t compTypeId, Archetype* fromArchetype, Archetype* toArchetype, size_t i, size_t j, size_t entityIndex) { const ComponentBase* componentBase = getComponentBase(compTypeId); const std::size_t componentDataSize = componentBase->GetSize(); size_t currentSize = FindCurrentSize(compTypeId, toArchetype, j); const size_t lastEntity = fromArchetype->entityIds.size() - 1; componentBase->MoveData(&fromArchetype->componentData[i][entityIndex * componentDataSize], &toArchetype->componentData[j][currentSize]); if (entityIndex != lastEntity) { componentBase->MoveData(&fromArchetype->componentData[i][lastEntity * componentDataSize], &fromArchetype->componentData[i][entityIndex * componentDataSize]); } componentBase->DestroyData(&fromArchetype->componentData[i][lastEntity * componentDataSize]); } void ComponentManager::MoveComponentData(size_t compTypeId, Archetype* fromArch, Archetype* toArch, size_t fromIndex, size_t toIndex, size_t fromEntityIndex, size_t toEntityIndex) { const ComponentBase* componentBase = getComponentBase(compTypeId); const std::size_t componentDataSize = componentBase->GetSize(); componentBase->MoveData(&fromArch->componentData[fromIndex][fromEntityIndex * componentDataSize], &toArch->componentData[toIndex][toEntityIndex * componentDataSize]); componentBase->DestroyData(&fromArch->componentData[fromIndex][fromEntityIndex * componentDataSize]); } size_t ComponentManager::FindCurrentSize(size_t compTypeId, Archetype* archetype, size_t index) { const ComponentBase* compbase = getComponentBase(compTypeId); const std::size_t& newCompDataSize = compbase->GetSize(); std::size_t currentSize = archetype->entityIds.size() * newCompDataSize; std::size_t newSize = currentSize + newCompDataSize; if (newSize > archetype->componentDataSize[index]) { Reallocate(compTypeId, newCompDataSize, archetype, index); } return currentSize; }
2c98c76915b8b15fcc25edd71a8a16ee
{ "intermediate": 0.4172722101211548, "beginner": 0.36510026454925537, "expert": 0.21762755513191223 }
11,476
<Pressable style={gStyle.goback}> <Text style={gStyle.gobacktxt}>Назад</Text> </Pressable> its react native, i need to do a go back button, how to do it?
8f8b1f58181a7ba4becc17adc72ce84d
{ "intermediate": 0.5928810834884644, "beginner": 0.18749167025089264, "expert": 0.219627246260643 }
11,477
ffmpeg Guessed Channel Layout for Input Stream #0.0 : stereo
5c8102afb1589815eb27bdf2ab460963
{ "intermediate": 0.4361823797225952, "beginner": 0.2770977020263672, "expert": 0.2867198586463928 }
11,478
How to create nested lists in a for loop in Python
923ee932c1cf689b222b5d473144734a
{ "intermediate": 0.3103592097759247, "beginner": 0.5299985408782959, "expert": 0.159642294049263 }
11,479
import requests import time API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' TARGET_ADDRESS = '0x81D3Df8b6a3e0fe27C3d44D06fC0E8c32d28FDfA' START_BLOCK = 28980180 RPC_API_URL = 'https://bsc-dataseed.binance.org/' method_ids = { "0xe8e33700": "Add Liquidity", "0xf305d719": "Add Liquidity ETH", "0xeaaed442": "Add Liquidity BNB", "0x4bb278f3": "finalize", "0x8a8c523c": "Enable Trading", "0xc9567bf9": "Open Trading", "0x07279357": "Lock", "0x6167aa61": "Lock Tokens", "0x8af416f6": "Lock LP Token", "0x715018a6": "renounceOwnership", "0xa57e3141": "Renounce Lock Ownership", } def get_latest_block_number(rpc_api_url): data = { 'jsonrpc': '2.0', 'id': 1, 'method': 'eth_blockNumber', 'params': [], } response = requests.post(rpc_api_url, json=data) if response.status_code == 200: result = response.json() block_number_hex = result.get('result') return int(block_number_hex, 16) if block_number_hex else None return None def get_transactions_from_block(api_key, target_address, start_block, end_block): url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={target_address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() return result['result'] if result['status'] == '1' else None def process_blocks(start_block, target_address, api_key, rpc_api_url): last_processed_block = start_block while True: latest_block = get_latest_block_number(rpc_api_url) if latest_block is None: print('Error getting latest block number') time.sleep(10) continue for block_number in range(last_processed_block, latest_block + 1): print(f'Processing block {block_number}') transactions = get_transactions_from_block(api_key, target_address, start_block=block_number, end_block=block_number) if transactions: method_ids_found = [(tx['hash'], tx['input'][:10]) for tx in transactions] for txn_hash, method_id in method_ids_found: method_name = method_ids.get(method_id) if method_name: print(f"{txn_hash}: {method_name}") # Use a delay to avoid overloading the server time.sleep(1) last_processed_block = latest_block + 1 # Check for new blocks every minute time.sleep(5) process_blocks(START_BLOCK, TARGET_ADDRESS, API_KEY, RPC_API_URL) This code returns the transaction block number from the page that is not needed. Token address transactions are at https://bscscan.com/token/0x81d3df8b6a3e0fe27c3d44d06fc0e8c32d28fdfa Make it so that hashes and methods are displayed when processing blocks.
43cc67cfa09cd59e30ec00191f496828
{ "intermediate": 0.4280276298522949, "beginner": 0.3920075297355652, "expert": 0.17996487021446228 }
11,480
how to join a a string: fios- and join it with a varible called combonation in python3
5324910a61d53296760361917722f4e5
{ "intermediate": 0.440925270318985, "beginner": 0.19614917039871216, "expert": 0.36292555928230286 }
11,481
hi i need to do that when user clicks on Забронировать they can see lil info about that post in their profile import { Text, View, Image, Pressable, ScrollView } from 'react-native'; import { gStyle } from '../styles/style'; import React, {useState, useEffect} from 'react'; import Header from '../components/Header'; import Footer from '../components/Footer'; import { Ionicons, MaterialCommunityIcons } from '@expo/vector-icons'; import { useNavigation } from '@react-navigation/native'; import moment from 'moment'; import {firebase} from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; export default function SignUpForMK({route}) { const [userAuthenticated, setUserAuthenticated] = useState(false); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } }); return unsubscribe; }, []); const {mkData}=route.params; const navigation = useNavigation(); const bookMK=()=>{ const currentUserID=firebase.auth().currentUser.uid; const bookedMKData={ name:mkData.name, time:mkData.time.toDate().toISOString(), image:mkData.image, price:mkData.price }; firebase .database() .ref(`users/${currentUserID}/bookedMK`) .push(bookedMKData) .then(()=>{ navigation.navigate('Profile'); }) } return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <View style={gStyle.SupBox}> <Text style={gStyle.header}>{mkData.name}</Text> <Text style={gStyle.hr}></Text> <Text style={gStyle.SupDate}>{moment(mkData.time.toDate()).format('Do MMM YYYY')}</Text> <View style={gStyle.SupContainer}> <Image source={{uri:mkData.image}} style={gStyle.SupImg} /> <View style={gStyle.SupForm}> <View style={gStyle.SupPrice}> <Text style={gStyle.SupPrice1}>Цена: </Text> <Text style={gStyle.SupNumber}>{mkData.price} Р.</Text> </View> </View> <Text style={gStyle.SupDescription}> {mkData.description} </Text> <Text style={gStyle.SupLine}></Text> <View style={gStyle.SupContaier1}> <View style={gStyle.SupBox1}> <Ionicons name="person-outline" size={30} color="black" /> <Text style={gStyle.SupPerson}>{mkData.person} человек</Text> </View> <View style={gStyle.SupBox1}> <MaterialCommunityIcons name="clock-time-four-outline" size={30} color="black" /> <Text style={gStyle.SupAlarm}>{mkData.timeOfMK} час(а)</Text> </View> </View> <Text style={gStyle.SupLine}></Text> {userAuthenticated ? <Pressable style={gStyle.SupMoreDetails} onPress={()=>navigation.navigate('Profile')} > <Text style={gStyle.SupBtn}>Забронировать</Text> </Pressable> : <Pressable style={gStyle.SupMoreDetails} onPress={()=>navigation.navigate('Auth')} > <Text style={gStyle.SupBtn}>Забронировать</Text> </Pressable> } {/*<Pressable style={gStyle.SupMoreDetails} onPress={bookMK} > <Text style={gStyle.SupBtn}>Забронировать</Text> </Pressable>*/} </View> </View> </View> <Footer/> </ScrollView> </View> ); } import { Text, View, Image, ScrollView, Pressable } from 'react-native'; import Header from '../components/Header'; import Footer from '../components/Footer'; import { gStyle } from '../styles/style'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, {useState, useEffect} from 'react'; import { useNavigation } from '@react-navigation/native'; export default function Profile() { const navigation = useNavigation(); const [userId, setUserId]=useState(null); const [userData, setUserData] = useState(null); const [bookedMK, setBookedMK] = useState([]); useEffect(()=>{ const unsubscribe=firebase.auth().onAuthStateChanged((user)=>{ if(user){ setUserId(user.uid); }else{ setUserId(null); } }); return()=>unsubscribe(); },[]) useEffect(() => { if(userId){ const userRef=firebase.database().ref(`users/${userId}`); userRef.on('value', snapshot=>{ const data = snapshot.val(); setUserData(data); },[userId]); const bookedMKRef = firebase.database().ref(`users/${userId}/bookedMK`); bookedMKRef.on('value', snapshot => { const data = snapshot.val(); if (data) { const mk = Object.values(data); setBookedMK(mk); } else { setBookedMK([]); } }); // Cleanup function which will remove the listeners when the component is unmounted return () => { userRef.off(); bookedMKRef.off(); }; } },[userId]) const handleLogOut = async () => { try { await firebase.auth().signOut(); navigation.navigate('Auth'); } catch (error) { console.error(error); } }; return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <View style={gStyle.ProfileBox}> <View style={gStyle.ProfileGreeting}> <Text style={gStyle.ProfileName}>{userData?.name},</Text> <Text style={gStyle.ProfileHello}>Добро пожаловать в{'\n'}личный кабинет</Text> </View> <View style={gStyle.ProfileBlock}> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Имя</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.name}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Фамилия</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.surname}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Электронная почта</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.email}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Номер телефона</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.phone}</Text> </View> </View> <Pressable style={gStyle.logout} onPress={handleLogOut} > <Text style={gStyle.gobacktxt}>Выйти</Text> </Pressable> </View> </View> <View style={gStyle.ProfilePaidMK}> <Text style={gStyle.ProfilePaid}>Забронированные{'\n'}мастер-классы</Text> <Text style={gStyle.ProfileLine}></Text> {bookedMK.map((mk, index)=>( <View key={index} style={gStyle.ProfileDetails}> <Image source={{uri:mk.image}} style={gStyle.ProfileImg}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK}>{mk.name}</Text> <Text style={gStyle.ProfileDate}>{mk.time}</Text> <Text style={gStyle.ProfilePrice}>Цена: {mk.price} Р.</Text> </View> </View> ))} <Text style={gStyle.ProfileLine}></Text> </View> </View> <Footer/> </ScrollView> </View> ); }
66ac9143aadd2ce1da621d956a464848
{ "intermediate": 0.4235009253025055, "beginner": 0.38871467113494873, "expert": 0.1877843737602234 }
11,482
hi
6ebc613dc1ea319cee56949f2a683aa4
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
11,483
Can you walk me through step by step to create an erc4337 abstract account using solidity? i am an experienced solidity developer
4a54422978e607e56da5cd4ed02e09b8
{ "intermediate": 0.5716914534568787, "beginner": 0.14303307235240936, "expert": 0.285275399684906 }
11,484
What is the proper formatting for this list comprehension in Python: matrix_1 = [[dscr.value for cost_of_debt.value in cost_of_debt_list] for occupancy.value in occupancy_list]
bb0112e71217b7f1fbf81f87228187a0
{ "intermediate": 0.40148717164993286, "beginner": 0.3632069528102875, "expert": 0.23530587553977966 }
11,485
Make a stock market prediction model using lstm for current status weather to buy or sell the stock right now using NIFTY dataset from yfinance : Data Preprocessing Do data preprocess, including data clean, replacing values with percent difference. Export new data which have been preprocessed. Create Labels Create trade decisions in regard to percent change of high and low price. There are 3 trade decisions: sell, buy, hold. These are labels for machine learning later. Explore the data Visualize the count of Buy, Hold, and Sell. Check for any correlation between the future price and the current quarter's features. Get and visualize feature importances using ExtraTreesClassifier. Select top 10 features (respectively correlation and importance) and save into Excel files. Training and prediction of Machine Learning Model Scale the Data. Split the Data. Plot confusion matrix. Fit and Train. Print out Evaluation Metrics. Tune model parameters. Show tuned results and choose optimal result. Model with the best parameters. Show results and confusion matrix from optimum parameters. Save the optimal model we trained into .m file. Classify new data using well-trained models Extract trained classifier and new data for prediction. Preprocess data. Do prediction and analysis result of prediction.
78aa5cb679f49c7bb33e6cd515bf92ca
{ "intermediate": 0.4182319641113281, "beginner": 0.15295475721359253, "expert": 0.42881321907043457 }
11,486
i need to show only day month hours and minutes <Text style={gStyle.ProfileDate}>{new Date(mk.time?.seconds * 1000).toLocaleTimeString()}</Text>
be6d9ab35cc654ee04f33d752cffee2b
{ "intermediate": 0.3958010673522949, "beginner": 0.2598778307437897, "expert": 0.34432119131088257 }
11,487
Can you create a dynamic event queue system that works with types and templates that is dynamic and flexible?
0d8d745be5901f03f00fcafedeee21cb
{ "intermediate": 0.4545234739780426, "beginner": 0.16760700941085815, "expert": 0.37786948680877686 }
11,488
How do I get privategpt from github. The link is https://github.com/imartinez/privateGPT
a8b07613407231f20ba0e0fde70eac69
{ "intermediate": 0.41118323802948, "beginner": 0.15787628293037415, "expert": 0.43094050884246826 }
11,489
Make a stock market prediction model using below code as referance the model must be relable use NIFTY dataset from yfinance: from sklearn.preprocessing import scale import numpy as np from abc import abstractmethod low = -0.01 high = 0.01 def to_category(label): label = np.where(label < low, -1, label) label = np.where(label > high, 1, label) label = np.where(abs(label) != 1, 0, label) label += 1 return label def standardise(data): data = np.nan_to_num(data) return data def print_summary(label): mean = np.mean(label) std = np.std(label) print('MARKET SUMMARY:\n', 'mean=\t', mean, '\tstd=\t', std) print('min=\t', np.min(label), '\tmax=\t', np.max(label)) print('left-outlier=\t', np.sum(label < mean - 3 * std), '\tright-outlier=\t', np.sum(label > mean + 3 * std)) class StrategyBase(object): def __init__(self, train_data, train_label, fit_data, target_filter, train_filter, month, split=None, kernel=None, method='category', pre_acc=1): self.pre_acc = pre_acc self.month = month self.model = None self.predict = None self.method = method self.kernel = kernel self.target_filter = target_filter self.train_filter = train_filter self.num_classes = 3 self.fit_data = standardise(fit_data[target_filter]) self.train_data = standardise(train_data[train_filter]) self.train_label = np.ravel(train_label)[train_filter] # ----------------------------SUMMARY----------------------- print_summary(self.train_label) print('training size(samples\tdata_dim\ttime_steps):') # ----------------------into MULTI-LABEL-------------------- if self.method == 'category': self.train_label = to_category(self.train_label) self.loss = 'categorical_crossentropy' else: self.loss = 'mse' self.train_data = self.train_data.swapaxes(1, 2) self.fit_data = self.fit_data.swapaxes(1, 2) self.samples, self.time_steps, self.data_dim = self.train_data.shape print(self.train_data.shape) print(self.fit_data.shape) if split is not None: self.data_dim1 = split + 1 self.data_dim2 = self.data_dim - self.data_dim1 self.split_data() @abstractmethod def get_model(self, class_weight=None): '''model construct''' @abstractmethod def fit_model(self, class_weight=None): '''model fit''' def get_predict(self): self.predict = self.model.predict(self.fit_data) def fit_predict(self, class_weight=None): if self.month > 1: self.load_models() # NEED OVERLOAD else: self.get_model(class_weight) # NEED IMPLEMENT self.fit_model(class_weight) # NEED IMPLEMENT self.get_predict() # NEED OVERLOAD self.predict_transform() self.save_models() # NEED OVERLOAD def predict_transform(self): if self.method == 'category': if self.predict.ndim > 1: # pre_sum = np.sum(self.predict, axis=1) # self.predict = np.matmul(self.predict, np.array([-1, 0, 1]).T) / pre_sum self.predict = np.argmax(self.predict, axis=1) - 1 # self.predict = to_target(self.predict) else: self.predict -= 1 self.predict = np.ravel(self.predict) predict = np.full(len(self.target_filter), fill_value=-1, dtype=float) predict[self.target_filter] = self.predict self.predict = predict def save_models(self): pass def load_models(self): pass def split_data(self): self.train_data = [ self.train_data[:, :, :self.data_dim1], scale( self.train_data[:, 0, -self.data_dim2:].reshape( [self.train_data.shape[0], -1] ) ) ] self.fit_data = [ self.fit_data[:, :, :self.data_dim1], scale( self.fit_data[:, 0, -self.data_dim2:].reshape( [self.fit_data.shape[0], -1] ) ) ]
fd77a5cc19979119f7f054e879fb4d25
{ "intermediate": 0.33598655462265015, "beginner": 0.4372553527355194, "expert": 0.22675806283950806 }
11,490
import requests import time API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' TARGET_ADDRESS = '0xd69e826715EEf32b243eC240E7b90861d89529fe' START_BLOCK = 28949445 RPC_API_URL = 'https://bsc-dataseed.binance.org/' method_ids = { "0xe8e33700": "Add Liquidity", "0xf305d719": "Add Liquidity ETH", "0xeaaed442": "Add Liquidity BNB", "0x4bb278f3": "finalize", "0x8a8c523c": "Enable Trading", "0xc9567bf9": "Open Trading", "0x07279357": "Lock", "0x6167aa61": "Lock Tokens", "0x8af416f6": "Lock LP Token", "0x715018a6": "renounceOwnership", "0xa57e3141": "Renounce Lock Ownership", } def get_latest_block_number(rpc_api_url): data = { 'jsonrpc': '2.0', 'id': 1, 'method': 'eth_blockNumber', 'params': [], } response = requests.post(rpc_api_url, json=data) if response.status_code == 200: result = response.json() block_number_hex = result.get('result') return int(block_number_hex, 16) if block_number_hex else None return None def get_transactions_from_block(api_key, target_address, start_block, end_block): url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={target_address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() return result['result'] if result['status'] == '1' else None def get_transactions_from_block(api_key, target_address, start_block, end_block): url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={target_address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() return result['result'] if result['status'] == '1' else None def process_blocks(start_block, target_address, api_key, rpc_api_url): last_processed_block = start_block while True: latest_block = get_latest_block_number(rpc_api_url) if latest_block is None: print('Error getting latest block number') time.sleep(10) continue for block_number in range(last_processed_block, latest_block + 1): print(f'Processing block {block_number}') transactions = get_transactions_from_block(api_key, target_address, start_block=block_number, end_block=block_number) if transactions: method_ids_found = [(tx['hash'], tx['input'][:10]) for tx in transactions] for txn_hash, method_id in method_ids_found: method_name = method_ids.get(method_id) if method_name: print(f"{txn_hash}: {method_name}") # Use a delay to avoid overloading the server time.sleep(1) last_processed_block = latest_block + 1 # Check for new blocks every minute time.sleep(5) process_blocks(START_BLOCK, TARGET_ADDRESS, API_KEY, RPC_API_URL) The code above does not return the hash and method id, although there is a transaction in block 28949450 with method id "0xf305d719": "Add Liquidity ETH" I remind you that the transactions are on the page https://bscscan.com/token/0xd69e826715eef32b243ec240e7b90861d89529fe Print me a transaction with hash 0x5ccf26c5e277c8177d9b743ab62011240029746d14aa6cb802e265234deb3e7d Block number 28949450 and method id "0xf305d719": "Add Liquidity ETH"
3c2b819de2c140b853a878a1e6064fa6
{ "intermediate": 0.3518037497997284, "beginner": 0.4135860502719879, "expert": 0.2346101999282837 }
11,491
it doesnt add posts to the profile import { Text, View, Image, Pressable, ScrollView } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import React, {useState, useEffect} from ‘react’; import Header from ‘…/components/Header’; import Footer from ‘…/components/Footer’; import { Ionicons, MaterialCommunityIcons } from ‘@expo/vector-icons’; import { useNavigation } from ‘@react-navigation/native’; import moment from ‘moment’; import {firebase} from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’; export default function SignUpForMK({route}) { const [userAuthenticated, setUserAuthenticated] = useState(false); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } }); return unsubscribe; }, []); const {mkData}=route.params; const navigation = useNavigation(); const bookMK=()=>{ const currentUserID=firebase.auth().currentUser.uid; const bookedMKData={ name:mkData.name, time:mkData.time.toDate().toISOString(), image:mkData.image, price:mkData.price }; firebase .database() .ref(users/${currentUserID}/bookedMK) .push(bookedMKData) .then(()=>{ navigation.navigate(‘Profile’,{bookedMKData}); }) } return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <View style={gStyle.SupBox}> <Text style={gStyle.header}>{mkData.name}</Text> <Text style={gStyle.hr}></Text> <Text style={gStyle.SupDate}>{moment(mkData.time.toDate()).format(‘Do MMM YYYY’)}</Text> <View style={gStyle.SupContainer}> <Image source={{uri:mkData.image}} style={gStyle.SupImg} /> <View style={gStyle.SupForm}> <View style={gStyle.SupPrice}> <Text style={gStyle.SupPrice1}>Цена: </Text> <Text style={gStyle.SupNumber}>{mkData.price} Р.</Text> </View> </View> <Text style={gStyle.SupDescription}> {mkData.description} </Text> <Text style={gStyle.SupLine}></Text> <View style={gStyle.SupContaier1}> <View style={gStyle.SupBox1}> <Ionicons name=“person-outline” size={30} color=“black” /> <Text style={gStyle.SupPerson}>{mkData.person} человек</Text> </View> <View style={gStyle.SupBox1}> <MaterialCommunityIcons name=“clock-time-four-outline” size={30} color=“black” /> <Text style={gStyle.SupAlarm}>{mkData.timeOfMK} час(а)</Text> </View> </View> <Text style={gStyle.SupLine}></Text> {userAuthenticated ? <Pressable style={gStyle.SupMoreDetails} onPress={()=>navigation.navigate(‘Profile’)} > <Text style={gStyle.SupBtn}>Забронировать</Text> </Pressable> : <Pressable style={gStyle.SupMoreDetails} onPress={()=>navigation.navigate(‘Auth’)} > <Text style={gStyle.SupBtn}>Забронировать</Text> </Pressable> } {/<Pressable style={gStyle.SupMoreDetails} onPress={bookMK} > <Text style={gStyle.SupBtn}>Забронировать</Text> </Pressable>/} </View> </View> </View> <Footer/> </ScrollView> </View> ); } import { Text, View, Image, ScrollView, Pressable } from ‘react-native’; import Header from ‘…/components/Header’; import Footer from ‘…/components/Footer’; import { gStyle } from ‘…/styles/style’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’; import React, {useState, useEffect} from ‘react’; import { useNavigation } from ‘@react-navigation/native’; export default function Profile() { const navigation = useNavigation(); const options = { day: ‘numeric’, month: ‘long’, hour: ‘numeric’, minute: ‘numeric’ }; const [userId, setUserId]=useState(null); const [userData, setUserData] = useState(null); const [bookedMK, setBookedMK] = useState([]); useEffect(()=>{ const unsubscribe=firebase.auth().onAuthStateChanged((user)=>{ if(user){ setUserId(user.uid); }else{ setUserId(null); } }); return()=>unsubscribe(); },[]) useEffect(() => { if(userId){ const userRef=firebase.database().ref(users/${userId}); userRef.on(‘value’, snapshot=>{ const data = snapshot.val(); setUserData(data); }); const bookedMKRef = firebase.database().ref(users/${userId}/bookedMK); bookedMKRef.on(‘value’, snapshot => { const data = snapshot.val(); if (data) { const mk = Object.values(data); setBookedMK([]); setBookedMK(mk) } else { setBookedMK([]); } }); // Cleanup function which will remove the listeners when the component is unmounted return () => { userRef.off(); bookedMKRef.off(); }; } },[userId]); const handleLogOut = async () => { try { await firebase.auth().signOut(); navigation.navigate(‘Auth’); } catch (error) { console.error(error); } }; return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <View style={gStyle.ProfileBox}> <View style={gStyle.ProfileGreeting}> <Text style={gStyle.ProfileName}>{userData?.name},</Text> <Text style={gStyle.ProfileHello}>Добро пожаловать в{‘\n’}личный кабинет</Text> </View> <View style={gStyle.ProfileBlock}> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Имя</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.name}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Фамилия</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.surname}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Электронная почта</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.email}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Номер телефона</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.phone}</Text> </View> </View> <Pressable style={gStyle.logout} onPress={handleLogOut} > <Text style={gStyle.gobacktxt}>Выйти</Text> </Pressable> </View> </View> <View style={gStyle.ProfilePaidMK}> <Text style={gStyle.ProfilePaid}>Забронированные{‘\n’}мастер-классы</Text> <Text style={gStyle.ProfileLine}></Text> {bookedMK.map((mk, index)=>( <View key={index} style={gStyle.ProfileDetails}> <Image source={{uri:mk.image}} style={gStyle.ProfileImg}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK}>{mk.name}</Text> <Text style={gStyle.ProfileDate}>{new Date(mk.time?.seconds * 1000).toLocaleTimeString([], options)}</Text> <Text style={gStyle.ProfilePrice}>Цена: {mk.price} Р.</Text> </View> </View> ))} <Text style={gStyle.ProfileLine}></Text> </View> </View> <Footer/> </ScrollView> </View> ); }
4fa167af376bb58ec2d14c42cf414e3e
{ "intermediate": 0.31955486536026, "beginner": 0.38157182931900024, "expert": 0.29887327551841736 }
11,492
where are you?
380ebb4fde1adae3b5fed10705a22191
{ "intermediate": 0.39041128754615784, "beginner": 0.2526722848415375, "expert": 0.3569163978099823 }
11,493
caught SyntaxError: Unexpected end of input at b (jquery.min.js:2:839) at Pe (jquery.min.js:2:48536) at S.fn.init.append (jquery.min.js:2:49887) at S.fn.init.<anonymous> (jquery.min.js:2:50979) at $ (jquery.min.js:2:32392) at S.fn.init.html (jquery.min.js:2:50657) at Object.<anonymous> (jquery.min.js:2:85040) at c (jquery.min.js:2:28294) at Object.fireWith [as resolveWith] (jquery.min.js:2:29039) at l (jquery.min.js:2:79800) b @ jquery.min.js:2 Pe @ jquery.min.js:2 append @ jquery.min.js:2 (anonymous) @ jquery.min.js:2 $ @ jquery.min.js:2 html @ jquery.min.js:2 (anonymous) @ jquery.min.js:2 c @ jquery.min.js:2 fireWith @ jquery.min.js:2 l @ jquery.min.js:2 (anonymous) @ jquery.min.js:2 load (async) send @ jquery.min.js:2 ajax @ jquery.min.js:2 S.fn.load @ jquery.min.js:2 (anonymous) @ admin:86
07b2923b84a49b9328b17dc73d402ddb
{ "intermediate": 0.3288387358188629, "beginner": 0.43749701976776123, "expert": 0.23366425931453705 }
11,494
write a python script to solve "3(9−2)+( 24/2)3" using the order of operations
e5dc8691900c859c4240bd92027cff68
{ "intermediate": 0.30490487813949585, "beginner": 0.257413387298584, "expert": 0.4376817047595978 }
11,495
async getCategoriesWithSub(): Promise<CategoryDto[]> { const categories = await this.categoryRepository .createQueryBuilder('category') .leftJoinAndSelect('category.parentCategory', 'parentCategory') .leftJoinAndSelect('category.subCategories', 'subCategory') .where('category.parentCategory IS NULL') .orWhere('category.parentCategory IS NOT NULL') .getMany(); return categories.map((category) => new CategoryDto(category)); } how can i update this code so that it returns Only categories with their related subcategories are needed (or an empty array of subcategories if there are none) like this { "id": 1, "name": "test 1 cat", "color": 1, "parentCategory": null, "subCategories": [ { "id": 3, "name": "test 1 scat", "color": 1, "parentCategory": null, "subCategories": [] } ] }
df5d154bb96f7f883dea9b7b0e198685
{ "intermediate": 0.6560574769973755, "beginner": 0.19759535789489746, "expert": 0.14634718000888824 }
11,496
изменяю buton_add но услоие срабатвает по прожнему с первой кнопкой button_add.addEventListener("click", function () { console.log(button_add); var row = table.insertRow(); // Добавляем новую строку for (var i = 0; i < cols - 1; i++) { var cell = row.insertCell(i); var input = document.createElement("input"); input.className = "input-table input-table-add rows-tb_2-" + (rows-1); input.type = "text"; input.placeholder = attribute_placeholder[i]; cell.appendChild(input); ini Copy } console.log(rows - 1); console.log(cols); var btn_cell = row.insertCell(cols-1); btn_cell.setAttribute('class', 'button'); var buttonPlus = document.createElement("button"); buttonPlus.id = "plus-" + (rows-1); buttonPlus.className = "plus button-icon"; var iconPlus = document.createElement("i"); iconPlus.className = "fa fa-plus"; buttonPlus.appendChild(iconPlus); btn_cell.appendChild(buttonPlus); var buttonSave = document.createElement("button"); buttonSave.id = "save-tb2-" + (rows-1); buttonSave.className = "save-tb-2 save-css button-icon"; var iconSave = document.createElement("i"); iconSave.className = "fa fa-floppy-o"; buttonSave.appendChild(iconSave); btn_cell.appendChild(buttonSave); // button_add.setAttribute("disabled", true); button_add = document.getElementById("plus-" + (rows-1)); console.log(button_add); rows++; }); for (let i = 0; i < buttons_save_2.length; i++) { buttons_save_2[i].addEventListener("click", function () { buttons_save_2[i].setAttribute("disabled", true); var inputs = document.querySelectorAll(".rows-tb_2-" + i); for (let j = 0; j < cols-1; j++){ inputs[j].setAttribute("disabled", true); } }); };
680568def36b6d1a42b448439437e5b1
{ "intermediate": 0.33824241161346436, "beginner": 0.4079182744026184, "expert": 0.2538392245769501 }
11,497
How to overcome this error in the code: Error: WARNING:tensorflow:Layer lstm will not use cuDNN kernels since it doesn't meet the criteria. It will use a generic GPU kernel as fallback when running on GPU. WARNING:tensorflow:Layer lstm_1 will not use cuDNN kernels since it doesn't meet the criteria. It will use a generic GPU kernel as fallback when running on GPU. Epoch 1/50 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-18-a88e8efe60eb> in <cell line: 12>() 10 11 X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1)) ---> 12 model.fit(X_train, y_train, epochs=50, verbose=1) 1 frames /usr/local/lib/python3.10/dist-packages/keras/engine/training.py in tf__train_function(iterator) 13 try: 14 do_return = True ---> 15 retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope) 16 except: 17 do_return = False ValueError: in user code: File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1284, in train_function * return step_function(self, iterator) File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1268, in step_function ** outputs = model.distribute_strategy.run(run_step, args=(data,)) File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1249, in run_step ** outputs = model.train_step(data) File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1050, in train_step y_pred = self(x, training=True) File "/usr/local/lib/python3.10/dist-packages/keras/utils/traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "/usr/local/lib/python3.10/dist-packages/keras/engine/input_spec.py", line 298, in assert_input_compatibility raise ValueError( ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 8, 1), found shape=(None, 9, 1) Code: import yfinance as yf import pandas as pd import numpy as np nifty_df = yf.download('^NSEI', start='2009-01-01', end='2021-12-31') # Clean the data nifty_df = nifty_df.dropna() # Calculate various percent differences nifty_df['PctOpenClose'] = (nifty_df['Close'] - nifty_df['Open']) / nifty_df['Open'] * 100 nifty_df['PctHighLow'] = (nifty_df['High'] - nifty_df['Low']) / nifty_df['Low'] * 100 nifty_df['PctChange'] = nifty_df['Close'].pct_change() * 100 # Remove the first row with NaN in 'PctChange' nifty_df = nifty_df.iloc[1:] # Export cleaned dataset nifty_df.to_csv('nifty_cleaned.csv') def create_labels(df, col_name, threshold=0.5): labels = [] for index, row in df.iterrows(): future_price = row[col_name] if future_price >= threshold: labels.append(1) # Buy elif future_price <= -threshold: labels.append(-1) # Sell else: labels.append(0) # Hold return labels nifty_df['Labels'] = create_labels(nifty_df, 'PctChange') import matplotlib.pyplot as plt import seaborn as sns sns.countplot(nifty_df['Labels']) plt.title('Count of Buy, Hold, and Sell') plt.xlabel('Trade Decisions') plt.ylabel('Count') plt.show() from sklearn.ensemble import ExtraTreesClassifier X = nifty_df.drop(['Labels'], axis=1) y = nifty_df['Labels'] # Fit the ExtraTreesClassifier et_clf = ExtraTreesClassifier() et_clf.fit(X, y) # Visualize feature importances feature_importances = pd.Series(et_clf.feature_importances_, index=X.columns) feature_importances.nlargest(10).plot(kind='barh') plt.show() from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaled_X = scaler.fit_transform(X) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size=0.2, random_state=42) from keras.models import Sequential from keras.layers import LSTM, Dense model = Sequential() model.add(LSTM(100, activation='relu', return_sequences=True, input_shape=(8, 1))) model.add(LSTM(100, activation='relu')) model.add(Dense(3)) model.compile(optimizer='adam', loss='mse') X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1)) model.fit(X_train, y_train, epochs=50, verbose=1) from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, accuracy_score X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1)) y_pred = model.predict(X_test) print(“Confusion Matrix:”) print(confusion_matrix(y_test, y_pred)) print(“\nEvaluation Metrics:”) print("Accuracy: ", accuracy_score(y_test, y_pred)) print("Precision: ", precision_score(y_test, y_pred, average=‘macro’)) print("Recall: ", recall_score(y_test, y_pred, average=‘macro’)) print("F1-Score: ", f1_score(y_test, y_pred, average=‘macro’)) model.save(‘nifty_lstm_model.h5’) # Import the necessary libraries from keras.models import load_model # Load the trained model trained_model = load_model(‘nifty_lstm_model.h5’) # Load the new dataset for prediction new_data = pd.read_csv(‘new_data.csv’) # Preprocess the new dataset preprocessed_new_data = preprocess_data(new_data) # Assumes the same preprocessing is applied as before # Predict predicted_labels = trained_model.predict(preprocessed_new_data)
b6fc8b7868a63f5c33a48ebdfb2f135f
{ "intermediate": 0.3924053907394409, "beginner": 0.3677555322647095, "expert": 0.2398390918970108 }
11,498
cloudflare
d5bdedf1e81856877100686ca526c41f
{ "intermediate": 0.3925948143005371, "beginner": 0.3200324475765228, "expert": 0.28737276792526245 }
11,499
Modify this code in this code the model should consider past 100 values in LSTM also add some more LSTM layers with 0.2 dropout value: import yfinance as yf import pandas as pd import numpy as np nifty_df = yf.download('^NSEI', start='2009-01-01', end='2021-12-31') # Clean the data nifty_df = nifty_df.dropna() # Calculate various percent differences nifty_df['PctOpenClose'] = (nifty_df['Close'] - nifty_df['Open']) / nifty_df['Open'] * 100 nifty_df['PctHighLow'] = (nifty_df['High'] - nifty_df['Low']) / nifty_df['Low'] * 100 nifty_df['PctChange'] = nifty_df['Close'].pct_change() * 100 # Remove the first row with NaN in 'PctChange' nifty_df = nifty_df.iloc[1:] # Export cleaned dataset nifty_df.to_csv('nifty_cleaned.csv') def create_labels(df, col_name, threshold=0.5): labels = [] for index, row in df.iterrows(): future_price = row[col_name] if future_price >= threshold: labels.append(1) # Buy elif future_price <= -threshold: labels.append(-1) # Sell else: labels.append(0) # Hold return labels nifty_df['Labels'] = create_labels(nifty_df, 'PctChange') import matplotlib.pyplot as plt import seaborn as sns sns.countplot(nifty_df['Labels']) plt.title('Count of Buy, Hold, and Sell') plt.xlabel('Trade Decisions') plt.ylabel('Count') plt.show() from sklearn.ensemble import ExtraTreesClassifier X = nifty_df.drop(['Labels'], axis=1) y = nifty_df['Labels'] # Fit the ExtraTreesClassifier et_clf = ExtraTreesClassifier() et_clf.fit(X, y) # Visualize feature importances feature_importances = pd.Series(et_clf.feature_importances_, index=X.columns) feature_importances.nlargest(10).plot(kind='barh') plt.show() important_features = feature_importances.nlargest(8).index.tolist() X_filtered = X[important_features] X_filtered from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaled_X = scaler.fit_transform(X_filtered) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size=0.2, random_state=42) from keras.models import Sequential from keras.layers import LSTM, Dense model = Sequential() model.add(LSTM(100, activation='relu', return_sequences=True, input_shape=(8, 1))) model.add(LSTM(100, activation='relu')) model.add(Dense(3)) model.compile(optimizer='adam', loss='mse') X_train = X_train.reshape((X_train.shape[0], X_train.shape[1], 1)) model.fit(X_train, y_train, epochs=200, verbose=1) from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, accuracy_score X_test = X_test.reshape((X_test.shape[0], X_test.shape[1], 1)) y_pred = model.predict(X_test) # Convert continuous output values to integer class labels y_pred_labels = np.argmax(y_pred, axis=1) - 1 # Subtract 1 to map back to -1, 0, 1 print("Confusion Matrix:") print(confusion_matrix(y_test, y_pred_labels)) print("\n Evaluation Metrics:") print("Accuracy: ", accuracy_score(y_test, y_pred_labels)) print("Precision: ", precision_score(y_test, y_pred_labels, average='macro')) print("Recall: ", recall_score(y_test, y_pred_labels, average='macro')) print("F1-Score: ", f1_score(y_test, y_pred_labels, average='macro')) model.save('nifty_lstm_model.h5') # Import the necessary libraries from keras.models import load_model # Load the trained model trained_model = load_model('nifty_lstm_model.h5') # Load the new dataset for prediction new_data = pd.read_csv('new_data.csv') # Preprocess the new dataset preprocessed_new_data = preprocess_data(new_data) # Assumes the same preprocessing is applied as before # Predict predicted_labels = trained_model.predict(preprocessed_new_data)
ee973f8c1adab9d973eb4077f37b2a17
{ "intermediate": 0.3715135157108307, "beginner": 0.36885395646095276, "expert": 0.25963252782821655 }
11,500
In python 3. Create a game where the player should guess a random number between 1 and 100. The game should be re-playable, the number of guesses should be counted each run and a high score should be kept and updated each run.
0fe64b8f5e23ebf1c1682a4217609f1f
{ "intermediate": 0.3718843162059784, "beginner": 0.19541582465171814, "expert": 0.4326997995376587 }
11,501
hey
9de09f40324be99558be631aa4e1dbb3
{ "intermediate": 0.33180856704711914, "beginner": 0.2916048467159271, "expert": 0.3765866458415985 }
11,502
import "./App.scss"; import Navbar from "./components/Navbar"; import Sidebar from "./components/Sidebar"; import Home from "./pages/Home"; import { Routes, Route } from "react-router-dom"; import UserList from "./pages/UserList"; import User from "./pages/UserList"; function App() { return ( <> <Navbar /> <div className="mainContainer"> <Sidebar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/users" element={<UserList />} /> <Route path="/user" element={<User />} /> </Routes> </div> </> ); } export default App; how to change Route to pick exact path?
66e1daefd634f0049212c2f0f760ed26
{ "intermediate": 0.5059278607368469, "beginner": 0.26317304372787476, "expert": 0.2308991402387619 }
11,503
when user adds mk its info displays in theirs profile and i need that person can delete it import { Text, View, Image, ScrollView, Pressable } from 'react-native'; import Header from '../components/Header'; import Footer from '../components/Footer'; import { gStyle } from '../styles/style'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, {useState, useEffect} from 'react'; import { useNavigation } from '@react-navigation/native'; export default function Profile() { const navigation = useNavigation(); const options = { day: 'numeric', month: 'long', hour: 'numeric', minute: 'numeric' }; const [userId, setUserId]=useState(null); const [userData, setUserData] = useState(null); const [bookedMK, setBookedMK] = useState([]); useEffect(()=>{ const unsubscribe=firebase.auth().onAuthStateChanged((user)=>{ if(user){ setUserId(user.uid); }else{ setUserId(null); } }); return()=>unsubscribe(); },[]) useEffect(() => { if(userId){ const userRef=firebase.database().ref(`users/${userId}`); userRef.on('value', snapshot=>{ const data = snapshot.val(); setUserData(data); }); const bookedMKRef = firebase.database().ref(`users/${userId}/bookedMK`); bookedMKRef.on('value', snapshot => { const data = snapshot.val(); if (data) { const mk = Object.values(data); setBookedMK([]); setBookedMK(mk) } else { setBookedMK([]); } }); // Cleanup function which will remove the listeners when the component is unmounted return () => { userRef.off(); bookedMKRef.off(); }; } },[userId]); const handleLogOut = async () => { try { await firebase.auth().signOut(); navigation.navigate('Auth'); } catch (error) { console.error(error); } }; return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <View style={gStyle.ProfileBox}> <View style={gStyle.ProfileGreeting}> <Text style={gStyle.ProfileName}>{userData?.name},</Text> <Text style={gStyle.ProfileHello}>Добро пожаловать в{'\n'}личный кабинет</Text> </View> <View style={gStyle.ProfileBlock}> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Имя</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.name}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Фамилия</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.surname}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Электронная почта</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.email}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Номер телефона</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.phone}</Text> </View> </View> <Pressable style={gStyle.logout} onPress={handleLogOut} > <Text style={gStyle.gobacktxt}>Выйти</Text> </Pressable> </View> </View> <View style={gStyle.ProfilePaidMK}> <Text style={gStyle.ProfilePaid}>Забронированные{'\n'}мастер-классы</Text> <Text style={gStyle.ProfileLine}></Text> {bookedMK.map((mk, index)=>( <View key={index} style={gStyle.ProfileDetails}> <Image source={{uri:mk.image}} style={gStyle.ProfileImg}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK}>{mk.name}</Text> <Text style={gStyle.ProfileDate}>{new Date(mk.time?.seconds * 1000).toLocaleTimeString([], options)}</Text> <Text style={gStyle.ProfilePrice}>Цена: {mk.price} Р.</Text> </View> </View> ))} <Text style={gStyle.ProfileLine}></Text> </View> </View> <Footer/> </ScrollView> </View> ); }
461dbac2b4110d70b06e3429323df99b
{ "intermediate": 0.47442910075187683, "beginner": 0.38445767760276794, "expert": 0.14111319184303284 }
11,504
import "./App.scss"; import Navbar from "./components/Navbar"; import Sidebar from "./components/Sidebar"; import Home from "./pages/Home"; import { Routes, Route } from "react-router-dom"; import UserList from "./pages/UserList"; import User from "./pages/UserList"; function App() { return ( <> <Navbar /> <div className="mainContainer"> <Sidebar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/users" element={<UserList />} /> <Route path="/user" element={<User />} {...(true ? { exact: true } : {})} /> </Routes> </div> </> ); } export default App; why <Route path="/users" element={<UserList />} /> <Route path="/user" element={<User />} {...(true ? { exact: true } : {})} /> are giving the same output?
1cd23d8b672154daeac43c15a3a33fed
{ "intermediate": 0.46264344453811646, "beginner": 0.4252539575099945, "expert": 0.11210260540246964 }
11,505
how to add a password to bash script
a0e8929c2b249f149840888959f5f2f9
{ "intermediate": 0.3465871214866638, "beginner": 0.357265830039978, "expert": 0.2961469888687134 }
11,506
how to add a password to bash script
d8737ee0c0fc524066943b370ad891e0
{ "intermediate": 0.3465871214866638, "beginner": 0.357265830039978, "expert": 0.2961469888687134 }
11,507
How to overcome this error: ERROR: Epoch 1/200 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-59-a2314fc7168e> in <cell line: 15>() 13 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) 14 ---> 15 model.fit(X_train, y_train, epochs=200, verbose=1) 1 frames /usr/local/lib/python3.10/dist-packages/keras/engine/training.py in tf__train_function(iterator) 13 try: 14 do_return = True ---> 15 retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope) 16 except: 17 do_return = False ValueError: in user code: File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1284, in train_function * return step_function(self, iterator) File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1268, in step_function ** outputs = model.distribute_strategy.run(run_step, args=(data,)) File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1249, in run_step ** outputs = model.train_step(data) File "/usr/local/lib/python3.10/dist-packages/keras/engine/training.py", line 1050, in train_step y_pred = self(x, training=True) File "/usr/local/lib/python3.10/dist-packages/keras/utils/traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "/usr/local/lib/python3.10/dist-packages/keras/engine/input_spec.py", line 298, in assert_input_compatibility raise ValueError( ValueError: Input 0 of layer "sequential_4" is incompatible with the layer: expected shape=(None, 100, 8), found shape=(None, 8) Code: import yfinance as yf import pandas as pd import numpy as np nifty_df = yf.download('^NSEI', start='2009-01-01', end='2021-12-31') # Clean the data nifty_df = nifty_df.dropna() # Calculate various percent differences nifty_df['PctOpenClose'] = (nifty_df['Close'] - nifty_df['Open']) / nifty_df['Open'] * 100 nifty_df['PctHighLow'] = (nifty_df['High'] - nifty_df['Low']) / nifty_df['Low'] * 100 nifty_df['PctChange'] = nifty_df['Close'].pct_change() * 100 # Remove the first row with NaN in 'PctChange' nifty_df = nifty_df.iloc[1:] # Export cleaned dataset nifty_df.to_csv('nifty_cleaned.csv') def create_labels(df, col_name, threshold=0.5): labels = [] for index, row in df.iterrows(): future_price = row[col_name] if future_price >= threshold: labels.append(1) # Buy elif future_price <= -threshold: labels.append(-1) # Sell else: labels.append(0) # Hold return labels nifty_df['Labels'] = create_labels(nifty_df, 'PctChange') import matplotlib.pyplot as plt import seaborn as sns sns.countplot(nifty_df['Labels']) plt.title('Count of Buy, Hold, and Sell') plt.xlabel('Trade Decisions') plt.ylabel('Count') plt.show() from sklearn.ensemble import ExtraTreesClassifier X = nifty_df.drop(['Labels'], axis=1) y = nifty_df['Labels'] # Fit the ExtraTreesClassifier et_clf = ExtraTreesClassifier() et_clf.fit(X, y) # Visualize feature importances feature_importances = pd.Series(et_clf.feature_importances_, index=X.columns) feature_importances.nlargest(10).plot(kind='barh') plt.show() important_features = feature_importances.nlargest(8).index.tolist() X_filtered = X[important_features] X_filtered from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaled_X = scaler.fit_transform(X_filtered) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size=0.2, random_state=42) from keras.models import Sequential from keras.layers import LSTM, Dense, Dropout look_back = 100 def create_dataset(X, y, look_back=100): dataX, dataY = [], [] for i in range(len(X)-look_back-1): dataX.append(X[i:(i+look_back), :]) dataY.append(y[i + look_back]) return np.array(dataX), np.array(dataY) X_train_lstm, y_train_lstm = create_dataset(X_train, y_train, look_back) X_test_lstm, y_test_lstm = create_dataset(X_test, y_test, look_back) from keras.models import Sequential from keras.layers import LSTM, Dense model = Sequential() model.add(LSTM(100, activation='relu', return_sequences=True, input_shape=(look_back, 8))) model.add(Dropout(0.2)) model.add(LSTM(100, activation='relu', return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(100, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(3, activation='softmax')) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(X_train, y_train, epochs=200, verbose=1) from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, accuracy_score y_pred = model.predict(X_test_lstm) y_pred_labels = np.argmax(y_pred, axis=1) - 1 print("Confusion Matrix:") print(confusion_matrix(y_test_lstm, y_pred_labels)) print("\n Evaluation Metrics:") print("Accuracy: ", accuracy_score(y_test_lstm, y_pred_labels)) print("Precision: ", precision_score(y_test_lstm, y_pred_labels, average='macro')) print("Recall: ", recall_score(y_test_lstm, y_pred_labels, average='macro')) print("F1-Score: ", f1_score(y_test_lstm, y_pred_labels, average='macro')) model.save('nifty_lstm_model.h5') # Import the necessary libraries from keras.models import load_model # Load the trained model trained_model = load_model('nifty_lstm_model.h5') # Load the new dataset for prediction new_data = pd.read_csv('new_data.csv') # Preprocess the new dataset preprocessed_new_data = preprocess_data(new_data) # Assumes the same preprocessing is applied as before # Predict predicted_labels = trained_model.predict(preprocessed_new_data)
99262a2bf95cae356a47ba9458ad7472
{ "intermediate": 0.3466014862060547, "beginner": 0.31763309240341187, "expert": 0.33576536178588867 }
11,508
This is about 0-1 knapsack problem Alan wants to buy and resell cost is c_i for i th item profit is 2^i total money alan has is integer X Find the maximum profit for X given report answer after taking modulo maxProfit % (10^9+7) Solve Java calculateMaximumProfit(List<Integer> cost,int x)
e968b3a7342eb27c212a316e7ac534a5
{ "intermediate": 0.5222166776657104, "beginner": 0.31067314743995667, "expert": 0.16711021959781647 }
11,509
что это значит new OpenAirConfigurator().Configure(modelBuilder);
8fcc90917a0487f3aad057bebe0ecfcd
{ "intermediate": 0.36177578568458557, "beginner": 0.23835891485214233, "expert": 0.39986535906791687 }
11,510
In this code The problem im facing with my code is that the loss value is becoming "nan" (not a number) during the training process. This can happen due to several reasons, such as incorrect data preprocessing, inappropriate choice of activation functions or loss function, or numerical instability in the model. Here are a few suggestions to help you overcome this problem: Check the data preprocessing: Ensure that the data preprocessing steps are correct and consistent. Make sure you are handling missing values appropriately and scaling the data properly. Double-check the input and output dimensions to the model. Use appropriate activation functions: The choice of activation functions can have an impact on the stability of the model during training. In your code, you are using the "softmax" activation function in the last layer, which is suitable for multi-class classification problems. However, since you are using "sparse_categorical_crossentropy" as the loss function, make sure your labels are integers and not one-hot encoded. If your labels are already one-hot encoded, consider changing the loss function to "categorical_crossentropy". Adjust learning rate and optimizer: Experiment with different learning rates and optimizers to find the optimal combination for your model. You can try reducing the learning rate or using different optimizers such as RMSprop or SGD to see if it helps stabilize the training process. Regularize the model: Overfitting can also lead to instability during training. You can try adding regularization techniques such as dropout or L2 regularization to the LSTM layers to prevent overfitting and improve the stability of the training process. Increase the number of training samples: If you have a small dataset, it can lead to unstable training. Consider gathering more data if possible or apply data augmentation techniques to increase the size of your training set. Check for numerical instability: Large or unnormalized values in the input data can lead to numerical instability. Apply appropriate scaling techniques such as normalization or standardization to ensure the input values are within a reasonable range. Debug step by step: Start by training the model with a small number of epochs and check if the loss value remains stable or becomes "nan". If it remains stable, gradually increase the number of epochs to identify at which point the loss becomes "nan". This can help identify if there is a specific issue with the data or model architecture.| Code: import yfinance as yf import pandas as pd import numpy as np nifty_df = yf.download('^NSEI', start='2009-01-01', end='2021-12-31') # Clean the data nifty_df = nifty_df.dropna() # Calculate various percent differences nifty_df['PctOpenClose'] = (nifty_df['Close'] - nifty_df['Open']) / nifty_df['Open'] * 100 nifty_df['PctHighLow'] = (nifty_df['High'] - nifty_df['Low']) / nifty_df['Low'] * 100 nifty_df['PctChange'] = nifty_df['Close'].pct_change() * 100 # Remove the first row with NaN in 'PctChange' nifty_df = nifty_df.iloc[1:] # Export cleaned dataset nifty_df.to_csv('nifty_cleaned.csv') def create_labels(df, col_name, threshold=0.5): labels = [] for index, row in df.iterrows(): future_price = row[col_name] if future_price >= threshold: labels.append(1) # Buy elif future_price <= -threshold: labels.append(-1) # Sell else: labels.append(0) # Hold return labels nifty_df['Labels'] = create_labels(nifty_df, 'PctChange') import matplotlib.pyplot as plt import seaborn as sns sns.countplot(nifty_df['Labels']) plt.title('Count of Buy, Hold, and Sell') plt.xlabel('Trade Decisions') plt.ylabel('Count') plt.show() from sklearn.ensemble import ExtraTreesClassifier X = nifty_df.drop(['Labels'], axis=1) y = nifty_df['Labels'] # Fit the ExtraTreesClassifier et_clf = ExtraTreesClassifier() et_clf.fit(X, y) # Visualize feature importances feature_importances = pd.Series(et_clf.feature_importances_, index=X.columns) feature_importances.nlargest(10).plot(kind='barh') plt.show() important_features = feature_importances.nlargest(8).index.tolist() X_filtered = X[important_features] X_filtered from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaled_X = scaler.fit_transform(X_filtered) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size=0.2, random_state=42) from keras.models import Sequential from keras.layers import LSTM, Dense, Dropout look_back = 20 def create_dataset(X, y, look_back=100): dataX, dataY = [], [] for i in range(len(X)-look_back-1): dataX.append(X[i:(i+look_back), :]) dataY.append(y[i + look_back]) return np.array(dataX), np.array(dataY) X_train_lstm, y_train_lstm = create_dataset(X_train, y_train, look_back) X_test_lstm, y_test_lstm = create_dataset(X_test, y_test, look_back) from keras.models import Sequential from keras.layers import LSTM, Dense model = Sequential() model.add(LSTM(100, activation='relu', return_sequences=True, input_shape=(look_back, 8))) model.add(Dropout(0.2)) model.add(LSTM(100, activation='relu', return_sequences=True)) model.add(Dropout(0.2)) model.add(LSTM(100, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(3, activation='softmax')) from keras.optimizers import Adam optimizer = Adam(clipvalue=1.0) model.compile(optimizer='SGD', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(X_train_lstm, y_train_lstm, epochs=200, verbose=1) from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, accuracy_score y_pred = model.predict(X_test_lstm) y_pred_labels = np.argmax(y_pred, axis=1) - 1 print("Confusion Matrix:") print(confusion_matrix(y_test_lstm, y_pred_labels)) print("\n Evaluation Metrics:") print("Accuracy: ", accuracy_score(y_test_lstm, y_pred_labels)) print("Precision: ", precision_score(y_test_lstm, y_pred_labels, average='macro')) print("Recall: ", recall_score(y_test_lstm, y_pred_labels, average='macro')) print("F1-Score: ", f1_score(y_test_lstm, y_pred_labels, average='macro')) model.save('nifty_lstm_model.h5') # Import the necessary libraries from keras.models import load_model # Load the trained model trained_model = load_model('nifty_lstm_model.h5') # Load the new dataset for prediction new_data = pd.read_csv('new_data.csv') # Preprocess the new dataset preprocessed_new_data = preprocess_data(new_data) # Assumes the same preprocessing is applied as before # Predict predicted_labels = trained_model.predict(preprocessed_new_data)
f5d06905bf22af66a517693f18b3a9c2
{ "intermediate": 0.43779417872428894, "beginner": 0.32183584570884705, "expert": 0.2403699904680252 }
11,511
Give a powerpoint presentation template with a wide variety of slides and visuals in the style of Bain & Company
7d92257593d07e463232602ad9090373
{ "intermediate": 0.3707665801048279, "beginner": 0.23263724148273468, "expert": 0.39659616351127625 }
11,512
ERROR ReferenceError: Property ‘index’ doesn’t exist import { Text, View, Image, ScrollView, Pressable } from ‘react-native’; import Header from ‘…/components/Header’; import Footer from ‘…/components/Footer’; import { gStyle } from ‘…/styles/style’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’; import React, {useState, useEffect} from ‘react’; import { useNavigation } from ‘@react-navigation/native’; import BookedMK from ‘…/components/BookedMK’; export default function Profile() { const navigation = useNavigation(); const [userId, setUserId]=useState(null); const [userData, setUserData] = useState(null); const [bookedMK, setBookedMK] = useState([]); useEffect(()=>{ const unsubscribe=firebase.auth().onAuthStateChanged((user)=>{ if(user){ setUserId(user.uid); }else{ setUserId(null); } }); return()=>unsubscribe(); },[]) useEffect(() => { if(userId){ const userRef=firebase.database().ref(users/${userId}); userRef.on(‘value’, snapshot=>{ const data = snapshot.val(); setUserData(data); }); const bookedMKRef = firebase.database().ref(users/${userId}/bookedMK); bookedMKRef.on(‘value’, (snapshot) => { const data = snapshot.val(); if (data) { const mk = Object.entries(data).map(([index, mk])=>({…mk, index})); setBookedMK(mk) } else { setBookedMK([]); } }); // Cleanup function which will remove the listeners when the component is unmounted return () => { userRef.off(); bookedMKRef.off(); }; } },[userId]); const handleDeleteBookedMK=(mkIndex)=>{ const updatedBookedMK=bookedMK.filter(mk=>mk.index !==mkIndex); setBookedMK(updatedBookedMK); } const handleLogOut = async () => { try { await firebase.auth().signOut(); navigation.navigate(‘Auth’); } catch (error) { console.error(error); } }; return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <View style={gStyle.ProfileBox}> <View style={gStyle.ProfileGreeting}> <Text style={gStyle.ProfileName}>{userData?.name},</Text> <Text style={gStyle.ProfileHello}>Добро пожаловать в{‘\n’}личный кабинет</Text> </View> <View style={gStyle.ProfileBlock}> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Имя</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.name}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Фамилия</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.surname}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Электронная почта</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.email}</Text> </View> </View> <View style={gStyle.ProfileChain}> <Text style={gStyle.ProfileTitle}>Номер телефона</Text> <View style={gStyle.ProfileInfo}> <Text style={gStyle.ProfileValue}>{userData?.phone}</Text> </View> </View> <Pressable style={gStyle.logout} onPress={handleLogOut} > <Text style={gStyle.gobacktxt}>Выйти</Text> </Pressable> </View> </View> {bookedMK.map((mk)=>( <BookedMK key={mk.index} mk={mk} userId={userId} onDelete={handleDeleteBookedMK} /> ))} </View> <Footer/> </ScrollView> </View> ); } import { Text, View, Image, Pressable } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import { firebase } from ‘…/Firebase/firebase’; import React, {useState, useEffect} from ‘react’; const options = { day: ‘numeric’, month: ‘long’, hour: ‘numeric’, minute: ‘numeric’ }; export default function BookedMK(props) { const {mk, userId, onDelete} = props; const handleDeleteBookedMK=()=>{ const userRef=firebase.database().ref(users/${userId}/bookedMK/${mk.index}); userRef.remove().then(()=>{ onDelete(mk.index); }).catch((error)=>{ console.error(error); }) } //const [userId, setUserId]=useState(null); //const [userData, setUserData] = useState(null); //const [bookedMK, setBookedMK] = useState([]); //useEffect(()=>{ //const unsubscribe=firebase.auth().onAuthStateChanged((user)=>{ //if(user){ //setUserId(user.uid); //}else{ //setUserId(null); //} //}); //return()=>unsubscribe(); //},[]) //useEffect(() => { //if(userId){ // const userRef=firebase.database().ref(users/${userId}); // userRef.on(‘value’, snapshot=>{ // const data = snapshot.val(); // setUserData(data); //}); //const bookedMKRef = firebase.database().ref(users/${userId}/bookedMK); // bookedMKRef.on(‘value’, snapshot => { // const data = snapshot.val(); // if (data) { // const mk = Object.values(data); // setBookedMK([]); // setBookedMK(mk) // } else { // setBookedMK([]); // } // }); // return () => { // userRef.off(); // bookedMKRef.off(); // }; // } // },[userId]); return ( <View style={gStyle.ProfilePaidMK}> <Text style={gStyle.ProfilePaid}>Забронированные{‘\n’}мастер-классы</Text> <Text style={gStyle.ProfileLine}></Text> <View key={index} style={gStyle.ProfileDetails}> <Image source={{uri:mk.image}} style={gStyle.ProfileImg}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK}>{mk.name}</Text> <Text style={gStyle.ProfileDate}>{new Date(mk.time?.seconds * 1000).toLocaleTimeString([], options)}</Text> <Text style={gStyle.ProfilePrice}>Цена: {mk.price} Р.</Text> </View> </View> <Pressable onPress={handleDeleteBookedMK} > <Text>Убрать</Text> </Pressable> <Text style={gStyle.ProfileLine}></Text> </View> ); }
cde9a35e3d38ddd460bc47243bf93774
{ "intermediate": 0.40178167819976807, "beginner": 0.408939391374588, "expert": 0.18927891552448273 }
11,513
hey i have code in c for stm32f103c6 and i want you to help me understand it
68e84ece36105eeaff03b5c72beeaade
{ "intermediate": 0.28327101469039917, "beginner": 0.39590519666671753, "expert": 0.3208237886428833 }
11,514
Another question Java classes Acquaintanc friend best friend Best friend> friend> acquaintance Class acquaintance has attribute name as string. Constructor: Acquaintance (String name) Has method public void getStatus that print "[name] is just \n" Class friend inherits class acquaintance Constructor: Friend (String name, String homeTown) Has attribute "homeTown' as string Class Best friend inherits friend Constructor: BestFriend(String name, String homeTown, String favouriteSong) has attribute favoriteSong
3e3d70087d41e287d2a59a610335f5d9
{ "intermediate": 0.29469773173332214, "beginner": 0.6439756751060486, "expert": 0.061326585710048676 }
11,515
import { Text, View, Image, Pressable } from 'react-native'; import { gStyle } from '../styles/style'; import { firebase } from '../Firebase/firebase'; import React, {useState, useEffect} from 'react'; const options = { day: 'numeric', month: 'long', hour: 'numeric', minute: 'numeric' }; export default function BookedMK(props) { const {mk, userId, onDelete, index} = props; const {time, ...mkData}=mk; let formattedTime=null; if(time?.seconds){ formattedTime = new Date(time.seconds * 1000).toLocaleTimeString([], options); } const handleDeleteBookedMK=()=>{ const userRef=firebase.database().ref(`users/${userId}/bookedMK/${mk.index}`); userRef.remove().then(()=>{ onDelete(mk.index); }).catch((error)=>{ console.error(error); }) } return ( <View style={gStyle.bookedMK}> <Text style={gStyle.ProfileLine}></Text> <View key={index} style={gStyle.ProfileDetails}> <Image source={{uri:mkData.image}} style={gStyle.ProfileImg}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK}>{mkData.name}</Text> <Text style={gStyle.ProfileDate}>{formattedTime}</Text> <Text style={gStyle.ProfilePrice}>Цена: {mkData.price} Р.</Text> </View> </View> <Pressable onPress={handleDeleteBookedMK} > <Text>Убрать</Text> </Pressable> <Text style={gStyle.ProfileLine}></Text> </View> ); } now it doesnt show time at all
46c226ccda567fe00d88f922db77847b
{ "intermediate": 0.3723260760307312, "beginner": 0.3568670153617859, "expert": 0.2708069086074829 }
11,516
this is about 0-1 knapsack problem. Alan wants to buy and resell cost is c_i for i th item profit is 2^i. Total money Alan has is int X. find the maximum profit for X given report answer after taking modulo maxProfit % (10^9 + 7)
267ca76cdc4cccd11d96263d5a65e7b6
{ "intermediate": 0.37125176191329956, "beginner": 0.40326640009880066, "expert": 0.22548185288906097 }
11,517
C# programm after compilation get error code 0x800B010A
045a36e20a6b8df1f52f79cb6bf3e3ec
{ "intermediate": 0.3887682259082794, "beginner": 0.2993469834327698, "expert": 0.3118848502635956 }
11,518
im going to give you a case study i want you to make the following things for a report 1- (Identification and analysis of candidate solutions 2 Recommended solution) 2- (Creation of DFDs) Case Study: A few years ago, Ronald Montgomery founded Cultural Learning Experiences (CLE), Inc., a small firm in Chicago that organizes and plans educational trips for faculty and students seeking a unique learning experience abroad. At first, the company focused mainly on organizing these educational experiences in France and Switzerland, but as the interest continued to grow, Ronald increased the scope of operations to include many other countries, including Spain, New Zealand, Germany, and others. Ronald has the help of Isabella Aubel (office manager) and two other employees that help with the day-to-day office tasks. At the present time, the work processes are entirely manual for this organization. With the recent growth in the business, it has become quite challenging for the current workforce to manage all of this manually. Everything is rather disorganized, with many mistakes being made with the recording of important information regarding students and their scheduled classes and locations, for example. Such errors are adding to the existing inefficiencies, thereby creating a work. An environment that is stressful and hectic. Even more importantly, customer needs are not being met and customer satisfaction is at an all-time low. Therefore, necessary to implement a database solution at the present time. It is important to note that while Ronald intends to eventually automate all business processes, including payroll and accounts payable, the more immediate concern is to ensure that data storage efficiencies are improved. The database solution should include a user-friendly interface that allows for entry, modification, and deletion of data pertaining to students, teachers, and classes, for example. Additionally, the database solution should be designed to ensure consistency of data entry (formatting) and should include enhanced reporting capabilities. Such functionalities should be considered in order to resolve the problems the company is currently experiencing. The total amount available to fund this project is $65,000. It may be possible to expand this budget, if necessary, but the company is hoping that the project can be completed within the specified amount. The company currently has only two computers, both with the Windows 7 operating system and Microsoft Office Professional 2010 installed. The machine is currently being used for electronic mail communications and simple word processing and spreadsheet 2 tasks. It will be necessary to purchase two additional machines for this office, as Ronald would like all of his employees to have access to the new database management system. Ronald is hoping that this database solution will be instrumental in improving customer relations and employee morale, as both are critical to the continued success and growth of his business. With an automated work process, Ronald knows that efficiencies within the organization will be dramatically improved. Cultural Learning Experiences, Inc. is essentially the middleman between faculty and students & international opportunities to teach and learn. CLE organizes educational trips/programs for college students (to take) and college professors (to teach/lead) in the USA and across the world. You have been hired to provide them a means to keep track of the classes offered in destinations around the world, all of the students who sign up for a particular class, the professors who are teaching specific courses, etc. You have several goals that you want to accomplish with this database. First, you will need to keep track of all the students –their student ID number, address, telephone number, e-mail address, etc. You will need to keep track of faculty members and their contact information as well. As students register for classes and pay their registration fees, the owners of CLE want to be able to record this information directly in their database. An outside accounting firm handles all of the billing processes. CLE simply provides this firm with a physical copy of a report containing the information necessary for billing. (Your team is responsible for designing this report.) All payments are made directly to CLE. Beyond the recording of whether or not the registration fees have been paid, this system should be concerned with something other than accounting practices. The recording of all billing and payment details will be handled outside of the boundaries of this system. CLE also outsources the marketing function and provides reports on a regular basis to an outside marketing firm that seeks to inform potential faculty participants of the educational trips that are available through CLE and to increase awareness in general. You should design at least one report that would provide helpful information to this marketing firm. (You may make assumptions here.) CLE would like the database to be password protected. Beyond the creation of these reports, Ronald wants you to focus on making data entry as easy and efficient as possible for her staff while simultaneously ensuring the accuracy of the entries. An organized database, focusing on data entry and reporting, is essential. (Your team will need to explore various options within Access that will allow for this)
1e903d0981a324dc7886b2d6e5559e89
{ "intermediate": 0.30692368745803833, "beginner": 0.40977102518081665, "expert": 0.2833053767681122 }
11,519
# Выводит хэши всех транзакций указанного токена в реальном времени # Нужно указать с какого блока начинается обработка # Только для контрактов созданных на платформе UNCX import requests import time API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' TARGET_ADDRESS = '0xd69e826715EEf32b243eC240E7b90861d89529fe' START_BLOCK = 28949445 RPC_API_URL = 'https://bsc-dataseed.binance.org/' def get_latest_block_number(rpc_api_url): data = { 'jsonrpc': '2.0', 'id': 1, 'method': 'eth_blockNumber', 'params': [], } response = requests.post(rpc_api_url, json=data) if response.status_code == 200: result = response.json() block_number_hex = result.get('result') return int(block_number_hex, 16) if block_number_hex else None return None def get_transactions_from_block(api_key, target_address, start_block, end_block): url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={target_address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() return result['result'] if result['status'] == '1' else None def process_blocks(start_block, target_address, api_key, rpc_api_url): last_processed_block = start_block while True: latest_block = get_latest_block_number(rpc_api_url) if latest_block is None: print('Error getting latest block number') time.sleep(10) continue for block_number in range(last_processed_block, latest_block + 1): print(f'Processing block {block_number}') transactions = get_transactions_from_block(api_key, target_address, start_block=block_number, end_block=block_number) if transactions: hashes = [tx['hash'] for tx in transactions] for txn_hash in hashes: print(txn_hash) # Use a delay to avoid overloading the server time.sleep(1) last_processed_block = latest_block + 1 # Check for new blocks every minute time.sleep(5) process_blocks(START_BLOCK, TARGET_ADDRESS, API_KEY, RPC_API_URL) The code above returns a hash located in block 28949450 there is a transaction with method id "0xf305d719": "Add Liquidity ETH" The code below does not return a hash and method id, although there is a transaction in block 28949450 with method id "0xf305d719": "Add Liquidity ETH" I remind you that the transactions are on the page https://bscscan.com/token/0xd69e826715eef32b243ec240e7b90861d89529fe Print me a transaction with hash 0x5ccf26c5e277c8177d9b743ab62011240029746d14aa6cb802e265234deb3e7d Block number import requests import time API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' TARGET_ADDRESS = '0xd69e826715EEf32b243eC240E7b90861d89529fe' START_BLOCK = 28949445 RPC_API_URL = 'https://bsc-dataseed.binance.org/' method_ids = { "0xe8e33700": "Add Liquidity", "0xf305d719": "Add Liquidity ETH", "0xeaaed442": "Add Liquidity BNB", "0x4bb278f3": "finalize", "0x8a8c523c": "Enable Trading", "0xc9567bf9": "Open Trading", "0x07279357": "Lock", "0x6167aa61": "Lock Tokens", "0x8af416f6": "Lock LP Token", "0x715018a6": "renounceOwnership", "0xa57e3141": "Renounce Lock Ownership", } def get_latest_block_number(rpc_api_url): data = { 'jsonrpc': '2.0', 'id': 1, 'method': 'eth_blockNumber', 'params': [], } response = requests.post(rpc_api_url, json=data) if response.status_code == 200: result = response.json() block_number_hex = result.get('result') return int(block_number_hex, 16) if block_number_hex else None return None def get_transactions_from_block(api_key, target_address, start_block, end_block): url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={target_address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() return result['result'] if result['status'] == '1' else None def get_transactions_from_block(api_key, target_address, start_block, end_block): url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={target_address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() return result['result'] if result['status'] == '1' else None def process_blocks(start_block, target_address, api_key, rpc_api_url): last_processed_block = start_block while True: latest_block = get_latest_block_number(rpc_api_url) if latest_block is None: print('Error getting latest block number') time.sleep(10) continue for block_number in range(last_processed_block, latest_block + 1): print(f'Processing block {block_number}') transactions = get_transactions_from_block(api_key, target_address, start_block=block_number, end_block=block_number) if transactions: method_ids_found = [(tx['hash'], tx['input'][:10]) for tx in transactions] for txn_hash, method_id in method_ids_found: method_name = method_ids.get(method_id) if method_name: print(f"{txn_hash}: {method_name}") last_processed_block = block_number + 1 # Use a delay to avoid overloading the server time.sleep(1) # Check for new blocks every minute time.sleep(5) process_blocks(START_BLOCK, TARGET_ADDRESS, API_KEY, RPC_API_URL) 28949450 and method id "0xf305d719": "Add Liquidity ETH"
64cf665559885a230800a23d84346e17
{ "intermediate": 0.3415754437446594, "beginner": 0.4730305075645447, "expert": 0.1853940337896347 }
11,520
hey
feaac60ba65710e869c24c58ee286897
{ "intermediate": 0.33180856704711914, "beginner": 0.2916048467159271, "expert": 0.3765866458415985 }
11,521
Write code in html css javascript that contains a chatbot using api spellbook ai this is my app link from spellbook ai this is https://spellbook.scale.com/app/chatgpt-9katl1dqk/ this is my api key this is clis0hqs900vc1ax41aac2o5u did you get what i said
65bd1e724436589d73c0f025504c4001
{ "intermediate": 0.47037413716316223, "beginner": 0.2585049271583557, "expert": 0.27112096548080444 }
11,523
write css, javascript, and html code for a simplified copy of the sims 4
d9314a8b1efea82add286363f13f7d6b
{ "intermediate": 0.4056704044342041, "beginner": 0.2002815157175064, "expert": 0.3940480947494507 }
11,524
help me make a best practice setup on vs code to start building a website with react and tailwindcss as the front-end, node.js as the backend and mongodb as the database.
d413127dab2307920297409c32fd0678
{ "intermediate": 0.6308318972587585, "beginner": 0.24869480729103088, "expert": 0.12047333270311356 }
11,525
import requests import time API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' TARGET_ADDRESS = '0x051F15B131bA12E4D5fA1283a5324a37C02521d7' START_BLOCK = 29002355 RPC_API_URL = 'https://bsc-dataseed.binance.org/' method_ids = { "0xe8e33700": "Add Liquidity", "0xf305d719": "Add Liquidity ETH", "0xeaaed442": "Add Liquidity BNB", "0x4bb278f3": "finalize", "0x8a8c523c": "Enable Trading", "0xc9567bf9": "Open Trading", "0x07279357": "Lock", "0x6167aa61": "Lock Tokens", "0x8af416f6": "Lock LP Token", "0x715018a6": "renounceOwnership", "0xa57e3141": "Renounce Lock Ownership", } def get_latest_block_number(rpc_api_url): data = { 'jsonrpc': '2.0', 'id': 1, 'method': 'eth_blockNumber', 'params': [], } response = requests.post(rpc_api_url, json=data) if response.status_code == 200: result = response.json() block_number_hex = result.get('result') return int(block_number_hex, 16) if block_number_hex else None return None def get_transactions_from_block(api_key, target_address, start_block, end_block): url = f'https://api.bscscan.com/api?module=account&action=txlist&address={target_address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={api_key}' response = requests.get(url) if response.status_code == 200: result = response.json() return result['result'] if result['status'] == '1' else None return None def process_blocks(start_block, target_address, api_key, rpc_api_url): last_processed_block = start_block while True: latest_block = get_latest_block_number(rpc_api_url) if latest_block is None: print('Error getting latest block number') time.sleep(10) continue for block_number in range(last_processed_block, latest_block + 1): print(f'Processing block {block_number}') transactions = get_transactions_from_block(api_key, target_address, start_block=block_number, end_block=block_number) if transactions: method_ids_found = [(tx['hash'], tx['input'][:10]) for tx in transactions] for txn_hash, method_id in method_ids_found: method_name = method_ids.get(method_id) if method_name: print(f"{txn_hash}: {method_name}") # Use a delay to avoid overloading the server time.sleep(1) last_processed_block = latest_block + 1 # Check for new blocks every minute time.sleep(5) process_blocks(START_BLOCK, TARGET_ADDRESS, API_KEY, RPC_API_URL) The code above returns the hash and method id that matches the transaction The code above returns the hash and method id that matches the transaction And the code below returns only the hash of the transaction. The id method is not recognized and returns None instead. Correct the code so that in block 28949450 only a transaction with the method id "0xf305d719": "Add Liquidity ETH" is displayed
f373de20c26c13f8f3709c9fbbb567c4
{ "intermediate": 0.37259194254875183, "beginner": 0.35661691427230835, "expert": 0.2707911729812622 }
11,526
what the word "word" means by your algorithms, how can you describe it in code of how you understand that one word, for example?
462239efa06391e74f75a6eda83fe49c
{ "intermediate": 0.23362600803375244, "beginner": 0.058894768357276917, "expert": 0.7074792385101318 }
11,527
An SQL DB table has 2 columns. Unique number and date. Create a query to show the last date for each unique number.
fb7fa168c64da5e6e43654de546805b1
{ "intermediate": 0.338909775018692, "beginner": 0.2752233147621155, "expert": 0.3858669102191925 }
11,528
import sys import pygame import math pygame.init() WIDTH = 900 HEIGHT = 900 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Tic-Tac-Toe") WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) FONT = pygame.font.SysFont("Arial", 80) SMALL_FONT = pygame.font.SysFont("Arial", 40) board = [['', '', ''], ['', '', ''], ['', '', '']] players = ['X', 'O'] current_player = players[0] game_over = False winner = None computer_player = 'O' game_started = False num_players = 0 player_starts = True def draw_home_screen(): screen.fill(WHITE) two_players_text = FONT.render("Press 1 For Two Players", True, BLACK) computer_text = FONT.render("Press 2 to Play with Computer", True, BLACK) two_players_rect = two_players_text.get_rect(center=(WIDTH/2, HEIGHT/2-50)) computer_rect = computer_text.get_rect(center=(WIDTH/2, HEIGHT/2+50)) screen.blit(two_players_text, two_players_rect) screen.blit(computer_text, computer_rect) def draw_board(): for x in range(3): for y in range(3): pygame.draw.rect(screen, BLUE, (x*300, y*300, 300, 300), 2) text = FONT.render(board[y][x], True, RED) text_rect = text.get_rect(center=(x*300+150, y*300+150)) screen.blit(text, text_rect) def check_win(): global game_over, winner for row in range(3): if board[row][0] == board[row][1] == board[row][2] != '': game_over = True winner = board[row][0] return for col in range(3): if board[0][col] == board[1][col] == board[2][col] != '': game_over = True winner = board[0][col] return if board[0][0] == board[1][1] == board[2][2] != '': game_over = True winner = board[0][0] return if board[0][2] == board[1][1] == board[2][0] != '': game_over = True winner = board[0][2] return if all([all(row) for row in board]) and not winner: game_over = True winner = 'Tie' def draw_winner(): if winner == 'Tie': text = FONT.render('Tie!', True, RED) else: text = FONT.render(f'{winner} wins!', True, RED) text_rect = text.get_rect(center=(WIDTH/2, HEIGHT/2)) screen.blit(text, text_rect) def draw_play_again(): text = SMALL_FONT.render('Press SPACE to play again', True, WHITE) text_rect = text.get_rect(center=(WIDTH/2, HEIGHT-50)) screen.blit(text, text_rect) def evaluate(board): for row in range(3): if board[row][0] == board[row][1] == board[row][2] != '': return 10 if board[row][0] == computer_player else -10 for col in range(3): if board[0][col] == board[1][col] == board[2][col] != '': return 10 if board[0][col] == computer_player else -10 if board[0][0] == board[1][1] == board[2][2] != '': return 10 if board[0][0] == computer_player else -10 if board[0][2] == board[1][1] == board[2][0] != '': return 10 if board[0][2] == computer_player else -10 return 0 def minimax(board, depth, is_maximizing): score = evaluate(board) if score == 10 or score == -10: return score if all([all(row) for row in board]): return 0 if is_maximizing: best_score = -math.inf for row in range(3): for col in range(3): if board[row][col] == '': board[row][col] = computer_player score = minimax(board, depth + 1, False) board[row][col] = '' best_score = max(best_score, score) return best_score else: best_score = math.inf for row in range(3): for col in range(3): if board[row][col] == '': board[row][col] = 'X' if computer_player == 'O' else 'O' score = minimax(board, depth + 1, True) board[row][col] = '' best_score = min(best_score, score) return best_score def find_best_move(board): best_value = -math.inf best_move = (-1, -1) for row in range(3): for col in range(3): if board[row][col] == '': board[row][col] = computer_player move_value = minimax(board, 0, False) board[row][col] = '' if move_value > best_value: best_value = move_value best_move = (row, col) return best_move def play_ai_turn(): global board, current_player if not game_over: row, col = find_best_move(board) if board[row][col] == '': board[row][col] = current_player check_win() current_player = players[1] if current_player == players[0] else players[0] def reset(): global board, game_over, winner, current_player, player_starts board = [['', '', ''], ['', '', ''], ['', '', '']] game_over = False winner = None current_player = players[0] if player_starts else players[1] player_starts = not player_starts ... while True: if not game_started: draw_home_screen() elif not game_over: screen.fill(BLACK) draw_board() if num_players == 1 and current_player == computer_player: play_ai_turn() elif game_over: draw_winner() draw_play_again() pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN and not game_started: if event.key == pygame.K_1: num_players = 2 if event.key == pygame.K_2: num_players = 1 if event.type == pygame.MOUSEBUTTONDOWN and game_started and not game_over: pygame.time.delay(500) x, y = pygame.mouse.get_pos() col = x // 200 row = y // 200 if board[row][col] == '': board[row][col] = current_player check_win() current_player = players[1] if current_player == players[0] else players[0] if event.type == pygame.KEYDOWN and game_over: if event.key == pygame.K_SPACE: reset() game_started = False please edit this code so that when I press 1 or 2, the game actually starts please edit this code so that when I press 1 or 2, the game actua
270d054d9d7453d65e767fadfa9ae729
{ "intermediate": 0.42301440238952637, "beginner": 0.3452683091163635, "expert": 0.2317173033952713 }
11,529
Random Forest
42e58586e3bb00e53d13ba7625ca7c87
{ "intermediate": 0.3046775758266449, "beginner": 0.36787185072898865, "expert": 0.32745054364204407 }
11,530
this is an old conversation between me and you : To achieve this, you can use the Activity Recognition API provided by Google Play services. Here’s how you can create a new interface to recognize user activities and display the confidence values: Step 1: Add Google Play services to your project. Add the following to your app’s build.gradle file, under the dependencies section: implementation ‘com.google.android.gms:play-services-location:18.0.0’ Step 2: Create a new class for detecting activities. Create a new class called ActivityRecognitionService and extend it from IntentService: import android.app.IntentService; import android.content.Intent; import com.google.android.gms.location.ActivityRecognitionResult; import com.google.android.gms.location.DetectedActivity; public class ActivityRecognitionService extends IntentService { public ActivityRecognitionService() { super(“ActivityRecognitionService”); } @Override protected void onHandleIntent(Intent intent) { if (ActivityRecognitionResult.hasResult(intent)) { ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent); DetectedActivity mostProbableActivity = result.getMostProbableActivity(); int confidence = mostProbableActivity.getConfidence(); int activityType = mostProbableActivity.getType(); // TODO: Handle the detected activity here } } } Step 3: Update your AndroidManifest.xml. Add the following service inside the &lt;application&gt; tag of your AndroidManifest.xml: <service android:name=“.ActivityRecognitionService” android:exported=“false” /> Step 4: Request activity recognition updates in your MainActivity. In your MainActivity class, add the following code to request activity recognition updates: private final int REQUEST_CODE_ACTIVITY_RECOGNITION = 100; private PendingIntent activityRecognitionPendingIntent; private ActivityRecognitionClient activityRecognitionClient; private void requestActivityUpdates() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, REQUEST_CODE_ACTIVITY_RECOGNITION); return; } activityRecognitionClient = new ActivityRecognitionClient(this); Intent intent = new Intent(this, ActivityRecognitionService.class); activityRecognitionPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); activityRecognitionClient.requestActivityUpdates(1000, activityRecognitionPendingIntent); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_ACTIVITY_RECOGNITION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { requestActivityUpdates(); } // Handle other permission results here } Now, when you call requestActivityUpdates() method, it will request for activity recognition updates. Handle the detected activities in the onHandleIntent() method of your ActivityRecognitionService class. Step 5: Create a new Activity to display confidence values. Create a new activity called ActivityConfidenceActivity with a layout that contains a TextView for each activity (walking, running, sitting, and jumping). Update the TextView with the confidence values in the onHandleIntent() method of the ActivityRecognitionService. Don’t forget to add your new activity to your AndroidManifest.xml. Now, when the user opens this activity, they will see the confidence values for each detected activity. j’ai une error la activityRecognitionClient = new ActivityRecognitionClient(this); dit que ‘ActivityRecognitionClient’ is abstract; cannot be instantiated I apologize for the confusion. You should use ActivityRecognition.getClient(this) instead of instantiating ActivityRecognitionClient. Here’s how to update the requestActivityUpdates() method: Change this line: activityRecognitionClient = new ActivityRecognitionClient(this); to: activityRecognitionClient = ActivityRecognition.getClient(this); So, the updated requestActivityUpdates() method should look like this: private void requestActivityUpdates() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, REQUEST_CODE_ACTIVITY_RECOGNITION); return; } activityRecognitionClient = ActivityRecognition.getClient(this); Intent intent = new Intent(this, ActivityRecognitionService.class); activityRecognitionPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); activityRecognitionClient.requestActivityUpdates(1000, activityRecognitionPendingIntent); } Now, you should no longer encounter the error. so know i added an activity ActivityConfidenceActivity contient textView for (walking, running, sitting, and jumping how can you provide the code that should out in onHandleIntent In order to update the TextViews in ActivityConfidenceActivity from ActivityRecognitionService, you can use a BroadcastReceiver. Here’s how you can do it: Step 1: Create a BroadcastReceiver in your ActivityConfidenceActivity. public class ActivityConfidenceActivity extends AppCompatActivity { private BroadcastReceiver activityReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_confidence); activityReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int type = intent.getIntExtra(“type”, -1); int confidence = intent.getIntExtra(“confidence”, 0); // Update the TextViews according to the activity type and confidence } }; } } Step 2: Register and unregister the BroadcastReceiver. @Override protected void onResume() { super.onResume(); LocalBroadcastManager.getInstance(this).registerReceiver(activityReceiver, new IntentFilter(“activity_update”)); } @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(activityReceiver); } Step 3: Update the onHandleIntent() method in ActivityRecognitionService. @Override protected void onHandleIntent(Intent intent) { if (ActivityRecognitionResult.hasResult(intent)) { ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent); DetectedActivity mostProbableActivity = result.getMostProbableActivity(); int confidence = mostProbableActivity.getConfidence(); int activityType = mostProbableActivity.getType(); // Send a broadcast with the activity type and confidence Intent broadcastIntent = new Intent(“activity_update”); broadcastIntent.putExtra(“type”, activityType); broadcastIntent.putExtra(“confidence”, confidence); LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent); } } Now, your ActivityConfidenceActivity will receive updates from the ActivityRecognitionService. Update the TextViews according to the received activityType and confidence values in the onReceive() method of the BroadcastReceiver. Please make sure you have added the required import statements for BroadcastReceiver, LocalBroadcastManager, and other classes used in the code snippets. can you give me // Update the TextViews according to the activity type and confidence code Certainly! First, you need to add the TextViews for walking, running, sitting, and jumping in your activity_confidence.xml layout file. Add the following to your layout: <TextView android:id=“@+id/tv_walking” android:layout_width=“wrap_content” android:layout_height=“wrap_content” android:text=“Walking: " /> <TextView android:id=”@+id/tv_running" android:layout_width=“wrap_content” android:layout_height=“wrap_content” android:text=“Running: " /> <TextView android:id=”@+id/tv_sitting" android:layout_width=“wrap_content” android:layout_height=“wrap_content” android:text=“Sitting: " /> <TextView android:id=”@+id/tv_jumping" android:layout_width=“wrap_content” android:layout_height=“wrap_content” android:text=“Jumping: " /> Now, you can reference these TextViews in your ActivityConfidenceActivity. Update the onReceive() method in the BroadcastReceiver as follows: activityReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int type = intent.getIntExtra(“type”, -1); int confidence = intent.getIntExtra(“confidence”, 0); TextView tvWalking = findViewById(R.id.tv_walking); TextView tvRunning = findViewById(R.id.tv_running); TextView tvSitting = findViewById(R.id.tv_sitting); TextView tvJumping = findViewById(R.id.tv_jumping); String confidenceText = " (” + confidence + “%)”; switch (type) { case DetectedActivity.WALKING: tvWalking.setText(“Walking:” + confidenceText); break; case DetectedActivity.RUNNING: tvRunning.setText(“Running:” + confidenceText); break; case DetectedActivity.STILL: tvSitting.setText(“Sitting:” + confidenceText); break; case DetectedActivity.ON_FOOT: // You can use this as an approximation for jumping tvJumping.setText(“Jumping:” + confidenceText); break; default: // Handle other activity types if needed break; } } }; This code will update the corresponding TextView based on the detected activity type and display the confidence value in the format “Activity: (Confidence%)”. Adjust the case values and other code parts if necessary according to your specific activity types and layout structure. ==> this is my main package org.project.ayoub_akanoun_projet; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.app.PendingIntent; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.widget.Button; import android.widget.Toast; import com.google.android.gms.location.ActivityRecognition; import com.google.android.gms.location.ActivityRecognitionClient; import org.project.ayoub_akanoun_projet.activitiesRecognition.ActivityConfidenceActivity; import org.project.ayoub_akanoun_projet.activitiesRecognition.ActivityRecognitionService; public class Main2Activity extends AppCompatActivity { private final int REQUEST_CODE_ACTIVITY_RECOGNITION = 100; private PendingIntent activityRecognitionPendingIntent; private ActivityRecognitionClient activityRecognitionClient; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { requestActivityUpdates(); } button = findViewById(R.id.button); button.setOnClickListener(v -> { Intent intent = new Intent(Main2Activity.this, ActivityConfidenceActivity.class); startActivity(intent); }); } @RequiresApi(api = Build.VERSION_CODES.Q) private void requestActivityUpdates() { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACTIVITY_RECOGNITION}, REQUEST_CODE_ACTIVITY_RECOGNITION); Toast.makeText(this, "permession diened", Toast.LENGTH_SHORT).show(); return; } activityRecognitionClient = ActivityRecognition.getClient(this); Intent intent = new Intent(this, ActivityRecognitionService.class); activityRecognitionPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); activityRecognitionClient.requestActivityUpdates(1000, activityRecognitionPendingIntent); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_ACTIVITY_RECOGNITION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { requestActivityUpdates(); } } } } when the ActivityConfidence showed it didn't updates
2e0c8a7a3ec498bcf8ad1382f8631025
{ "intermediate": 0.3895219564437866, "beginner": 0.3743382692337036, "expert": 0.23613972961902618 }
11,531
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/ // © capissimo //@version=5 indicator('Machine Learning: kNN-based Strategy', 'ML-kNN', true, max_labels_count=300, format=format.price, precision=2, timeframe="", timeframe_gaps=true) // kNN-based Strategy (FX and Crypto) // Description: // This strategy uses a classic machine learning algorithm - k Nearest Neighbours (kNN) - // to let you find a prediction for the next (tomorrow's, next month's, etc.) market move. // Being an unsupervised machine learning algorithm, kNN is one of the most simple learning algorithms. // To do a prediction of the next market move, the kNN algorithm uses the historic data, // collected in 3 arrays - feature1, feature2 and directions, - and finds the k-nearest // neighbours of the current indicator(s) values. // The two dimensional kNN algorithm just has a look on what has happened in the past when // the two indicators had a similar level. It then looks at the k nearest neighbours, // sees their state and thus classifies the current point. // The kNN algorithm offers a framework to test all kinds of indicators easily to see if they // have got any *predictive value*. One can easily add cog, wpr and others. // Note: TradingViews's playback feature helps to see this strategy in action. // Warning: Signals ARE repainting. // Style tags: Trend Following, Trend Analysis // Asset class: Equities, Futures, ETFs, Currencies and Commodities // Dataset: FX Minutes/Hours+++/Days //-- Preset Dates int startdate = timestamp('01 Jan 2000 00:00:00 GMT+10') int stopdate = timestamp('31 Dec 2025 23:45:00 GMT+10') //-- Inputs StartDate = input.time (startdate, 'Start Date') StopDate = input.time (stopdate, 'Stop Date') Indicator = input.string('All', 'Indicator', ['RSI','ROC','CCI','Volume','All']) ShortWinow = input.int (14, 'Short Period [1..n]', 1) LongWindow = input.int (28, 'Long Period [2..n]', 2) BaseK = input.int (252, 'Base No. of Neighbours (K) [5..n]', 5) Filter = input.bool (false, 'Volatility Filter') Bars = input.int (300, 'Bar Threshold [2..5000]', 2, 5000) //-- Constants var int BUY = 1 var int SELL =-1 var int CLEAR = 0 var int k = math.floor(math.sqrt(BaseK)) // k Value for kNN algo //-- Variable // Training data, normalized to the range of [0,...,100] var array<float> feature1 = array.new_float(0) // [0,...,100] var array<float> feature2 = array.new_float(0) // ... var array<int> directions = array.new_int(0) // [-1; +1] // Result data var array<int> predictions = array.new_int(0) var float prediction = 0.0 var array<int> bars = array.new<int>(1, 0) // array used as a container for inter-bar variables // Signals var int signal = CLEAR //-- Functions minimax(float x, int p, float min, float max) => float hi = ta.highest(x, p), float lo = ta.lowest(x, p) (max - min) * (x - lo)/(hi - lo) + min cAqua(int g) => g>9?#0080FFff:g>8?#0080FFe5:g>7?#0080FFcc:g>6?#0080FFb2:g>5?#0080FF99:g>4?#0080FF7f:g>3?#0080FF66:g>2?#0080FF4c:g>1?#0080FF33:#00C0FF19 cPink(int g) => g>9?#FF0080ff:g>8?#FF0080e5:g>7?#FF0080cc:g>6?#FF0080b2:g>5?#FF008099:g>4?#FF00807f:g>3?#FF008066:g>2?#FF00804c:g>1?#FF008033:#FF008019 inside_window(float start, float stop) => time >= start and time <= stop ? true : false //-- Logic bool window = inside_window(StartDate, StopDate) // 3 pairs of predictor indicators, long and short each float rs = ta.rsi(close, LongWindow), float rf = ta.rsi(close, ShortWinow) float cs = ta.cci(close, LongWindow), float cf = ta.cci(close, ShortWinow) float os = ta.roc(close, LongWindow), float of = ta.roc(close, ShortWinow) float vs = minimax(volume, LongWindow, 0, 99), float vf = minimax(volume, ShortWinow, 0, 99) // TOADD or TOTRYOUT: // ta.cmo(close, LongWindow), ta.cmo(close, ShortWinow) // ta.mfi(close, LongWindow), ta.mfi(close, ShortWinow) // ta.mom(close, LongWindow), ta.mom(close, ShortWinow) float f1 = switch Indicator 'RSI' => rs 'CCI' => cs 'ROC' => os 'Volume' => vs => math.avg(rs, cs, os, vs) float f2 = switch Indicator 'RSI' => rf 'CCI' => cf 'ROC' => of 'Volume' => vf => math.avg(rf, cf, of, vf) // Classification data, what happens on the next bar int class_label = int(math.sign(close[1] - close[0])) // eq. close[1]<close[0] ? SELL: close[1]>close[0] ? BUY : CLEAR // Use particular training period if window // Store everything in arrays. Features represent a square 100 x 100 matrix, // whose row-colum intersections represent class labels, showing historic directions array.push(feature1, f1) array.push(feature2, f2) array.push(directions, class_label) // Ucomment the followng statement (if barstate.islast) and tab everything below // between BOBlock and EOBlock marks to see just the recent several signals gradually // showing up, rather than all the preceding signals //if barstate.islast //==BOBlock // Core logic of the algorithm int size = array.size(directions) float maxdist = -999.0 // Loop through the training arrays, getting distances and corresponding directions. for i=0 to size-1 // Calculate the euclidean distance of current point to all historic points, // here the metric used might as well be a manhattan distance or any other. float d = math.sqrt(math.pow(f1 - array.get(feature1, i), 2) + math.pow(f2 - array.get(feature2, i), 2)) if d > maxdist maxdist := d if array.size(predictions) >= k array.shift(predictions) array.push(predictions, array.get(directions, i)) //==EOBlock // Note: in this setup there's no need for distances array (i.e. array.push(distances, d)), // but the drawback is that a sudden max value may shadow all the subsequent values. // One of the ways to bypass this is to: // 1) store d in distances array, // 2) calculate newdirs = bubbleSort(distances, directions), and then // 3) take a slice with array.slice(newdirs) from the end // Get the overall prediction of k nearest neighbours prediction := array.sum(predictions) bool filter = Filter ? ta.atr(10) > ta.atr(40) : true // filter out by volatility or ex. ta.atr(1) > ta.atr(10)... // Now that we got a prediction for the next market move, we need to make use of this prediction and // trade it. The returns then will show if everything works as predicted. // Over here is a simple long/short interpretation of the prediction, // but of course one could also use the quality of the prediction (+5 or +1) in some sort of way, // ex. for position sizing. bool long = prediction > 0 and filter bool short = prediction < 0 and filter bool clear = not(long and short) if array.get(bars, 0)==Bars // stop by trade duration signal := CLEAR array.set(bars, 0, 0) else array.set(bars, 0, array.get(bars, 0) + 1) signal := long ? BUY : short ? SELL : clear ? CLEAR : nz(signal[1]) int changed = ta.change(signal) bool startLongTrade = changed and signal==BUY bool startShortTrade = changed and signal==SELL // bool endLongTrade = changed and signal==SELL // bool endShortTrade = changed and signal==BUY bool clear_condition = changed and signal==CLEAR //or (changed and signal==SELL) or (changed and signal==BUY) float maxpos = ta.highest(high, 10) float minpos = ta.lowest (low, 10) //-- Visuals plotshape(startLongTrade ? minpos : na, 'Buy', shape.labelup, location.belowbar, cAqua(int(prediction*5)), size=size.small) // color intensity correction plotshape(startShortTrade ? maxpos : na, 'Sell', shape.labeldown, location.abovebar, cPink(int(-prediction*5)), size=size.small) // plot(endLongTrade ? ohlc4 : na, 'StopBuy', cAqua(6), 3, plot.style_cross) // plot(endShortTrade ? ohlc4 : na, 'StopSell', cPink(6), 3, plot.style_cross) plot(clear_condition ? close : na, 'ClearPos', color.yellow, 4, plot.style_cross) //-- Notification // if changed and signal==BUY // alert('Buy Alert', alert.freq_once_per_bar) // alert.freq_once_per_bar_close // if changed and signal==SELL // alert('Sell Alert', alert.freq_once_per_bar) alertcondition(startLongTrade, 'Buy', 'Go long!') alertcondition(startShortTrade, 'Sell', 'Go short!') //alertcondition(startLongTrade or startShortTrade, 'Alert', 'Deal Time!') //-------------------- Backtesting (TODO) // show_cumtr = input.bool (false, 'Show Trade Return?') // lot_size = input.float(100.0, 'Lot Size', [0.1,0.2,0.3,0.5,1,2,3,5,10,20,30,50,100,1000,2000,3000,5000,10000]) // var start_lt = 0. // var long_trades = 0. // var start_st = 0. // var short_trades = 0. // if startLongTrade // start_lt := ohlc4 // if endLongTrade // long_trades := (open - start_lt) * lot_size // if startShortTrade // start_st := ohlc4 // if endShortTrade // short_trades := (start_st - open) * lot_size // cumreturn = ta.cum(long_trades) + ta.cum(short_trades) // var label lbl = na // if show_cumtr //and barstate.islast // lbl := label.new(bar_index+10, close, 'CumReturn: ' + str.tostring(cumreturn, '#.#'), xloc.bar_index, yloc.price, // color.new(color.blue, 100), label.style_label_left, color.black, size.small, text.align_left) // label.delete(lbl[1]) give me somme suggition
4eb900e22c95dbc20b45b69187e316b5
{ "intermediate": 0.3246089220046997, "beginner": 0.4258100390434265, "expert": 0.2495809644460678 }
11,532
echart 'requestAnimationFrame' handler took 182ms
24080b29ff4de5727151c6817a19d487
{ "intermediate": 0.36566463112831116, "beginner": 0.23241394758224487, "expert": 0.4019213914871216 }
11,533
Nested struct in golang
f05b50428b59126e5fa9e67548605349
{ "intermediate": 0.35219821333885193, "beginner": 0.22615867853164673, "expert": 0.42164313793182373 }
11,534
I have a reactjs project with node js for the backend and mongodb as the database, I need you to create a Register/log in/log out functionalities. User has Email,Password,Username,avatarimg,Firstname,Lastname,phoneNumber,IPAdresses,WalletName,WalletID,TasksDone,JoinDate,. User can login with either email or Username. show me the step by step to implement this.
d0920fa5529ab2ef9b4af6b60e649c95
{ "intermediate": 0.7030590176582336, "beginner": 0.11155734211206436, "expert": 0.1853836476802826 }
11,535
Debian packaging tools generally labels all files in /etc as config files, as mandated by policy, so fpm defaults to this behavior for deb packages
1790f112d1f468e1f30b82f4dacc5425
{ "intermediate": 0.32661429047584534, "beginner": 0.18629857897758484, "expert": 0.48708707094192505 }
11,536
hi
acac8217579220bb69759ec656a4eeca
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
11,537
I want to use WebSocket and PuppeteerSharp to create a server and multiple clients system. What I want is for the server to listen for incoming connections. When a connection is made, the server signals the connected client to open a new Puppeteer browser and go to google.com. (on the client side, so there is no need to open a browser on the VPS server) The client sends back the response to the server.
30ff52f7cd9ec459f3b801b87800e9b0
{ "intermediate": 0.5429727435112, "beginner": 0.20951789617538452, "expert": 0.24750930070877075 }
11,538
hi
c049ebd42146c6e8dce4f47b870af5e9
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
11,539
color red
e062b31774763103db18a9209583203f
{ "intermediate": 0.3726997673511505, "beginner": 0.31664466857910156, "expert": 0.3106555640697479 }
11,540
How to replicate massive objects from one bucket to another rapidly
140d9f532bf21a98fadcfd74eaa40eb6
{ "intermediate": 0.3067580759525299, "beginner": 0.12435268610715866, "expert": 0.5688892602920532 }
11,541
fivem scripting trigger an event once a week
cd97127a63a0c6454df387261ddf4400
{ "intermediate": 0.2932128608226776, "beginner": 0.38000378012657166, "expert": 0.32678332924842834 }
11,542
I have now finished a prt of the front-end and for me to continue I need some sort of backend. So I was thinking of the following data schema. What do you think? What should I change for long term use and scalability? Should I change names of the documents or collections? How can I make it better. Users (collection) <userID> (document) Main (collection) <jobID> (document) {jobInformation} (fields) <jobID> (document) {jobInformation} (fields) etc. Signup (collection) Information (document) {UserInformation} (fields) <userID> (document) Main (collection) <jobID> (document) {jobInformation} (fields) <jobID> (document) {jobInformation} (fields) etc. Signup (collection) Information (document) {UserInformation} (fields) etc. Aggregation (collection) Jobs (document) <jobID> (field (type map)) {jobInfo} <jobID> (field (type map)) {jobInfo} etc. Pharmacists (document) <userID> (field (type map)) {userInfo} <userID> (field (type map)) {userInfo} etc. pharmacyAssistant ((document) consists of both pharmacy tech and assistant users) <userID> (field (type map)) {userInfo} <userID> (field (type map)) {userInfo} etc.
619dfe7caef534f7f92771df86e1617c
{ "intermediate": 0.37637409567832947, "beginner": 0.3390074074268341, "expert": 0.2846185564994812 }
11,543
I want to see what a YT thumbnail would look like. How can I edit the html of the youtube page on my pc to test out what it looks like? I tried setting the src of a random YT video thumbnail to point to my local image but I don't see it rendered on the YT page.
b82fa5a27df4152cbb6bbda554ff49ce
{ "intermediate": 0.5025662183761597, "beginner": 0.19964078068733215, "expert": 0.2977930009365082 }
11,544
wxpython3.0 加载pdf
850f60194dc60aba35a7d1cb6e518984
{ "intermediate": 0.3263414204120636, "beginner": 0.3742457926273346, "expert": 0.2994127571582794 }
11,545
python build a GUI for this import os input_file = 'input.mkv' output_file = 'output.mp4' os.system(f'ffmpeg -i {input_file} -c:v libx264 -x264-params crf=23 -preset medium -c:a copy -movflags +faststart {output_file}') which allows user to select input file select where to save and file name and a convert button plus a progress bar
0769d62db34cc1ed2933b95fc5f3096f
{ "intermediate": 0.5388895869255066, "beginner": 0.1970033049583435, "expert": 0.2641071081161499 }
11,546
What type of implementation is this? Is it good? Alternatives? class ComponentBase { public: virtual ~ComponentBase() {} virtual void DestroyData(unsigned char* data) const = 0; virtual void MoveData(unsigned char* source, unsigned char* destination) const = 0; virtual void ConstructData(unsigned char* data) const = 0; virtual std::size_t GetSize() const = 0; }; template<class C> class Component : public ComponentBase { public: virtual void DestroyData(unsigned char* data) const override; virtual void MoveData(unsigned char* source, unsigned char* destination) const override; virtual void ConstructData(unsigned char* data) const override; virtual size_t GetSize() const override; static size_t GetTypeID(); }; template<class C> void Component<C>::DestroyData(unsigned char* data) const { C* dataLocation = std::launder(reinterpret_cast<C*>(data)); dataLocation->~C(); } template<class C> void Component<C>::ConstructData(unsigned char* data) const { new (&data[0]) C(); } template<class C> void Component<C>::MoveData(unsigned char* source, unsigned char* destination) const { new (&destination[0]) C(std::move(*std::bit_cast<C*>(source))); } template<class C> std::size_t Component<C>::GetSize() const { return sizeof(C); } template<class C> std::size_t Component<C>::GetTypeID() { return TypeIdGenerator<ComponentBase>::GetNewID<C>(); } template <class C> std::size_t GetTypeID() { return TypeIdGenerator<ComponentBase>::GetNewID<C>(); }
c5ccaf1949dd40a6b7812a5eecf9554c
{ "intermediate": 0.4068030118942261, "beginner": 0.398721307516098, "expert": 0.19447563588619232 }
11,547
write html code to scan website for urls and download them and the scan the downloaded urls and on and on. then package all the files in .zip file and download it. basically make web scraper.
b414090827ab092c7e64d8eb2b8d71d5
{ "intermediate": 0.36547502875328064, "beginner": 0.21095046401023865, "expert": 0.4235745072364807 }
11,548
please review this code import axios, { AxiosInstance } from "axios"; import { BASE_URL } from "../../constants/appconfig"; export const httpClient = axios.create({ baseURL: BASE_URL, headers: { "Content-Type": "application/json", }, }); export const get = async <T>(axiosHttpClient: AxiosInstance): Promise<T> => { const response = await axiosHttpClient.get<T>(BASE_URL); return response.data; }; export const post = async <T, U>( data: T, axiosHttpClient: AxiosInstance ): Promise<U> => { const response = await axiosHttpClient.post<U>(BASE_URL, data); return response.data; }; export default { get, post, };
7ec668ff6fbcb3ff62825c15d28f837b
{ "intermediate": 0.4068114459514618, "beginner": 0.38756972551345825, "expert": 0.20561881363391876 }