row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
12,053
|
Нужно как-то сжимать загруженные mp3 файлы в app.post("/profile/:id/upload"
вот код:
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"));
connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => {
if(err) throw err;
});
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
//функция для получения песен музыканта по id
function getMusicianTracks(musicianId, callback) {
connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => {
if (err) {
console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result);
}
});
}
function getMusicians(callback) {
connection.query("SELECT * FROM users", (err, result) => {
if (err) {
console.error("Ошибка при получении списка музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
// Функция для получения музыканта по id
function getMusicianById(id, callback) {
connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
if (err) {
console.error("Ошибка при получении музыканта с id ${id}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result[0]);
}
});
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];
// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}
// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.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
};
});
// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;
if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}
// Сортировка по score (убывающая)
return scoreB - scoreA;
});
// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}
app.use((req, res, next) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении current user: ", err);
} else {
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
}
});
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
res.status(500).send("Ошибка получения данных");
} else {
res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' });
}
});
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT DISTINCT city FROM users 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:'', query:'',role:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {
// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
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_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});
app.get("/profile/:id", (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
getMusicianTracks(musician.id, (err, tracks) => {
if(err) {
console.error("Ошибка при получении треков для профиля: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
res.render("profile", { musician: musician, tracks: tracks, query:'', role:'', city:''});
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
if (err) {
console.error("Ошибка при входе: ", err);
res.status(500).send("Ошибка при входе");
} else {
if (result.length > 0) {
req.session.musicianId = result[0].id;
res.redirect("/profile/" + result[0].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) => {
let query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
const genre = req.query.genre || '';
if (query || role || city || genre) {
search(query, role, city, genre, (err, musicians) => {
if (err) {
res.status(500).send("Ошибка при выполнении поиска");
} else {
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
} else {
// Use the getMusicians function instead of reading from musicians.json
getMusicians((err, musiciansList) => {
if (err) {
res.status(500).send("Ошибка при получении списка музыкантов");
} else {
const musicians = musiciansList.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
};
});
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
}
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
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 musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
//загрузка музыки и изображений к музыке
app.post("/profile/:id/upload", requireLogin, async (req, res) => {
const musicianId = req.session.musicianId;
if (!req.files) {
res.status(400).send("No files were uploaded.");
return;
}
const trackFile = req.files.track;
if (!trackFile) {
res.status(400).send("No track file was uploaded.");
return;
}
if (trackFile && !trackFile.name.endsWith(".mp3")) {
res.status(400).send("Only .mp3 files can be uploaded.");
return;
}
// Set a maximum file size of 10MB for uploaded files
const maxSizeInBytes = 10000000; // 10MB
if (trackFile && trackFile.size > maxSizeInBytes) {
res.status(400).send("File size exceeds 10MB limit.");
return;
}
const trackFilename = "track_" + musicianId + "" + trackFile.name;
trackFile.mv("./public/tracks/" + trackFilename);
const title = req.body.title;
const album_title = req.body.albumTitle;
const track = {
musician_id: musicianId,
title,
album_title,
filename: trackFilename,
};
if (req.files.image) {
const imageFile = req.files.image;
const imageFilename = "image" + musicianId + "_" + imageFile.name;
imageFile.mv("./public/img/" + imageFilename);
track.image_filename = imageFilename;
}
connection.query("INSERT INTO tracks SET ?", track, (err, result) => {
if (err) {
console.error("Ошибка при добавлении трека: ", err);
res.status(500).send("Ошибка при добавлении трека");
} else {
res.redirect("/profile/" + musicianId);
}
});
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
|
aadd39588c91caafe650b2f439f3eeaa
|
{
"intermediate": 0.2768152058124542,
"beginner": 0.4282282590866089,
"expert": 0.2949565351009369
}
|
12,054
|
which flag to use with msbuild in order to check its version?
|
fea7d8c02b75d91643bff295e5bc8ef1
|
{
"intermediate": 0.5559948682785034,
"beginner": 0.1492680013179779,
"expert": 0.2947371304035187
}
|
12,055
|
hi gpt
|
c0694713c7ec001e6096c5f459377a3a
|
{
"intermediate": 0.28147566318511963,
"beginner": 0.2624020278453827,
"expert": 0.4561222791671753
}
|
12,056
|
Implement a neural network in python
|
128f51d4a868ebc8f2ad378a35ef21e8
|
{
"intermediate": 0.11625747382640839,
"beginner": 0.06275620311498642,
"expert": 0.8209863305091858
}
|
12,057
|
def predict_next_periods(model, last_period, num_periods):
predictions = []
for _ in range(num_periods):
next_period = model.predict(last_period[np.newaxis])
predictions.append(next_period[0])
last_period = np.roll(last_period, -7)
last_period[-7:] = next_period
return predictions
predicted_next_periods = predict_next_periods(model, x_train[-1], 5)
ValueError: could not broadcast input array from shape (1,35) into shape (1,7)
|
65231eeced0679edcc1512f541aa7be6
|
{
"intermediate": 0.3681045472621918,
"beginner": 0.32903704047203064,
"expert": 0.3028583526611328
}
|
12,058
|
test
|
1ab81cf43526e2729b0807b7a76de18f
|
{
"intermediate": 0.3229040801525116,
"beginner": 0.34353747963905334,
"expert": 0.33355844020843506
}
|
12,059
|
write some cross-platform python code, that displays a full screen image
|
4e11edea800ae326e224e22c6655a84d
|
{
"intermediate": 0.4079054296016693,
"beginner": 0.19386696815490723,
"expert": 0.3982275724411011
}
|
12,060
|
Implement a web scraper to collect financial data in python
|
673d519bce06cd0843f6a26a1538d6c2
|
{
"intermediate": 0.5440929532051086,
"beginner": 0.11317244917154312,
"expert": 0.34273454546928406
}
|
12,061
|
Hi!
|
94e6a2f4cb84e04343f4d171a79599c7
|
{
"intermediate": 0.3230988085269928,
"beginner": 0.2665199935436249,
"expert": 0.4103812277317047
}
|
12,062
|
. Implement a password manager application in python
|
5f0179bd2fa6148b754ccb50c75f2819
|
{
"intermediate": 0.42658093571662903,
"beginner": 0.16333362460136414,
"expert": 0.41008543968200684
}
|
12,063
|
jaxb2-maven-plugin how to use
|
d211bb8ae90fc504b34f6dfd0199750e
|
{
"intermediate": 0.4763071537017822,
"beginner": 0.17323358356952667,
"expert": 0.3504592776298523
}
|
12,064
|
#include <stdio.h>
#include <stdlib.h>
#include “smr.h”
#define REGION_NAME “anony”
#define REGION_ADDR 0x001000
#define REGION_SIZE 0x100000
#define CHUNK_NUM 5
typedef struct {
uint8_t* addr;
uint32_t size;
}chunk_t;
chunk_t chunks[CHUNK_NUM];
int main() {
smr_region region = {
.region_name = REGION_NAME,
.addr = REGION_ADDR,
.len = REGION_SIZE
};
smr_attr attr = {
.cur_regions = ®ion,
.num = 1,
.alloc_name = “chunk”
};
uint32_t chunk_size = REGION_SIZE / CHUNK_NUM;
uint32_t chunk_align = 4;
ot_smr_alloc_attr alloc_attr = {
.region_name = REGION_NAME,
.len = chunk_size,
.align = chunk_align,
.cached = false
};
// initialize SMR
ot_s32 ret = ot_smr_init(&attr);
if(ret != 0) {
printf(“SMR init error[%d]!\n”, ret);
return -1;
}
// allocate memory for each chunk
for(int i = 0; i < CHUNK_NUM; i++) {
char name[16];
sprintf(name, “chunk_%d”, i); // set name for each chunk
chunks[i].size = chunk_size; // set size for each chunk
alloc_attr.len = chunk_size;
alloc_attr.region_name = REGION_NAME;
alloc_attr.align = chunk_align;
alloc_attr.cached = false;
attr.alloc_name = name;
ret = ot_smr_alloc(&alloc_attr, (phys_addr*)&chunks[i].addr); // allocate memory for the chunk
if(ret != 0) {
printf(“SMR alloc error[%d]!\n”, ret);
return -1;
}
printf(“Chunk %d allocated at address 0x%08X with size %d bytes\n”, i, chunks[i].addr, chunks[i].size);
}
// deinitialize SMR
ot_smr_deinit();
return 0;
} 基于上面的代码增加smr_mmap映射,将chunk[2].addr进行虚拟地址映射,并返回对应的虚拟地址
|
0a88fa79805889b630c606bf6aece1bb
|
{
"intermediate": 0.3714153468608856,
"beginner": 0.28130415081977844,
"expert": 0.34728044271469116
}
|
12,065
|
Implement a stopwatch application in python
|
787ecf08d37ec84db9db6423e73330c1
|
{
"intermediate": 0.3664219379425049,
"beginner": 0.16516032814979553,
"expert": 0.4684177041053772
}
|
12,066
|
import React from 'react';
import { yupResolver } from '@hookform/resolvers/yup';
import { Checkbox, FormControlLabel, FormGroup } from '@material-ui/core';
import cx from 'classnames';
import { isAfter, isBefore, isValid } from 'date-fns';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import * as Yup from 'yup';
import {
Button,
DateTimePicker,
Label,
RadioGroup,
Select,
TagSelector,
} from 'components/common';
import { MAX_DATE, MIN_DATE, eventDateOptions } from 'constants/manualActions';
import { useFlagsContext } from 'contexts/FlagsContext';
import {
blockSettlementDefault,
useManualActionsContext,
} from 'contexts/ManualActionsContext';
import { BranchStatus } from 'models/BranchStatus';
import { Competition, ListCompetitions } from 'models/Competition';
import { ListEvents } from 'models/Context';
import {
EventSearchCheckBoxesOptions,
EventSearchFormValues,
} from 'models/EventSearchForm';
import { FeatureFlags } from 'models/FeatureFlags';
import { Sport } from 'models/Sport';
import { getDatesFromRange } from 'utils/Date';
export interface EventSearchFormProps {
sports: Sport[];
competitions: Competition[];
selectedSearchValues: EventSearchFormValues;
listCompetitions: ListCompetitions;
listCompetitionsStatus: BranchStatus;
listEvents: ListEvents;
listEventsStatus: BranchStatus;
rowsPerPage: number;
disableEventStatus: boolean;
}
const showBlockSettlement = (flags: FeatureFlags): boolean =>
!flags.BLOCK_SETTLEMENT_FLAG;
const checkBoxes: EventSearchCheckBoxesOptions = [
{
labelName: 'resettlementBlockedEvents',
formName: 'eventStatusBlocked',
},
{
labelName: 'settlementBlockedEvents',
formName: 'eventStatus',
},
{
labelName: 'unsettledEvents',
formName: 'isFullyResulted',
},
];
export const EventSearchForm: React.FC<EventSearchFormProps> = ({
sports,
competitions,
selectedSearchValues,
listCompetitions,
listCompetitionsStatus,
listEvents,
listEventsStatus,
rowsPerPage,
disableEventStatus,
}) => {
const { t } = useTranslation();
const { flags } = useFlagsContext();
const { setBlockSettlementPayload } = useManualActionsContext();
const { control, handleSubmit, setValue, watch } =
useForm<EventSearchFormValues>({
resolver: yupResolver(
Yup.object().shape({
sport: Yup.string().required(),
competitions: Yup.array().required(),
fromDate: Yup.date().required(),
toDate: Yup.date().required(),
eventDate: Yup.string().nullable(),
eventStatusBlocked: Yup.boolean().required(),
isFullyResulted: Yup.boolean(),
eventStatus: Yup.boolean(),
}),
),
});
const eventDateWatch = watch('eventDate');
const sportWatch = watch('sport');
const competitionsWatch = watch('competitions');
const toDateWatch = watch('toDate');
const fromDateWatch = watch('fromDate');
React.useEffect(() => {
if (typeof eventDateWatch !== 'undefined' && eventDateWatch) {
const { fromDate, toDate } = getDatesFromRange(
new Date(Date.now()),
eventDateWatch,
);
setValue('fromDate', fromDate);
setValue('toDate', toDate);
selectedSearchValues.fromDate = fromDate;
selectedSearchValues.toDate = toDate;
} else if (typeof eventDateWatch === 'undefined') {
setValue('fromDate', selectedSearchValues.fromDate);
setValue('toDate', selectedSearchValues.toDate);
}
}, [eventDateWatch, selectedSearchValues, setValue]);
React.useEffect(() => {
sportWatch && listCompetitions(+sportWatch);
}, [sportWatch, listCompetitions]);
const onSubmit = async (data: EventSearchFormValues) => {
await listEvents(data, 0, rowsPerPage);
setBlockSettlementPayload(blockSettlementDefault);
};
const eventSearchFormBlockedStyles = cx(
'event-search-form__blocked-content',
{
[`disabled`]: disableEventStatus,
},
);
return (
<form
className="event-search-form"
onSubmit={handleSubmit(onSubmit)}
data-testid="event-search-form"
>
<Controller
name="sport"
control={control}
defaultValue={selectedSearchValues.sport}
render={({ onChange, value, name }) => (
<Select
label={t('form.sport')}
className="event-search-form__sport-select"
testId="event-search-form-sport-select"
placeholder={t('form.sportPlaceholder')}
options={sports.map((sport) => {
return { label: sport.name, value: sport.id.toString() };
})}
name={name}
value={value}
onChange={(event) => {
setValue('competitions', []);
onChange(event);
}}
/>
)}
/>
<Controller
name="competitions"
control={control}
defaultValue={selectedSearchValues.competitions}
render={({ onChange, value, name }) => (
<TagSelector
label={t('form.competition')}
className="event-search-form__competition-select"
options={competitions.map((competition) => {
return {
label: competition.name,
value: competition.id,
};
})}
placeholder={t('form.competitionPlaceholder')}
testId="event-search-form-competition-select"
onChange={onChange}
disabled={!sportWatch}
loading={listCompetitionsStatus === BranchStatus.LOADING}
value={value}
name={name}
/>
)}
/>
<div className="event-search-form__blocked-container">
{!showBlockSettlement(flags) ? (
<Controller
name="eventStatusBlocked"
control={control}
defaultValue={selectedSearchValues.eventStatusBlocked}
render={({ value, name, onChange }) => (
<>
<Label
label={t('form.eventStatus')}
className="event-search-form__event-status-label"
id="eventStatus"
testId="event-status-label"
/>
<div className={eventSearchFormBlockedStyles}>
<Checkbox
checked={!!value}
disabled={disableEventStatus}
name={name}
className="event-search-form__blocked-checkbox"
data-testid="event-search-form-blocked-checkbox"
color="primary"
onChange={(event) => {
onChange(event.target.checked);
}}
/>
<p className="event-search-form__blocked-label">
{t('form.blockedLabel')}
</p>
</div>
</>
)}
/>
) : (
<>
<Label testId="event-status-label" label={t('form.eventStatus')} />
<FormGroup>
{checkBoxes.map(({ labelName, formName }, index) => (
<FormControlLabel
label={t(`form.${labelName}`)}
key={labelName}
control={
<Controller
name={formName}
control={control}
defaultValue={!!selectedSearchValues[formName]}
render={({ onChange, value }) => (
<Checkbox
checked={!!value}
name={formName}
className="event-search-form__event-status-checkbox"
data-testid={
index === 0
? 'event-search-form-blocked-checkbox'
: undefined
}
color="primary"
onChange={(event) => onChange(event.target.checked)}
/>
)}
/>
}
/>
))}
</FormGroup>
</>
)}
</div>
<div className="event-search-form__date-container">
<Controller
control={control}
name="eventDate"
defaultValue={selectedSearchValues.eventDate}
render={({ onChange, value, name }) => (
<RadioGroup
label={t('form.eventDate')}
onChangeRadio={onChange}
testId="event-search-form-event-date"
options={eventDateOptions}
name={name}
value={value}
/>
)}
/>
<Controller
control={control}
name="fromDate"
defaultValue={selectedSearchValues.fromDate}
render={({ onChange, value, name }) => (
<DateTimePicker
label={t('form.from')}
testId="event-search-form-from-date"
name={name}
value={fromDateWatch || value}
maxDate={toDateWatch}
maxDateMessage={t('validations.fromMaxMessage')}
onChange={(updatedDate) => {
onChange(updatedDate);
setValue('eventDate', null);
}}
variant="dialog"
/>
)}
/>
<Controller
control={control}
name="toDate"
defaultValue={selectedSearchValues.toDate}
render={({ onChange, value, name }) => (
<DateTimePicker
label={t('form.to')}
testId="event-search-form-to-date"
name={name}
value={toDateWatch || value}
minDate={fromDateWatch}
minDateMessage={t('validations.toMinMessage')}
onChange={(newValue) => {
onChange(newValue);
setValue('eventDate', null);
}}
variant="dialog"
/>
)}
/>
</div>
<Button
testId="event-search-form-submit-button"
type="submit"
buttonColor="positive"
disabled={
!sportWatch ||
!competitionsWatch?.length ||
!isValid(toDateWatch) ||
!isValid(fromDateWatch) ||
!isBefore(fromDateWatch as Date, toDateWatch as Date) ||
isBefore(fromDateWatch as Date, new Date(MIN_DATE)) ||
isAfter(toDateWatch as Date, new Date(MAX_DATE)) ||
listEventsStatus === BranchStatus.LOADING
}
className="event-search-form__submit-button"
loading={listEventsStatus === BranchStatus.LOADING}
>
{t('common.cta.submit')}
</Button>
</form>
);
};
can I make this better so that I don't have to do this disabled={
!sportWatch ||
!competitionsWatch?.length ||
!isValid(toDateWatch) ||
!isValid(fromDateWatch) ||
!isBefore(fromDateWatch as Date, toDateWatch as Date) ||
isBefore(fromDateWatch as Date, new Date(MIN_DATE)) ||
isAfter(toDateWatch as Date, new Date(MAX_DATE)) ||
listEventsStatus === BranchStatus.LOADING
}
|
efe5e425f8258ccdea8cf30e2e53bbd2
|
{
"intermediate": 0.42776256799697876,
"beginner": 0.3684902489185333,
"expert": 0.2037472426891327
}
|
12,067
|
Lock down boot partition to Read only mode in linux server
|
d352bd9a10add06f9fbabc5d24930949
|
{
"intermediate": 0.37824246287345886,
"beginner": 0.2227569818496704,
"expert": 0.3990005850791931
}
|
12,068
|
- Fetch Account details using : XUP
- Fetch retirement type using : AR1
- Fetch brokerage distribution transaction using : EAMO510I
- Fetch accrued dividend brokerage distribution transaction using : RAMO427E
- Fetch merge expanded history using : MEG
- Fetch mutual fund distribution transaction using : RAMO112E
- Fetch accrued dividend mutual fund distribution transaction using : RAMO437A
- Fetch security details using : BFP
make the block diagram as easy as you can in understanding manner
|
8f1ae02e8098db2db121aceb015a16e1
|
{
"intermediate": 0.36990073323249817,
"beginner": 0.32955366373062134,
"expert": 0.3005455732345581
}
|
12,069
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include “smr.h”
#define REGION_NAME “anony”
#define REGION_ADDR 0x001000
#define REGION_SIZE 0x100000
#define CHUNK_SIZE 4096
typedef struct {
uint8_t* addr;
uint32_t size;
} chunk_t;
int main() {
smr_region region = {
.region_name = REGION_NAME,
.addr = REGION_ADDR,
.len = REGION_SIZE
};
smr_attr smr_attr = {
.cur_regions = ®ion,
.num = 1,
.alloc_name = “chunk”
};
uint32_t chunk_align = 4;
ot_smr_alloc_attr alloc_attr = {
.region_name = REGION_NAME,
.len = CHUNK_SIZE,
.align = chunk_align,
};
// initialize SMR
ot_s32 ret = ot_smr_init(&smr_attr);
if (ret != 0) {
printf(“SMR init error[%d]!\n”, ret);
return -1;
}
// allocate memory for chunk
chunk_t chunk;
chunk.size = CHUNK_SIZE;
alloc_attr.len = CHUNK_SIZE;
alloc_attr.region_name = REGION_NAME;
alloc_attr.align = chunk_align;
ret = ot_smr_alloc(&alloc_attr, (phys_addr*)&chunk.addr);
if (ret != 0) {
printf(“SMR alloc error[%d]!\n”, ret);
ot_smr_deinit();
return -1;
}
printf(“Chunk allocated at physical address 0x%08X with size %d bytes\n”, chunk.addr, chunk.size);
// create child process
pid_t child_pid = fork();
if (child_pid < 0) {
printf(“Failed to create child process!\n”);
ot_smr_munmap(chunk.addr, CHUNK_SIZE);
ot_smr_deinit();
return -1;
} else if (child_pid == 0) { // child process
// receive physical address from parent process
uint8_t* phys_addr;
read(STDIN_FILENO, &phys_addr, sizeof(phys_addr));
// map physical address to virtual address
void* vaddr = mmap(NULL, CHUNK_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(stdin), 0);
if (vaddr == MAP_FAILED) {
printf(“Failed to map physical address to virtual address!\n”);
return -1;
}
printf(“Child process: Chunk mapped to virtual address 0x%08X\n”, vaddr);
// add reference count to chunk
ret = ot_smr_add_ref(vaddr);
if (ret != 0) {
printf(“SMR add reference error[%d]!\n”, ret);
return -1;
}
// wait for parent process to terminate
sleep(5);
// remove chunk
munmap(vaddr, CHUNK_SIZE);
} else { // parent process
// map physical address to virtual address
void* vaddr = mmap(NULL, CHUNK_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(stdin), 0);
if (vaddr == MAP_FAILED) {
printf(“Failed to map physical address to virtual address!\n”);
return -1;
}
printf(“Parent process: Chunk mapped to virtual address 0x%08X\n”, vaddr);
// add reference count to chunk
ret = ot_smr_add_ref(vaddr);
if (ret != 0) {
printf(“SMR add reference error[%d]!\n”, ret);
munmap(vaddr, CHUNK_SIZE);
ot_smr_munmap(chunk.addr, CHUNK_SIZE);
ot_smr_deinit();
return -1;
}
// send physical address to child process
write(STDOUT_FILENO, &chunk.addr, sizeof(chunk.addr));
// wait for child process to terminate
int status;
wait(&status);
// remove chunk
munmap(vaddr, CHUNK_SIZE);
ot_smr_munmap(chunk.addr, CHUNK_SIZE);
ot_smr_deinit();
}
return 0;
}从 pid_t child_pid = fork();这一行开始解释一下每一行代码的意思
|
92bc9deb8d03de36a438cccb07973db6
|
{
"intermediate": 0.3246808350086212,
"beginner": 0.5286003351211548,
"expert": 0.146718829870224
}
|
12,070
|
Hi there!
|
a7321ab88fd92dc43a0ea45e7b6f2c14
|
{
"intermediate": 0.32267293334007263,
"beginner": 0.25843358039855957,
"expert": 0.4188934564590454
}
|
12,071
|
write some cross-platform python3 code, that plays videos from an m3u playlist in fullscreen.
there should be a text box in the center of the video, when you type the word "unlock" and hit the enter key, the application closes.
the meta key, alt keys and escape key should be disabled.
|
b2b0311df6d64f64e9acc79cdbca9174
|
{
"intermediate": 0.4050058126449585,
"beginner": 0.2772558033466339,
"expert": 0.31773841381073
}
|
12,072
|
ما وظيف جهاز spectrum analyzer
|
40fb03efb38d1157c7b5d287abba8092
|
{
"intermediate": 0.25591570138931274,
"beginner": 0.3461062014102936,
"expert": 0.3979780972003937
}
|
12,073
|
how to read cdf file common data format in python
|
90b48ef6ccc84378e09f2162cf5db3e4
|
{
"intermediate": 0.5417335033416748,
"beginner": 0.2636825740337372,
"expert": 0.19458389282226562
}
|
12,074
|
- Fetch Account details using : XUP
- Fetch retirement type using : AR1
- Fetch brokerage distribution transaction using : EAMO510I
- Fetch accrued dividend brokerage distribution transaction using : RAMO427E
- Fetch merge expanded history using : MEG
- Fetch mutual fund distribution transaction using : RAMO112E
- Fetch accrued dividend mutual fund distribution transaction using : RAMO437A
- Fetch security details using : BFP
make the block diagram of above information nicely and in understanding manner
|
02639e1d953bd278ce30c6fe18ee5c89
|
{
"intermediate": 0.3530593812465668,
"beginner": 0.3032133877277374,
"expert": 0.3437272012233734
}
|
12,075
|
Please find the errors in this code : def plot_epam_lefs60(date1, date2, ax, filename, bins=['F1P','F2P','F3P','F4P'] ,cadence=None):
import pandas
import re
headers = ['EPOCH','F1P','F2P','F3P','F4P','UF1P','UF2P','UF3P','UF4P']
data = []
with open(filename, 'r') as f:
for line in f:
# Use regular expression to match datetime and other columns
match = re.match(r"(\d{2}-\d{2}-\d{4}\s+\d{2}:\d{2}:\d{2}.\d+)\s+(.*)", line.strip())
if match:
row = [match.group(1)] + match.group(2).split()
data.append(row)
frame = pd.DataFrame(data, columns=headers)
# Convert the EPOCH column to pandas datetime format
frame['EPOCH'] = pd.to_datetime(frame['EPOCH'], format="%d-%m-%Y %H:%M:%S.%f")
#replace nans with 0 (-1e31)
frame[['F1P', 'F2P', 'F3P', 'F4P', 'UF1P','UF2P','UF3P','UF4P']]= frame[['F1P', 'F2P', 'F3P', 'F4P', 'UF1P','UF2P','UF3P','UF4P']].astype(float)
frame[['F1P', 'F2P', 'F3P', 'F4P', 'UF1P','UF2P','UF3P','UF4P']] = frame[['F1P', 'F2P', 'F3P', 'F4P','UF1P','UF2P','UF3P','UF4P']].applymap(lambda x: 0 if x < 0 else x)
filtered_frame = frame[(frame['EPOCH'] >= date1) & (frame['EPOCH'] <= date2)]
epambin_labels={'F1P':'0.045 - 0.062 MeV','F2P':'0.062 - 0.103 MeV','F3P':'0.103 - 0.175 MeV','F4P':'0.175 - 0.312 MeV'}
if cadence is not None:
filtered_frame=filtered_frame.set_index(['EPOCH'])
filtered_frame=filtered_frame.resample(cadence).mean()
for epambin in bins: ax.plot(filtered_frame.index, filtered_frame[epambin], label = epambin_labels[epambin])
#ax.plot(filtered_frame.index, filtered_frame['F1P'], label='EPAM 0.045 - 0.062 MeV')
#ax.plot(filtered_frame.index, filtered_frame['F2P'], label='EPAM 0.062 - 0.103 MeV')
#ax.plot(filtered_frame.index, filtered_frame['F3P'], label='EPAM 0.103 - 0.175 MeV')
#ax.plot(filtered_frame.index, filtered_frame['F4P'], label='EPAM 0.175 - 0.312 MeV')
# plot the filtered data
else:
for epambin in bins: ax.plot(filtered_frame['EPOCH'], filtered_frame[epambin], label= epambin_labels[epambin] )
|
dcd632e6128773e3fa20a2e5535cf75f
|
{
"intermediate": 0.3979516327381134,
"beginner": 0.40926069021224976,
"expert": 0.19278763234615326
}
|
12,076
|
В моем аудио-плеере нет расстояния между обложками. gap и max-width были использованы, дело в том, что обложки имеют свойство object-fit: cover; это как-то с этим связано. я удалил object-fit: cover и все равно тоже самое
<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>
<!-- audio player -->
<div class="audio-player">
<div class="row">
<% tracks.forEach((track, index) => { %>
<div class="col-md-3">
<div class="track">
<img src="/img/<%= track.image_filename || 'default-track-image.jpg' %>" alt="<%= track.title %>" width="200" height="200">
<div class="info">
<h4><%= track.title %></h4>
<p><%= track.album_title || "No Album" %></p>
<div class="progress-bar">
<div class="progress-bar-fill" style="width: 0;"></div>
</div>
<audio id="audio-<%= index %>" src="/tracks/<%= track.filename %>"></audio>
<button class="play-button" data-audio-id="audio-<%= index %>">
<i class="fa fa-play"></i>
</button>
</div>
</div>
</div>
<% }); %>
</div>
</div>
css:
/* audio player */
.audio-player {
display: flex;
flex-wrap: wrap;
/* justify-content: space-between; */
align-items: center;
width: 100%;
padding: 0 10px;
box-sizing: border-box;
gap: 30px;
}
.audio-player .track {
position: relative;
margin: 10px 5px;
max-width: 250px;
text-align: center;
}
.audio-player .info {
margin-top: 10px;
}
.audio-player .image-container {
position: relative;
overflow: hidden;
width: 150px;
height: 150px;
}
.audio-player img {
display: block;
margin: 0 auto;
width: 200px;
height: 200px;
object-fit: cover; /* Добавлено свойство object-fit */
transition: transform 0.3s ease-in-out;
}
.audio-player .overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
.audio-player .play-button {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: transparent;
border: none;
cursor: pointer;
outline: none;
transition: transform 0.3s ease-in-out;
}
.audio-player .play-button i {
color: #fff;
font-size: 24px;
}
.audio-player .progress-bar {
position: relative;
width: 100%;
height: 2px;
background-color: #ccc;
}
.audio-player .progress-bar-fill {
position: absolute;
top: 0;
left: 0;
height: 100%;
background-color: #f50;
transition: width 0.1s ease-in-out;
}
.audio-player li:hover img {
transform: scale(1.1);
}
.audio-player .track:hover .overlay {
opacity: 1;
}
.audio-player .track:hover .play-button {
transform: translate(-50%, -50%) scale(1.2);
}
.audio-player .track:hover .progress-bar-fill {
transition: width 0.5s ease-in-out;
}
@media (max-width: 768px) {
.audio-player .track {
margin: 10px 0;
width: 100%;
}
.audio-player .image-container {
width: 100%;
height: auto;
}
.audio-player img {
max-width: 100%;
height: auto;
transition: none;
}
.audio-player .overlay {
background-color: rgba(0, 0, 0, 0.7);
}
.audio-player .play-button {
transform: translate(-50%, -50%) scale(1.5);
}
}
|
11812649bccfe40589157f143dad05e4
|
{
"intermediate": 0.38909074664115906,
"beginner": 0.482824444770813,
"expert": 0.12808483839035034
}
|
12,077
|
Tell me how to make the result value appear positive even if it is negative in pineScript V5.
|
508029acfbc19d3de123b28ffb0f2ab4
|
{
"intermediate": 0.31157270073890686,
"beginner": 0.17271965742111206,
"expert": 0.5157075524330139
}
|
12,078
|
how to decrypt and create napsternetv ios inpv config file?
|
1d60ae71a7d4335ff0a3fd664a6854af
|
{
"intermediate": 0.3806016743183136,
"beginner": 0.2665642499923706,
"expert": 0.3528341054916382
}
|
12,079
|
. Implement a currency converter application in python
|
2dff820e9276183746300e5ef8379591
|
{
"intermediate": 0.41041678190231323,
"beginner": 0.14135928452014923,
"expert": 0.44822391867637634
}
|
12,080
|
Implement a budget calculator application in python
|
3eafb9d0a8bafc2d1a6aee4906cdb336
|
{
"intermediate": 0.46722787618637085,
"beginner": 0.24606510996818542,
"expert": 0.2867071032524109
}
|
12,081
|
python code (read file line by line)
|
6d1f1e5ae1575685454372bbb94dc1b3
|
{
"intermediate": 0.2778626084327698,
"beginner": 0.32947948575019836,
"expert": 0.39265796542167664
}
|
12,082
|
Implement a simple budget calculator application
|
48bc9637b0148310547c1ef4e522f6cb
|
{
"intermediate": 0.425382137298584,
"beginner": 0.3367255926132202,
"expert": 0.2378922700881958
}
|
12,083
|
Convert this Azure data factory expression into python(to use with pandas) if A and B are two columns.: and(isNull(A)==false(),or(B=='',isNull(B)==true()))
|
caf5e7b689f4fc324b0c0aa7df6a2402
|
{
"intermediate": 0.6011810302734375,
"beginner": 0.25610706210136414,
"expert": 0.14271187782287598
}
|
12,084
|
ак создать в гриде основанном на mui data grid отдельную панель с фильтрами? Можно использовать react-hook-form
|
93ce559eea2c8b697875d061834b958c
|
{
"intermediate": 0.42157065868377686,
"beginner": 0.21232683956623077,
"expert": 0.36610254645347595
}
|
12,085
|
products: List<Product>.from(json["products"]!.map((x) => Product.fromJson(x))), make null check in this to accept null
|
4974262df423139106403299d2b99924
|
{
"intermediate": 0.4329580068588257,
"beginner": 0.28048714995384216,
"expert": 0.28655484318733215
}
|
12,086
|
Как с помощью pdfplumber сжать pdf файлы в папке и её подпапках
|
e797107ea8883285c5a1ecf52ce536fc
|
{
"intermediate": 0.27576783299446106,
"beginner": 0.4827945828437805,
"expert": 0.24143759906291962
}
|
12,087
|
how do you subtract one day from a boost date in c++
|
8ad5ca19f2305fa8642bdffb51f27472
|
{
"intermediate": 0.301395058631897,
"beginner": 0.3018922805786133,
"expert": 0.39671263098716736
}
|
12,088
|
server.go:563] external host was not specified, using
|
c9a460a8515282c73b47de72e5afb949
|
{
"intermediate": 0.33998289704322815,
"beginner": 0.327406644821167,
"expert": 0.33261045813560486
}
|
12,089
|
javascrit how to check array defined or not
|
f0d70587f20524b03a491d94ada4fa3f
|
{
"intermediate": 0.6530170440673828,
"beginner": 0.1321614384651184,
"expert": 0.21482151746749878
}
|
12,090
|
<div id="thumb-content-9"><img onclick="f_showdetailimage('sgce/images/44_Consumer_Electronics-OCT21_1-043.jpg', 'mainimg_9',9);" data-toggle="modal" data-target="#showdetail" title="Shenzhen Chitado Technology Co. Ltd" id="mainimg_9" class="lazy coupon_img imagefadein-x" data-checker="checked_9_landing" data-original="sgce/images/44_Consumer_Electronics-OCT21_1-043.jpg?l=3373644323" style="width: 400px;" alt="scooter, hoverboard, gyroor, chitado" src="sgce/images/44_Consumer_Electronics-OCT21_1-043.jpg?l=3373644323"></div>
I have above html, I want to add a image preloader while the image "mainimg_9" is loading.
|
d0a3881ec6496fac489e76d336876a5a
|
{
"intermediate": 0.4096631705760956,
"beginner": 0.24776451289653778,
"expert": 0.34257230162620544
}
|
12,091
|
нужно добавить сжатие добавляемых mp3 файлов по битрейту:
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"));
connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => {
if(err) throw err;
});
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
//функция для получения песен музыканта по id
function getMusicianTracks(musicianId, callback) {
connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => {
if (err) {
console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result);
}
});
}
function getMusicians(callback) {
connection.query("SELECT * FROM users", (err, result) => {
if (err) {
console.error("Ошибка при получении списка музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
// Функция для получения музыканта по id
function getMusicianById(id, callback) {
connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
if (err) {
console.error("Ошибка при получении музыканта с id ${id}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result[0]);
}
});
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];
// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}
// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.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
};
});
// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;
if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}
// Сортировка по score (убывающая)
return scoreB - scoreA;
});
// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}
app.use((req, res, next) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении current user: ", err);
} else {
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
}
});
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
res.status(500).send("Ошибка получения данных");
} else {
res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' });
}
});
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT DISTINCT city FROM users 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:'', query:'',role:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {
// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
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_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});
app.get("/profile/:id", (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
getMusicianTracks(musician.id, (err, tracks) => {
if(err) {
console.error("Ошибка при получении треков для профиля: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
res.render("profile", { musician: musician, tracks: tracks, query:'', role:'', city:''});
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
if (err) {
console.error("Ошибка при входе: ", err);
res.status(500).send("Ошибка при входе");
} else {
if (result.length > 0) {
req.session.musicianId = result[0].id;
res.redirect("/profile/" + result[0].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) => {
let query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
const genre = req.query.genre || '';
if (query || role || city || genre) {
search(query, role, city, genre, (err, musicians) => {
if (err) {
res.status(500).send("Ошибка при выполнении поиска");
} else {
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
} else {
// Use the getMusicians function instead of reading from musicians.json
getMusicians((err, musiciansList) => {
if (err) {
res.status(500).send("Ошибка при получении списка музыкантов");
} else {
const musicians = musiciansList.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
};
});
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
}
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
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 musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
//загрузка музыки и изображений к музыке
app.post("/profile/:id/upload", requireLogin, async (req, res) => {
const musicianId = req.session.musicianId;
if (!req.files) {
res.status(400).send("No files were uploaded.");
return;
}
const trackFile = req.files.track;
if (!trackFile) {
res.status(400).send("No track file was uploaded.");
return;
}
if (trackFile && !trackFile.name.endsWith(".mp3")) {
res.status(400).send("Only .mp3 files can be uploaded.");
return;
}
// Set a maximum file size of 10MB for uploaded files
const maxSizeInBytes = 10000000; // 10MB
if (trackFile && trackFile.size > maxSizeInBytes) {
res.status(400).send("File size exceeds 10MB limit.");
return;
}
const trackFilename = "track_" + musicianId + "" + trackFile.name;
trackFile.mv("./public/tracks/" + trackFilename);
const title = req.body.title;
const album_title = req.body.albumTitle;
const track = {
musician_id: musicianId,
title,
album_title,
filename: trackFilename,
};
if (req.files.image) {
const imageFile = req.files.image;
const imageFilename = "image" + musicianId + "_" + imageFile.name;
imageFile.mv("./public/img/" + imageFilename);
track.image_filename = imageFilename;
}
connection.query("INSERT INTO tracks SET ?", track, (err, result) => {
if (err) {
console.error("Ошибка при добавлении трека: ", err);
res.status(500).send("Ошибка при добавлении трека");
} else {
res.redirect("/profile/" + musicianId);
}
});
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
|
fbc28bf1f848a5ca3e58472a51198216
|
{
"intermediate": 0.30173641443252563,
"beginner": 0.5026488900184631,
"expert": 0.19561469554901123
}
|
12,092
|
redis_pool = redis.ConnectionPool(host="127.0.0.1", port=6379)
redis_client = redis.Redis(connection_pool=redis_pool , decode_responses=True)
data = redis_client.get("_a_key_123").decode()
`AttributeError: 'NoneType' object has no attribute 'decode'`
|
7e206c2e7fa434046bd67b76fc82db19
|
{
"intermediate": 0.5219528675079346,
"beginner": 0.2433929294347763,
"expert": 0.2346542328596115
}
|
12,093
|
how long can lemerence last if you stop seeing the person? is this a state that can come and go?
|
3b2c9b52e54fa427b4bd1a5d825a2dfc
|
{
"intermediate": 0.3622395098209381,
"beginner": 0.3281383812427521,
"expert": 0.30962204933166504
}
|
12,094
|
say this more succinctly: This example is showing complexity between two ‘Homegrown’ FPCs. There’s additional complexity when one considers ‘Acquisition Deal’ FPCs.
|
3664418929af7261c8fbcb033f8c9acf
|
{
"intermediate": 0.3235650658607483,
"beginner": 0.3575844466686249,
"expert": 0.31885048747062683
}
|
12,095
|
You are a professional programmer with decades of experience with decades of experience in every known language. write me a short python script that pulls the latest 100 tweets from twitter. show me step by step
|
9e2698d9083d13871aeddec38c70e03c
|
{
"intermediate": 0.4833277463912964,
"beginner": 0.24859829246997833,
"expert": 0.2680739760398865
}
|
12,096
|
почему-то мой скрипт не запоминает сессию. я логинюсь (/login), но возвращаясь назад на index, в навигационной панели не показывается, что я залогинен, там должно быть сообщение вроде "hello, username", но этого нет. Просмотри код и найди ошибку:
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"));
connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => {
if(err) throw err;
});
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
//функция для получения песен музыканта по id
function getMusicianTracks(musicianId, callback) {
connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => {
if (err) {
console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result);
}
});
}
function getMusicians(callback) {
connection.query("SELECT * FROM users", (err, result) => {
if (err) {
console.error("Ошибка при получении списка музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
// Функция для получения музыканта по id
function getMusicianById(id, callback) {
connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
if (err) {
console.error("Ошибка при получении музыканта с id ${id}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result[0]);
}
});
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];
// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}
// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.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
};
});
// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;
if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}
// Сортировка по score (убывающая)
return scoreB - scoreA;
});
// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}
app.use((req, res, next) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении current user: ", err);
} else {
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
}
});
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
res.status(500).send("Ошибка получения данных");
} else {
res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' });
}
});
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT DISTINCT city FROM users 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/" + musicianId);
} else {
res.render("register", { citiesAndRegions, city:'', query:'',role:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {
// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
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_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});
app.get("/profile/:id", (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
getMusicianTracks(musician.id, (err, tracks) => {
if(err) {
console.error("Ошибка при получении треков для профиля: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
res.render("profile", { musician: musician, tracks: tracks, query:'', role:'', city:''});
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
if (err) {
console.error("Ошибка при входе: ", err);
res.status(500).send("Ошибка при входе");
} else {
if (result.length > 0) {
req.session.musicianId = result[0].id;
res.redirect("/profile/" + result[0].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) => {
let query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
const genre = req.query.genre || '';
if (query || role || city || genre) {
search(query, role, city, genre, (err, musicians) => {
if (err) {
res.status(500).send("Ошибка при выполнении поиска");
} else {
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
} else {
// Use the getMusicians function instead of reading from musicians.json
getMusicians((err, musiciansList) => {
if (err) {
res.status(500).send("Ошибка при получении списка музыкантов");
} else {
const musicians = musiciansList.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
};
});
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
}
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
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 musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
//загрузка музыки и изображений к музыке
app.post("/profile/:id/upload", requireLogin, async (req, res) => {
const musicianId = req.session.musicianId;
if (!req.files) {
res.status(400).send("No files were uploaded.");
return;
}
const trackFile = req.files.track;
if (!trackFile) {
res.status(400).send("No track file was uploaded.");
return;
}
if (trackFile && !trackFile.name.endsWith(".mp3")) {
res.status(400).send("Only .mp3 files can be uploaded.");
return;
}
// Set a maximum file size of 10MB for uploaded files
const maxSizeInBytes = 10000000; // 10MB
if (trackFile && trackFile.size > maxSizeInBytes) {
res.status(400).send("File size exceeds 10MB limit.");
return;
}
const trackFilename = "track_" + musicianId + "" + trackFile.name;
const tmpPath = './public/tracks/tmp_' + trackFilename;
trackFile.mv("./public/tracks/" + trackFilename);
const title = req.body.title;
const album_title = req.body.albumTitle;
const track = {
musician_id: musicianId,
title,
album_title,
filename: trackFilename,
};
if (req.files.image) {
const imageFile = req.files.image;
const imageFilename = "image" + musicianId + "_" + imageFile.name;
imageFile.mv("./public/img/" + imageFilename);
track.image_filename = imageFilename;
}
connection.query("INSERT INTO tracks SET ?", track, (err, result) => {
if (err) {
console.error("Ошибка при добавлении трека: ", err);
res.status(500).send("Ошибка при добавлении трека");
} else {
res.redirect("/profile/" + musicianId);
}
});
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
|
873603efb815247af5c63b3acda1d1de
|
{
"intermediate": 0.378420889377594,
"beginner": 0.47585004568099976,
"expert": 0.14572910964488983
}
|
12,097
|
You are a professional programmer with decades of experience with decades of experience in every known language. write me a short python script that pulls the latest 100 tweets from twitter. show me step by step
|
3fe04bea565c8ead2164a1c9dea5a9d6
|
{
"intermediate": 0.4833277463912964,
"beginner": 0.24859829246997833,
"expert": 0.2680739760398865
}
|
12,098
|
how to use python to detect the outcome of command "nmap -sn <ip_address> --max-retries 1"
|
677a8bd04cf275aaf7fbc9dff6913b17
|
{
"intermediate": 0.44150495529174805,
"beginner": 0.19531673192977905,
"expert": 0.3631783127784729
}
|
12,099
|
Write a Java method to calculate Telephone Bill
Write a program to calculate the monthly telephone bills as per the following rule:
Minimum Rs. 200 for up to 100 calls.
Plus Rs. 0.60 per call for next 50 calls.
Plus Rs. 0.50 per call for next 50 calls.
Plus Rs. 0.40 per call for any call beyond 200 calls.
|
2329b59083cbcd1b6f896dd96803570d
|
{
"intermediate": 0.35267767310142517,
"beginner": 0.2502622902393341,
"expert": 0.3970600962638855
}
|
12,100
|
how to use python to detect the outcome of command "nmap -sn <ip_address> --max-retries 1"
|
6418d7f4dcad2e2d9b74910ac9f595a8
|
{
"intermediate": 0.44150495529174805,
"beginner": 0.19531673192977905,
"expert": 0.3631783127784729
}
|
12,101
|
почему-то мой скрипт не запоминает сессию. я логинюсь (/login), но возвращаясь назад на index, в навигационной панели не показывается, что я залогинен, хотя я залогинен и могу редактировать свой профиль, на index.ejs должно быть сообщение вроде “hello, username”, и если залогинен, предложение с ссылкой на logout, но этого нет. Просмотри код и найди ошибку:
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"));
connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => {
if(err) throw err;
});
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
//функция для получения песен музыканта по id
function getMusicianTracks(musicianId, callback) {
connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => {
if (err) {
console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result);
}
});
}
function getMusicians(callback) {
connection.query("SELECT * FROM users", (err, result) => {
if (err) {
console.error("Ошибка при получении списка музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
// Функция для получения музыканта по id
function getMusicianById(id, callback) {
connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
if (err) {
console.error("Ошибка при получении музыканта с id ${id}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result[0]);
}
});
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];
// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}
// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.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
};
});
// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;
if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}
// Сортировка по score (убывающая)
return scoreB - scoreA;
});
// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}
app.use((req, res, next) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении current user: ", err);
res.locals.userLoggedIn = false;
} else {
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
}
next();
});
} else {
res.locals.userLoggedIn = false;
next();
}
});
app.get("/", (req, res) => {
getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
res.status(500).send("Ошибка получения данных");
} else {
res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' });
}
});
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT DISTINCT city FROM users 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/" + musicianId);
} else {
res.render("register", { citiesAndRegions, city:'', query:'',role:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {
// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
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_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});
app.get("/profile/:id", (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
getMusicianTracks(musician.id, (err, tracks) => {
if(err) {
console.error("Ошибка при получении треков для профиля: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
res.render("profile", { musician: musician, tracks: tracks, query:'', role:'', city:''});
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
if (err) {
console.error("Ошибка при входе: ", err);
res.status(500).send("Ошибка при входе");
} else {
if (result.length > 0) {
req.session.musicianId = result[0].id;
res.redirect("/profile/" + result[0].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) => {
let query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
const genre = req.query.genre || '';
if (query || role || city || genre) {
search(query, role, city, genre, (err, musicians) => {
if (err) {
res.status(500).send("Ошибка при выполнении поиска");
} else {
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
} else {
// Use the getMusicians function instead of reading from musicians.json
getMusicians((err, musiciansList) => {
if (err) {
res.status(500).send("Ошибка при получении списка музыкантов");
} else {
const musicians = musiciansList.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
};
});
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
}
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
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 musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
//загрузка музыки и изображений к музыке
app.post("/profile/:id/upload", requireLogin, async (req, res) => {
const musicianId = req.session.musicianId;
if (!req.files) {
res.status(400).send("No files were uploaded.");
return;
}
const trackFile = req.files.track;
if (!trackFile) {
res.status(400).send("No track file was uploaded.");
return;
}
if (trackFile && !trackFile.name.endsWith(".mp3")) {
res.status(400).send("Only .mp3 files can be uploaded.");
return;
}
// Set a maximum file size of 10MB for uploaded files
const maxSizeInBytes = 10000000; // 10MB
if (trackFile && trackFile.size > maxSizeInBytes) {
res.status(400).send("File size exceeds 10MB limit.");
return;
}
const trackFilename = "track_" + musicianId + "" + trackFile.name;
const tmpPath = './public/tracks/tmp_' + trackFilename;
trackFile.mv("./public/tracks/" + trackFilename);
const title = req.body.title;
const album_title = req.body.albumTitle;
const track = {
musician_id: musicianId,
title,
album_title,
filename: trackFilename,
};
if (req.files.image) {
const imageFile = req.files.image;
const imageFilename = "image" + musicianId + "_" + imageFile.name;
imageFile.mv("./public/img/" + imageFilename);
track.image_filename = imageFilename;
}
connection.query("INSERT INTO tracks SET ?", track, (err, result) => {
if (err) {
console.error("Ошибка при добавлении трека: ", err);
res.status(500).send("Ошибка при добавлении трека");
} else {
res.redirect("/profile/" + musicianId);
}
});
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="/css/main.css" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="/jquery-ui/themes/base/all.css" rel="stylesheet">
<title>Home</title>
</head>
<body>
<header class="header">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="/">
<img src="/img/logo.png" alt="My Musician Site">
</a>
<button aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarNav" data-toggle="collapse" type="button">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#find-musicians">Find Musicians</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/register"><i class="fa fa-user-plus" aria-hidden="true"></i> Register</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/login"><i class="fa fa-sign-in" aria-hidden="true"></i> Login</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="hero">
<div class="container">
<h1 class="hero-title">Find the Perfect Musician for Your Band or Project</h1>
<p class="hero-subtitle">Join our community today and connect with talented musicians from around the world.</p>
<a class="btn btn-primary btn-lg" href="/register">Register Now</a>
</div>
</div>
</header>
<main class="main">
<section class="section section-search" id="find-musicians">
<div class="container">
<h2 class="section-title"><i class="fa fa-search" aria-hidden="true"></i> Find Musicians</h2>
<form class="form-search" action="/search" method="get">
<div class="form-group">
<label for="role"><i class="fa fa-users" aria-hidden="true"></i> Role:</label>
<select class="form-control" id="role" name="role">
<option value="">All</option>
<option value="Band">Band</option>
<option value="Artist">Artist</option>
</select>
</div>
<div class="form-group">
<label for="genre">Search by genre:</label>
<select class="form-control" id="genre" name="genre">
<option value="">All</option>
</select>
</div>
<div class="form-group">
<label for="city"><i class="fa fa-map-marker" aria-hidden="true"></i> Location:</label>
<input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value="">
</div>
<button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button>
</form>
</div>
</section>
<!-- последние зарегистрированные пользователи -->
<section class="musicians">
<div class="container">
<h2>Find Musicians</h2>
<div class="row">
<% musicians.forEach(function(musician) { %>
<div class="col-lg-4 col-md-6 col-sm-12">
<div class="musician-card">
<div class="musician-info">
<h3><%= musician.name %></h3>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
</div>
<div class="musician-link">
<a href="/musicians/<%= musician.id %>">View profile</a>
</div>
</div>
</div>
<% }); %>
</div>
</div>
</section>
<!-- end -->
</main>
<footer class="footer">
<div class="container">
<p class="text-center mb-0">My Musician Site © 2023</p>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></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>
<script>
const genres = ["Rock", "Pop", "Jazz", "Blues", "Country"];
const genreSelect = document.querySelector("#genre");
genres.forEach((genre) => {
const option = document.createElement("option");
option.value = genre;
option.text = genre;
genreSelect.appendChild(option);
});
</script>
</body>
</html>
|
1320844385298158aa7eea87f9c1789d
|
{
"intermediate": 0.32682254910469055,
"beginner": 0.45064297318458557,
"expert": 0.2225344479084015
}
|
12,102
|
<!DOCTYPE html>
<html>
<head>
<title>tab editor</title>
<meta name=“viewport” content=“width=device-width, initial-scale=1”>
<link rel=“stylesheet” type=“text/css” href=“https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css”>
<script src=“https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
<script src=“https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js”></script>
<script src=“https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js”></script>
<link rel=“stylesheet” type=“text/css” href=“guitar_tab_editor.css”>
<script src=“guitar_tab_editor.js”></script>
</head>
<body>
<div class=“container”>
<h2>Guitar Tab Editor</h2>
<br>
<p>Write the guitar tab in the text area below. Use Time Signature and Key Signature below to adjust your tablature if needed:</p>
<div class=“form-group”>
<textarea class=“form-control” rows=“12” id=“guitar_tab_textarea”></textarea>
</div>
<div class=“form-inline”>
<label for=“time_signature”>Time Signature:</label>
<select class=“form-control” id=“time_signature”>
<option>2/4</option>
<option>3/4</option>
<option selected>4/4</option>
<option>6/8</option>
<option>9/8</option>
<option>12/8</option>
</select>
<label for=“key_signature”>Key Signature:</label>
<select class=“form-control” id=“key_signature”>
<option selected>C</option>
<option>C#/Db</option>
<option>D</option>
<option>D#/Eb</option>
<option>E</option>
<option>F</option>
<option>F#/Gb</option>
<option>G</option>
<option>G#/Ab</option>
<option>A</option>
<option>A#/Bb</option>
<option>B</option>
</select>
</div>
<br>
<button type=“button” class=“btn btn-primary” onclick=“updateGuitarTab()”>Update Tab</button>
<button type=“button” class=“btn btn-danger” onclick=“clearGuitarTab()”>Clear Tab</button>
<br><br>
<p>Your Guitar Tab:</p>
<div id=“guitar_tab_display” class=“jumbotron”></div>
</div>
</body>
</html>
guitar_tab_editor.css:
|
cb4b5e069419885c3d2946f1ca153979
|
{
"intermediate": 0.24505527317523956,
"beginner": 0.3979710340499878,
"expert": 0.35697364807128906
}
|
12,103
|
import snscrape.modules.twitter as sntwitter
import pandas as pd
query = "Seattle Kraken"
for tweet in sntwitter.TwitterSearchScraper(query).get_items():
print(vars(tweet))
could you please tell me how to make it only print the last 100 item and also save them to a csv file please and thank you
|
f4a4fadeebabe27226778b3ec3865272
|
{
"intermediate": 0.7394992709159851,
"beginner": 0.11982506513595581,
"expert": 0.1406756490468979
}
|
12,104
|
import snscrape.modules.twitter as sntwitter
import pandas as pd
query = "Seattle Kraken"
for tweet in sntwitter.TwitterSearchScraper(query).get_items():
print(vars(tweet))
could you please tell me how to make it only print the last 100 item and also save them to a csv file please and thank you
|
d6ad138acd324ca3d9bdcb7e9c91714a
|
{
"intermediate": 0.7394992709159851,
"beginner": 0.11982506513595581,
"expert": 0.1406756490468979
}
|
12,105
|
import snscrape.modules.twitter as sntwitter
query = "Seattle Kraken"
for tweet in sntwitter.TwitterSearchScraper(query).get_items():
print(vars(tweet))
could you please tell me how to make it only print the last 100 item and also save them to a csv file please and thank you
|
75472ec8aad1bb4481f8528d0d583291
|
{
"intermediate": 0.6745213866233826,
"beginner": 0.14421023428440094,
"expert": 0.18126839399337769
}
|
12,106
|
import snscrape.modules.twitter as sntwitter
query = "Seattle Kraken"
for tweet in sntwitter.TwitterSearchScraper(query).get_items():
print(vars(tweet))
could you please tell me how to make it only print the last 100 item and also save them to a csv file please and thank you
|
f3c3e4b66a5b1b4e586d6e11b8f38d23
|
{
"intermediate": 0.6745213866233826,
"beginner": 0.14421023428440094,
"expert": 0.18126839399337769
}
|
12,107
|
javascript, I want to use filter & indexOf to search some values. How can I use multi-condition with indexOf?
|
57e57d92913e5cac9750a11abda83858
|
{
"intermediate": 0.4802613854408264,
"beginner": 0.16304224729537964,
"expert": 0.35669636726379395
}
|
12,108
|
write some javascript code to display 100 rectangles , and allow for them to be dynamically added, updated, or removed via a websocket connection
|
e44e762074f40d21bd2c70cb8bbbf487
|
{
"intermediate": 0.5775847434997559,
"beginner": 0.16633422672748566,
"expert": 0.25608110427856445
}
|
12,109
|
could you please show me step by step how to scrape the last 100 tweets from the query Counter Strike 2 and save the result to a csv file please and without using the twitter API at all or tweepy thank you
|
1188d00f3d617e9d91a6c4ef3cfe7f26
|
{
"intermediate": 0.7392127513885498,
"beginner": 0.09177708625793457,
"expert": 0.16901011765003204
}
|
12,110
|
AttributeError: 'NoneType' object has no attribute 'drop'
|
e0d77ff1f6fe98048f8e3a4f1abc284d
|
{
"intermediate": 0.4644468426704407,
"beginner": 0.24241387844085693,
"expert": 0.2931393086910248
}
|
12,111
|
write me C++ code for a loop to include the same time scale in X-axis, and same amount of increasing of field in Y-axis after that time, and then move into the next time scale for the lopp
|
4869f2bf39fd2fdcd0ac2b484bf3a7a9
|
{
"intermediate": 0.29336297512054443,
"beginner": 0.39190101623535156,
"expert": 0.3147360384464264
}
|
12,112
|
test case for getCarePlanDetails(indvId:string):Observable<any> {
return this.http
// .get(`${this.baseUrl}/careplan_document?indvId=`+ "2721060")
.get(`http://localhost:8081/member/api/v1.0.0/careplan_document?indvId=`+ "2721060")
.pipe(retry(3), catchError(this.sharedDataService.handleErrors()));
}
|
702d1c0f423b3e5c6ec451e657ae24e7
|
{
"intermediate": 0.4538659155368805,
"beginner": 0.35914647579193115,
"expert": 0.18698760867118835
}
|
12,113
|
я хочу использовать вместо недавно зарегистрированных пользователей в index.ejs недавно загруженные .mp3 файлы из profile.ejs пользователей. index.ejs я уже поменял, добавив <section class="musicians">
<div class="container">
<h2>Recent Uploads</h2>
<div class="row">
<% tracks.forEach(function(track) { %>
осталось изменить app.get("/", (req, res) => чтобы треки рендерились в index.ejs.
Вот код:
index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="/css/main.css" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="/jquery-ui/themes/base/all.css" rel="stylesheet">
<title>Home</title>
</head>
<body>
<header class="header">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="/">
<img src="/img/logo.png" alt="My Musician Site">
</a>
<button aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarNav" data-toggle="collapse" type="button">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#find-musicians">Find Musicians</a>
</li>
<% if (!userLoggedIn) { %>
<li class="nav-item">
<a class="nav-link" href="/register"><i class="fa fa-user-plus" aria-hidden="true"></i> Register</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/login"><i class="fa fa-sign-in" aria-hidden="true"></i> Login</a>
</li>
<% } else { %>
<li class="nav-item">
<a class="nav-link"><i class="fa fa-user" aria-hidden="true"></i> Hello, <%= username %></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/logout"><i class="fa fa-sign-out" aria-hidden="true"></i> Logout</a>
</li>
<% } %>
</ul>
</div>
</div>
</nav>
<div class="hero">
<div class="container">
<h1 class="hero-title">Find the Perfect Musician for Your Band or Project</h1>
<p class="hero-subtitle">Join our community today and connect with talented musicians from around the world.</p>
<a class="btn btn-primary btn-lg" href="/register">Register Now</a>
</div>
</div>
</header>
<main class="main">
<section class="section section-search" id="find-musicians">
<div class="container">
<h2 class="section-title"><i class="fa fa-search" aria-hidden="true"></i> Find Musicians</h2>
<form class="form-search" action="/search" method="get">
<div class="form-group">
<label for="role"><i class="fa fa-users" aria-hidden="true"></i> Role:</label>
<select class="form-control" id="role" name="role">
<option value="">All</option>
<option value="Band">Band</option>
<option value="Artist">Artist</option>
</select>
</div>
<div class="form-group">
<label for="genre">Search by genre:</label>
<select class="form-control" id="genre" name="genre">
<option value="">All</option>
</select>
</div>
<div class="form-group">
<label for="city"><i class="fa fa-map-marker" aria-hidden="true"></i> Location:</label>
<input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value="">
</div>
<button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button>
</form>
</div>
</section>
<!-- последние зарегистрированные пользователи -->
<section class="musicians">
<div class="container">
<h2>Recent Uploads</h2>
<div class="row">
<% tracks.forEach(function(track) { %>
<div class="col-lg-4 col-md-6 col-sm-12">
<div class="track-card">
<div class="track-info">
<h3><%= track.title %></h3>
<p><strong>Album:</strong> <%= track.album_title || "No Album" %></p>
</div>
<div class="track-link">
<audio src="/tracks/<%= track.filename %>"></audio>
<button>Play</button>
</div>
</div>
</div>
<% }); %>
</div>
</div>
</section>
<!-- end -->
</main>
<footer class="footer">
<div class="container">
<p class="text-center mb-0">My Musician Site © 2023</p>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></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>
<script>
const genres = ["Rock", "Pop", "Jazz", "Blues", "Country"];
const genreSelect = document.querySelector("#genre");
genres.forEach((genre) => {
const option = document.createElement("option");
option.value = genre;
option.text = genre;
genreSelect.appendChild(option);
});
</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" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</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>
<!-- audio player -->
<p><strong>Tracks:</strong>
<div class="audio-player">
<div class="row">
<% tracks.forEach((track, index) => { %>
<div class="col-md-4 mb-3">
<div class="track">
<img src="/img/<%= track.image_filename || 'default-track-image.png' %>" alt="<%= track.title %>" width="200" height="200">
<div class="info">
<h4><%= track.title %></h4>
<p><%= track.album_title || "No Album" %></p>
<div class="progress-bar">
<div class="progress-bar-fill" style="width: 0;"></div>
</div>
<audio id="audio-<%= index %>" src="/tracks/<%= track.filename %>"></audio>
<button class="play-button" data-audio-id="audio-<%= index %>">
<i class="fa fa-play"></i>
</button>
</div>
</div>
</div>
<% }); %>
</div>
</div>
<!-- end -->
<% 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">×</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>
<h2>Upload a new track:</h2>
<form id="upload-form" action="/profile/<%= musician.id %>/upload" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="track">Track file:</label>
<input type="file" id="track" name="track" accept="audio/*" class="form-control-file" required>
<h4>only .mp3 allowed</h4>
</div>
<div class="form-group">
<label for="title">Track title:</label>
<input type="text" id="title" name="title" class="form-control" required>
</div>
<div class="form-group">
<label for="albumTitle">Album title:</label>
<input type="text" id="albumTitle" name="albumTitle" class="form-control">
</div>
<div class="form-group">
<label for="image">Track image:</label>
<input type="file" id="image" name="image" accept="image/*" class="form-control-file">
</div>
<button type="submit" class="btn btn-primary">Upload Track</button>
</form>
</div>
</div>
</div>
</div>
<% } %>
</div>
</div>
</div>
<script>
$(function() {
$('.play-button').on('click', function() {
var audioId = $(this).data('audio-id');
var audio = document.getElementById(audioId);
var isPaused = audio.paused;
$('.play-button').removeClass('active');
if (isPaused) {
audio.play();
$(this).addClass('active');
} else {
audio.pause();
}
});
$('audio').on('timeupdate', function() {
var audio = $(this)[0];
var progress = audio.currentTime / audio.duration * 100;
$(this).siblings('.progress-bar').find('.progress-bar-fill').css('width', progress + '%');
});
});
</script>
<script>
function submitForm(event) {
event.preventDefault();
const form = document.getElementById("upload-form");
const formData = new FormData(form);
fetch("/profile/:id/upload", {
method: "POST",
body: formData,
})
.then((response) => {
if (response.ok) {
// если запрос прошел успешно - обновляем страницу
location.reload();
} else {
// если что-то пошло не так - выводим сообщение об ошибке
alert("Error uploading track");
}
})
.catch((error) => {
console.error("Error:", error);
alert("Error uploading track");
});
}
// Заменяем элемент формы с кнопкой "submit" на обработчик события "submit"
document.getElementById("upload-form").addEventListener("submit", submitForm);
</script>
<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("#edit-profile-modal 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>
<style>
.ui-autocomplete {
z-index: 9999;
}
</style>
</body>
</html>
css:
.audio-player {
display: flex;
flex-wrap: wrap;
/* justify-content: space-between; */
align-items: center;
width: 100%;
padding: 0 10px;
box-sizing: border-box;
gap: 30px;
}
.audio-player .track {
position: relative;
margin: 10px 5px;
max-width: 250px;
text-align: center;
}
.audio-player .info {
margin-top: 10px;
}
.audio-player .image-container {
position: relative;
overflow: hidden;
width: 350px;
height: 350px;
}
.audio-player img {
display: block;
margin: 0 auto;
width: 200px;
height: 200px;
object-fit: cover; /* Добавлено свойство object-fit */
transition: transform 0.3s ease-in-out;
}
.audio-player .overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
.audio-player .play-button {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: transparent;
border: none;
cursor: pointer;
outline: none;
transition: transform 0.3s ease-in-out;
}
.audio-player .play-button i {
color: #fff;
font-size: 24px;
}
.audio-player .progress-bar {
position: relative;
width: 100%;
height: 2px;
background-color: #ccc;
}
.audio-player .progress-bar-fill {
position: absolute;
top: 0;
left: 0;
height: 100%;
background-color: #f50;
transition: width 0.1s ease-in-out;
}
.audio-player li:hover img {
transform: scale(1.1);
}
.audio-player .track:hover .overlay {
opacity: 1;
}
.audio-player .track:hover .play-button {
transform: translate(-50%, -50%) scale(1.2);
}
.audio-player .track:hover .progress-bar-fill {
transition: width 0.5s ease-in-out;
}
@media (max-width: 768px) {
.audio-player .track {
margin: 10px 0;
width: 100%;
}
.audio-player .image-container {
width: 100%;
height: auto;
}
.audio-player img {
max-width: 100%;
height: auto;
transition: none;
}
.audio-player .overlay {
background-color: rgba(0, 0, 0, 0.7);
}
.audio-player .play-button {
transform: translate(-50%, -50%) scale(1.5);
}
}
|
f9605fdd1edde33ce9f1ea552fac8e13
|
{
"intermediate": 0.21984507143497467,
"beginner": 0.5824708342552185,
"expert": 0.19768409430980682
}
|
12,114
|
whic is not a valid stack command ? A) STMED B)LDMFD C)LDMEI D)LDMFA
|
a9a86f5be556e029c9b8f1759470f687
|
{
"intermediate": 0.4680981934070587,
"beginner": 0.23870031535625458,
"expert": 0.2932015061378479
}
|
12,115
|
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
TOKEN = '5893668363:AAG_2N0n-lNagqMjglsR7EobAcJI_zWfNCI'
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
from aiogram import Poll, Options
def create_poll(update, context):
poll = Poll(question=“Choose a name:, options=[Options(name=“Name {}.format(i)) for i in range(10)])
context.reply(poll)
import sqlite3
connection = sqlite3.connect(‘poll_results.db’)
cursor = connection.cursor()
cursor.execute(‘’‘
CREATE TABLE IF NOT EXISTS poll_results
(id INTEGER PRIMARY KEY, name TEXT, votes INTEGER)
’‘’)
connection.commit()
import sqlite3
def save_poll_results(update, context):
poll_id = update.poll.id
options = update.poll.options
connection = sqlite3.connect(‘poll_results.db’)
cursor = connection.cursor()
for option in options:
name = option.text
votes = option.votes
cursor.execute(‘SELECT * FROM poll_results WHERE name=?’, (name,))
record = cursor.fetchone()
if record:
cursor.execute(‘UPDATE poll_results SET votes=? WHERE name=?’, (record[2] + votes, name))
else:
cursor.execute(‘INSERT INTO poll_results(name, votes) VALUES (?, ?)’, (name, votes))
connection.commit()
from iogram import PollHandler
bot.add_command(“poll”, create_poll)
bot.add_handler(PollHandler(save_poll_results))
Исправь этот код, чтобы он работал исправно
|
0e5d738960522cc96084e3cb61c8a2f4
|
{
"intermediate": 0.45758727192878723,
"beginner": 0.27983659505844116,
"expert": 0.2625761032104492
}
|
12,116
|
where are branch points stored in monocle3 object?
|
d5aaa2d2f35eed1e084d21ca3ea1b6bc
|
{
"intermediate": 0.4145890772342682,
"beginner": 0.19630037248134613,
"expert": 0.3891105353832245
}
|
12,117
|
you are an expert developer working on a VBA code and you have to write an AI code to learn to calculate the ratio of inspector assigned to each operation based on the number of operation, the time of inspection, numbre of operators, FPY, experience of operations, APQP, complexity, new operations, number of previous inspector
|
76dada4d899340cb5a46307722c6664c
|
{
"intermediate": 0.0999661311507225,
"beginner": 0.12180931866168976,
"expert": 0.7782245874404907
}
|
12,118
|
from aiogram import Bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor
TOKEN = '5893668363:AAG_2N0n-lNagqMjglsR7EobAcJI_zWfNCI'
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
from aiogram import Poll, Options
def create_poll(update, context):
poll = Poll(question=“Choose a name:, options=[Options(name=“Name {}.format(i)) for i in range(10)])
context.reply(poll)
import sqlite3
connection = sqlite3.connect(‘poll_results.db’)
cursor = connection.cursor()
cursor.execute(‘’‘
CREATE TABLE IF NOT EXISTS poll_results
(id INTEGER PRIMARY KEY, name TEXT, votes INTEGER)
’‘’)
connection.commit()
import sqlite3
def save_poll_results(update, context):
poll_id = update.poll.id
options = update.poll.options
connection = sqlite3.connect(‘poll_results.db’)
cursor = connection.cursor()
for option in options:
name = option.text
votes = option.votes
cursor.execute(‘SELECT * FROM poll_results WHERE name=?’, (name,))
record = cursor.fetchone()
if record:
cursor.execute(‘UPDATE poll_results SET votes=? WHERE name=?’, (record[2] + votes, name))
else:
cursor.execute(‘INSERT INTO poll_results(name, votes) VALUES (?, ?)’, (name, votes))
connection.commit()
from iogram import PollHandler
bot.add_command(“poll”, create_poll)
bot.add_handler(PollHandler(save_poll_results))
исправь этот код чтобы он работал исправно
|
552fb1e30f567b3ab8b626145ab5912d
|
{
"intermediate": 0.4976940453052521,
"beginner": 0.24956205487251282,
"expert": 0.2527438700199127
}
|
12,119
|
напиши код для телеграм бота, суть которого заключается в создании телеграм бота в котором после запуска бота появляется multiply vote, в котором участвуют десять учеников с разными цифрами, после выбора ответов в опросе, по другой команде можно вывести массив в который сохранены значеня опроса
|
11b1fad32d46082eacabfb76192920f5
|
{
"intermediate": 0.3845841884613037,
"beginner": 0.30572471022605896,
"expert": 0.3096911311149597
}
|
12,120
|
Write a Pseudocode on an approval matrix for PR
|
16476796a3cc3069620fac97b5b24e47
|
{
"intermediate": 0.29944396018981934,
"beginner": 0.35211580991744995,
"expert": 0.3484402298927307
}
|
12,121
|
I have a raspberry pi 4 and i have a macbook pro and i want to connect from the macbook pro to raspberry pi 4 using bluetooth in java (java application is on macbook pro) how do i do that? mind that i don't have internet on the raspberry pi... if you have any better ideas than bluetooth im all ears, but mainly how do i do it in java bluetooth
|
647609d53b6e0d1b2e1ef89f4fde4bfc
|
{
"intermediate": 0.5879735350608826,
"beginner": 0.1828254759311676,
"expert": 0.2292010337114334
}
|
12,122
|
я хочу использовать вместо недавно зарегистрированных пользователей в index.ejs недавно загруженные .mp3 файлы из profile.ejs пользователей. index.ejs я уже поменял. осталось добавить в app.get("/", (req, res) => {
сейчас я получаю ошибку ReferenceError: tracks is not defined
at C:\Users\Ilya\Downloads\my-musician-network\app.js:199:101
at Query.<anonymous> (C:\Users\Ilya\Downloads\my-musician-network\app.js:52:8)
код:
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"));
connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => {
if(err) throw err;
});
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
//функция для получения песен музыканта по id
function getMusicianTracks(musicianId, callback) {
connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => {
if (err) {
console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result);
}
});
}
function getMusicians(callback) {
connection.query("SELECT * FROM users", (err, result) => {
if (err) {
console.error("Ошибка при получении списка музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
// Функция для получения музыканта по id
function getMusicianById(id, callback) {
connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
if (err) {
console.error("Ошибка при получении музыканта с id ${id}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result[0]);
}
});
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];
// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}
// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.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
};
});
// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;
if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}
// Сортировка по score (убывающая)
return scoreB - scoreA;
});
// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}
app.use((req, res, next) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении current user: ", err);
res.locals.userLoggedIn = false;
} else {
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
}
next();
});
} else {
res.locals.userLoggedIn = false;
next();
}
});
app.get("/", (req, res) => {
getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
res.status(500).send("Ошибка получения данных");
} else {
res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'',tracks:tracks});
}
});
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT DISTINCT city FROM users 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/" + musicianId);
} else {
res.render("register", { citiesAndRegions, city:'', query:'',role:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {
// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
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_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});
app.get("/profile/:id", (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
getMusicianTracks(musician.id, (err, tracks) => {
if(err) {
console.error("Ошибка при получении треков для профиля: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
res.render("profile", { musician: musician, tracks: tracks, query:'', role:'', city:''});
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
if (err) {
console.error("Ошибка при входе: ", err);
res.status(500).send("Ошибка при входе");
} else {
if (result.length > 0) {
req.session.musicianId = result[0].id;
res.redirect("/profile/" + result[0].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) => {
let query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
const genre = req.query.genre || '';
if (query || role || city || genre) {
search(query, role, city, genre, (err, musicians) => {
if (err) {
res.status(500).send("Ошибка при выполнении поиска");
} else {
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
} else {
// Use the getMusicians function instead of reading from musicians.json
getMusicians((err, musiciansList) => {
if (err) {
res.status(500).send("Ошибка при получении списка музыкантов");
} else {
const musicians = musiciansList.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
};
});
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
}
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
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 musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
//загрузка музыки и изображений к музыке
app.post("/profile/:id/upload", requireLogin, async (req, res) => {
const musicianId = req.session.musicianId;
if (!req.files) {
res.status(400).send("No files were uploaded.");
return;
}
const trackFile = req.files.track;
if (!trackFile) {
res.status(400).send("No track file was uploaded.");
return;
}
if (trackFile && !trackFile.name.endsWith(".mp3")) {
res.status(400).send("Only .mp3 files can be uploaded.");
return;
}
// Set a maximum file size of 10MB for uploaded files
const maxSizeInBytes = 10000000; // 10MB
if (trackFile && trackFile.size > maxSizeInBytes) {
res.status(400).send("File size exceeds 10MB limit.");
return;
}
const trackFilename = "track_" + musicianId + "" + trackFile.name;
const tmpPath = './public/tracks/tmp_' + trackFilename;
trackFile.mv("./public/tracks/" + trackFilename);
const title = req.body.title;
const album_title = req.body.albumTitle;
const track = {
musician_id: musicianId,
title,
album_title,
filename: trackFilename,
};
if (req.files.image) {
const imageFile = req.files.image;
const imageFilename = "image" + musicianId + "_" + imageFile.name;
imageFile.mv("./public/img/" + imageFilename);
track.image_filename = imageFilename;
}
connection.query("INSERT INTO tracks SET ?", track, (err, result) => {
if (err) {
console.error("Ошибка при добавлении трека: ", err);
res.status(500).send("Ошибка при добавлении трека");
} else {
res.redirect("/profile/" + musicianId);
}
});
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="/css/main.css" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="/jquery-ui/themes/base/all.css" rel="stylesheet">
<title>Home</title>
</head>
<body>
<header class="header">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="/">
<img src="/img/logo.png" alt="My Musician Site">
</a>
<button aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarNav" data-toggle="collapse" type="button">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#find-musicians">Find Musicians</a>
</li>
<% if (!userLoggedIn) { %>
<li class="nav-item">
<a class="nav-link" href="/register"><i class="fa fa-user-plus" aria-hidden="true"></i> Register</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/login"><i class="fa fa-sign-in" aria-hidden="true"></i> Login</a>
</li>
<% } else { %>
<li class="nav-item">
<a class="nav-link"><i class="fa fa-user" aria-hidden="true"></i> Hello, <%= username %></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/logout"><i class="fa fa-sign-out" aria-hidden="true"></i> Logout</a>
</li>
<% } %>
</ul>
</div>
</div>
</nav>
<div class="hero">
<div class="container">
<h1 class="hero-title">Find the Perfect Musician for Your Band or Project</h1>
<p class="hero-subtitle">Join our community today and connect with talented musicians from around the world.</p>
<a class="btn btn-primary btn-lg" href="/register">Register Now</a>
</div>
</div>
</header>
<main class="main">
<section class="section section-search" id="find-musicians">
<div class="container">
<h2 class="section-title"><i class="fa fa-search" aria-hidden="true"></i> Find Musicians</h2>
<form class="form-search" action="/search" method="get">
<div class="form-group">
<label for="role"><i class="fa fa-users" aria-hidden="true"></i> Role:</label>
<select class="form-control" id="role" name="role">
<option value="">All</option>
<option value="Band">Band</option>
<option value="Artist">Artist</option>
</select>
</div>
<div class="form-group">
<label for="genre">Search by genre:</label>
<select class="form-control" id="genre" name="genre">
<option value="">All</option>
</select>
</div>
<div class="form-group">
<label for="city"><i class="fa fa-map-marker" aria-hidden="true"></i> Location:</label>
<input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value="">
</div>
<button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button>
</form>
</div>
</section>
<!-- последние зарегистрированные пользователи -->
<section class="musicians">
<div class="container">
<h2>Recent Uploads</h2>
<div class="row">
<% tracks.forEach(function(track) { %>
<div class="col-lg-4 col-md-6 col-sm-12">
<div class="track-card">
<div class="track-info">
<h3><%= track.title %></h3>
<p><strong>Album:</strong> <%= track.album_title || "No Album" %></p>
</div>
<div class="track-link">
<audio src="/tracks/<%= track.filename %>"></audio>
<button>Play</button>
</div>
</div>
</div>
<% }); %>
</div>
</div>
</section>
<!-- end -->
</main>
<footer class="footer">
<div class="container">
<p class="text-center mb-0">My Musician Site © 2023</p>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></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>
<script>
const genres = ["Rock", "Pop", "Jazz", "Blues", "Country"];
const genreSelect = document.querySelector("#genre");
genres.forEach((genre) => {
const option = document.createElement("option");
option.value = genre;
option.text = genre;
genreSelect.appendChild(option);
});
</script>
</body>
</html>
profile.ejs:
<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>
<!-- audio player -->
<p><strong>Tracks:</strong>
<div class="audio-player">
<div class="row">
<% tracks.forEach((track, index) => { %>
<div class="col-md-4 mb-3">
<div class="track">
<img src="/img/<%= track.image_filename || 'default-track-image.png' %>" alt="<%= track.title %>" width="200" height="200">
<div class="info">
<h4><%= track.title %></h4>
<p><%= track.album_title || "No Album" %></p>
<div class="progress-bar">
<div class="progress-bar-fill" style="width: 0;"></div>
</div>
<audio id="audio-<%= index %>" src="/tracks/<%= track.filename %>"></audio>
<button class="play-button" data-audio-id="audio-<%= index %>">
<i class="fa fa-play"></i>
</button>
</div>
</div>
</div>
<% }); %>
</div>
</div>
<!-- end -->
<% 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">×</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>
<h2>Upload a new track:</h2>
<form id="upload-form" action="/profile/<%= musician.id %>/upload" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="track">Track file:</label>
<input type="file" id="track" name="track" accept="audio/*" class="form-control-file" required>
<h4>only .mp3 allowed</h4>
</div>
<div class="form-group">
<label for="title">Track title:</label>
<input type="text" id="title" name="title" class="form-control" required>
</div>
<div class="form-group">
<label for="albumTitle">Album title:</label>
<input type="text" id="albumTitle" name="albumTitle" class="form-control">
</div>
<div class="form-group">
<label for="image">Track image:</label>
<input type="file" id="image" name="image" accept="image/*" class="form-control-file">
</div>
<button type="submit" class="btn btn-primary">Upload Track</button>
</form>
</div>
</div>
</div>
</div>
<% } %>
</div>
</div>
</div>
<script>
$(function() {
$('.play-button').on('click', function() {
var audioId = $(this).data('audio-id');
var audio = document.getElementById(audioId);
var isPaused = audio.paused;
$('.play-button').removeClass('active');
if (isPaused) {
audio.play();
$(this).addClass('active');
} else {
audio.pause();
}
});
$('audio').on('timeupdate', function() {
var audio = $(this)[0];
var progress = audio.currentTime / audio.duration * 100;
$(this).siblings('.progress-bar').find('.progress-bar-fill').css('width', progress + '%');
});
});
</script>
|
e9d92a3b416f5802cd60c148d91a2eb4
|
{
"intermediate": 0.4225047528743744,
"beginner": 0.3917118012905121,
"expert": 0.1857834756374359
}
|
12,123
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Can you modify the following header file to properly utilise Vulkan.hpp and RAII? We will then begin updating the class source file to conform to the new header and then expand to the broader codebase.
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
|
805ceb41e8d0d3d38e30c5511fb51689
|
{
"intermediate": 0.25512373447418213,
"beginner": 0.3797565698623657,
"expert": 0.36511966586112976
}
|
12,124
|
Hy are you aware of the Teleport Role Templates
|
6517021b8bd12fdef56229efc2ddeae5
|
{
"intermediate": 0.35998010635375977,
"beginner": 0.28027546405792236,
"expert": 0.3597443997859955
}
|
12,125
|
this is my sql code: SELECT
c.contactFirstName,
c.contactLastName,
c.country,
o.orderNumber,
o.orderDate,
o.status,
od.total
FROM
customers c
INNER JOIN orders o ON c.customerNumber = o.customerNumber
INNER JOIN (
SELECT
orderNumber,
SUM(quantityOrdered * priceEach) AS total
FROM
orderdetails
GROUP BY
orderNumber and it givethis error: Ошибка в запросe (1064): Syntax error near '' at line 19 , correct the code
|
49325e55cefd93ffc8420e05cea210b7
|
{
"intermediate": 0.3014758229255676,
"beginner": 0.4189460873603821,
"expert": 0.2795780599117279
}
|
12,126
|
Introduction. Linear programming provides a powerful framework for modeling and solving
numerous problems in industrial applications like resource management, transportation,
scheduling, structural design, telecommunications, etc. In many other important applications,
however, non-linearity can be crucial for modeling the underlying problem accurately.
In this laboratory, we will take our first steps into non-linear programming and study a
problem in portfolio optimization, where the objective function is quadratic.
The main purpose of this lab is to delve deeper into one area of the theory of linear
programming. Part of the work is therefore to read and understand a fairly complex
description of new material.
We start by formulating the portfolio optimization problem. Then we derive an algorithm
for solving this formulation and we prove convergence guarantees of the proposed algorithm.
Finally, we implement and use this algorithm for solving the problem in a computer
experiment.
Problem and model: Portfolio Optimization. Sonya wants to build an investment
portfolio and she needs to decide how to allocate her savings into different assets. She has
a low tolerance for risk and her goal is to design a portfolio which minimizes the risk while
maintaining an expected return roughly around the inflation rate.
Her advisor in the bank provides historical data on monthly returns of N assets for the
last T months. We denote the return of asset n = 1, . . . ,N in month t = 1, . . . , T by an,t.
Empirically, the expected return of asset n is its average return, μn = 1
T PT
t=1 an,t.
We can write a mathematical program to model Sonya’s goals and constraints. Without
loss of generality, we denote the total amount of investment by 1 and the amount invested
in asset n by xn. We assume that xn must be non-negative (since we do not allow investing
negative amounts, or shorting) and sum up to 1.
She wants her savings to protect their value by maintaining a minimum expected value
around the inflation rate. Her empirical expected return is PN
n=1 μnxn. Let 2 R be the
inflation rate. Then we have the following minimum expected return constraint:
N
Xn
=1
μnxn .
In statistics, we often model the risk as the variance. The variance associated to asset
n (denoted by 2n
) is its expected squared deviation from its expected return, i.e., 2n
=
1
T PT
t=1 |an,t − μn|2. The goal is minimizing the total risk f(x1, . . . , xN), given by
f(x1, . . . , xN) =
N
X
n=1
1
T
T
X t=1
|an,txn − μnxn|2
=
N
X
n=1
x2
n
1
T
T
X t=1
|an,t − μn|2
=
N
X
n=1
x2
n2n
.
Hence, we can find a proper strategy for Sonya by solving the following program:
(P)
minimize
N
X
n=1
2n
x2
n
subject to
N
X
n=1
μnxn
N
X
n=1
xn = 1
xn 0 n = 1, . . . ,N
This problem has linear constraints but also a non-linear (convex quadratic) objective
function. The algorithms that we learned in the course are not directly applicable because
of this non-linearity. Nevertheless, we can find a solution to this problem by solving a
sequence of linear programs. This classical approach in non-linear programming is called
the conditional gradient method (CGM).
Theory, solution method: Conditional Gradient Method. CGM (also known as the
Frank-Wolfe Algorithm1) is a classical method in non-linear programming dating back to
1956. Despite its old age, CGM is still very popular today and widely used in the fields of
computer vision and artificial intelligence. In this laboratory, we consider a basic version
of CGM for solving the portfolio optimization problem.
The main strategy of CGM is as follows:
Initialize the algorithm from a feasible point x(1) = (x(1)
1 , . . . , x(1)
N ). Then, for iteration
k = 1, 2, . . .,
(1) Form a linear surrogate ˆ fk for the objective function f by using its first-order Taylor
expansion at the current estimate x(k):
ˆ fk(x) = f(x(k)) +
N
X
n=1
@f
@xn
(x(k)) · (x − x(k))
Recall that Taylor’s expansion gives the best linear approximation of function f
around x(k). Note that · is the dot-product.
NOTE! Since Calculus is not formally a prerequisite for this course, it is very
much allowed to ask questions about this particular part of the theory.
For (P), we can specify ˆ fk as
ˆ fk(x) =
N
X
n=1
2n x(k)
n 2 + 2
N
X
n=1
2n
x(k)
n (xn − x(k)
n )
= 2
N
X
n=1
2n
x(k)
n xn −
N
X
n=1
2n
x(k)
n 2.
(2) Form an auxiliary problem with the same constraints as the original problem, but
with the linear surrogate objective ˆ fk instead of the original non-linear objective
function. This auxiliary problem is a linear program, so we can use the simplex
method for solving it. Denote the solution by y(k).
1Frank, M. & Wolfe, P. (1956). “An algorithm for quadratic programming”. Naval Research Logistics
Quarterly. 3 (1–2): pp. 95–110.
For (P), we can specify the auxiliary problem (ˆPk) as2
(ˆPk)
minimize 2
N
X
n=1
2n
x(k)
n xn
subject to
N
X
n=1
μnxn
N
X
n=1
xn = 1
xn 0 n = 1, . . . ,N
(3) Update the estimate x(k+1) by moving from x(k) towards y(k):
x(k+1) = (1 − k)x(k) + ky(k) with some step-size k 2 [0, 1].
Go back to step 1 and repeat the procedure.
With a suitable choice of step-size k, the sequence x(k) generated by CGM converges to a
solution of the original problem3. Common choices are the agnostic step-size k = 2/(k+1)
and the greedy step-size
k = argmin
η∈[0,1]
f(1 − )x(k) + y(k).
2We discarded the second term of ˆ fk in (ˆ Pk) because that term is constant with respect to x and does
not affect the solution.
3The proof is simple and provided in the appendix of this document. You do not need to read the proof
to complete this laboratory, but you are encouraged to read it, especially if you are interested in analysis.
Computer Experiment
The main task of this laboratory is to implement and use CGM for solving Sonya’s portfolio
optimization problem. Download historical data on the return of S&P 500 stock companies
from the website below:
http://www.cs.technion.ac.il/rani/portfolios/portfolios.htm
Suggested steps in the process:
(1) Process the data format from the source above so that it can be used as input data
for your software / programming language.
(2) Implement an LP routine for solving the auxiliary problems in Step 2 of CGM. You
are allowed to use, for instance, MatLab’s built-in LP solver as a component of your
implementation.
(3) Implement CGM. Your implementation should call the LP routine for Step 2 of the
algorithm.
(4) Suppose the inflation rate is = μav = 1
N PN
n=1 μn. Run CGM for 1000 iterations
and note the results. Do the results seem to be numerically stable after this many
iterations? How many iterations do you need? What happens if you change the
step size and re-run your implementation of CGM? Investigate this in a systematic
way.
(5) Try again with a more ambitious goal of expected return, = 1
2 (μav +μmax), where
μmax = maxn μn. Compare your result (i.e., the total variance / risk) with your
previous result. Does it increase or decrease? Is it reasonable? Investigate this in a
systematic way, and comment on the results. do this in python with pulp
|
8cbcbd325e6bc9ecc6385372993dc2ba
|
{
"intermediate": 0.3907832205295563,
"beginner": 0.24469122290611267,
"expert": 0.36452558636665344
}
|
12,127
|
я хочу использовать вместо недавно зарегистрированных пользователей в index.ejs недавно загруженные .mp3 файлы из profile.ejs пользователей. index.ejs я уже поменял. осталось добавить в app.get(“/”, (req, res) => {
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"));
connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => {
if(err) throw err;
});
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
function getLastNUploadedTracks(N, callback) {
connection.query("SELECT * FROM tracks ORDER BY uploaded_at DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних загруженных треков: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
//функция для получения песен музыканта по id
function getMusicianTracks(musicianId, callback) {
connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => {
if (err) {
console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result);
}
});
}
function getMusicians(callback) {
connection.query("SELECT * FROM users", (err, result) => {
if (err) {
console.error("Ошибка при получении списка музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
// Функция для получения музыканта по id
function getMusicianById(id, callback) {
connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
if (err) {
console.error("Ошибка при получении музыканта с id ${id}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result[0]);
}
});
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];
// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}
// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.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
};
});
// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;
if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}
// Сортировка по score (убывающая)
return scoreB - scoreA;
});
// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}
app.use((req, res, next) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении current user: ", err);
res.locals.userLoggedIn = false;
} else {
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
}
next();
});
} else {
res.locals.userLoggedIn = false;
next();
}
});
app.get("/", (req, res) => {
getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
res.status(500).send("Ошибка получения данных");
} else {
res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'',tracks: getLastNUploadedTracks});
}
});
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT DISTINCT city FROM users 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/" + musicianId);
} else {
res.render("register", { citiesAndRegions, city:'', query:'',role:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {
// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
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_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});
app.get("/profile/:id", (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
getMusicianTracks(musician.id, (err, tracks) => {
if(err) {
console.error("Ошибка при получении треков для профиля: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
res.render("profile", { musician: musician, tracks: tracks, query:'', role:'', city:''});
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
if (err) {
console.error("Ошибка при входе: ", err);
res.status(500).send("Ошибка при входе");
} else {
if (result.length > 0) {
req.session.musicianId = result[0].id;
res.redirect("/profile/" + result[0].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) => {
let query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
const genre = req.query.genre || '';
if (query || role || city || genre) {
search(query, role, city, genre, (err, musicians) => {
if (err) {
res.status(500).send("Ошибка при выполнении поиска");
} else {
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
} else {
// Use the getMusicians function instead of reading from musicians.json
getMusicians((err, musiciansList) => {
if (err) {
res.status(500).send("Ошибка при получении списка музыкантов");
} else {
const musicians = musiciansList.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
};
});
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
}
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
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 musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
//загрузка музыки и изображений к музыке
app.post("/profile/:id/upload", requireLogin, async (req, res) => {
const musicianId = req.session.musicianId;
if (!req.files) {
res.status(400).send("No files were uploaded.");
return;
}
const trackFile = req.files.track;
if (!trackFile) {
res.status(400).send("No track file was uploaded.");
return;
}
if (trackFile && !trackFile.name.endsWith(".mp3")) {
res.status(400).send("Only .mp3 files can be uploaded.");
return;
}
// Set a maximum file size of 10MB for uploaded files
const maxSizeInBytes = 10000000; // 10MB
if (trackFile && trackFile.size > maxSizeInBytes) {
res.status(400).send("File size exceeds 10MB limit.");
return;
}
const trackFilename = "track_" + musicianId + "" + trackFile.name;
const tmpPath = './public/tracks/tmp_' + trackFilename;
trackFile.mv("./public/tracks/" + trackFilename);
const title = req.body.title;
const album_title = req.body.albumTitle;
const track = {
musician_id: musicianId,
title,
album_title,
filename: trackFilename,
};
if (req.files.image) {
const imageFile = req.files.image;
const imageFilename = "image" + musicianId + "_" + imageFile.name;
imageFile.mv("./public/img/" + imageFilename);
track.image_filename = imageFilename;
}
connection.query("INSERT INTO tracks SET ?", track, (err, result) => {
if (err) {
console.error("Ошибка при добавлении трека: ", err);
res.status(500).send("Ошибка при добавлении трека");
} else {
res.redirect("/profile/" + musicianId);
}
});
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
index.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="/css/main.css" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="/jquery-ui/themes/base/all.css" rel="stylesheet">
<title>Home</title>
</head>
<body>
<header class="header">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="/">
<img src="/img/logo.png" alt="My Musician Site">
</a>
<button aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarNav" data-toggle="collapse" type="button">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#find-musicians">Find Musicians</a>
</li>
<% if (!userLoggedIn) { %>
<li class="nav-item">
<a class="nav-link" href="/register"><i class="fa fa-user-plus" aria-hidden="true"></i> Register</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/login"><i class="fa fa-sign-in" aria-hidden="true"></i> Login</a>
</li>
<% } else { %>
<li class="nav-item">
<a class="nav-link"><i class="fa fa-user" aria-hidden="true"></i> Hello, <%= username %></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/logout"><i class="fa fa-sign-out" aria-hidden="true"></i> Logout</a>
</li>
<% } %>
</ul>
</div>
</div>
</nav>
<div class="hero">
<div class="container">
<h1 class="hero-title">Find the Perfect Musician for Your Band or Project</h1>
<p class="hero-subtitle">Join our community today and connect with talented musicians from around the world.</p>
<a class="btn btn-primary btn-lg" href="/register">Register Now</a>
</div>
</div>
</header>
<main class="main">
<section class="section section-search" id="find-musicians">
<div class="container">
<h2 class="section-title"><i class="fa fa-search" aria-hidden="true"></i> Find Musicians</h2>
<form class="form-search" action="/search" method="get">
<div class="form-group">
<label for="role"><i class="fa fa-users" aria-hidden="true"></i> Role:</label>
<select class="form-control" id="role" name="role">
<option value="">All</option>
<option value="Band">Band</option>
<option value="Artist">Artist</option>
</select>
</div>
<div class="form-group">
<label for="genre">Search by genre:</label>
<select class="form-control" id="genre" name="genre">
<option value="">All</option>
</select>
</div>
<div class="form-group">
<label for="city"><i class="fa fa-map-marker" aria-hidden="true"></i> Location:</label>
<input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value="">
</div>
<button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button>
</form>
</div>
</section>
<!-- последние зарегистрированные пользователи -->
<section class="musicians">
<div class="container">
<h2>Recent Uploads</h2>
<div class="row">
<% tracks.forEach(function(track) { %>
<div class="col-lg-4 col-md-6 col-sm-12">
<div class="track-card">
<div class="track-info">
<h3><%= track.title %></h3>
<p><strong>Album:</strong> <%= track.album_title || "No Album" %></p>
</div>
<div class="track-link">
<audio src="/tracks/<%= track.filename %>"></audio>
<button>Play</button>
</div>
</div>
</div>
<% }); %>
</div>
</div>
</section>
<!-- end -->
</main>
<footer class="footer">
<div class="container">
<p class="text-center mb-0">My Musician Site © 2023</p>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></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>
<script>
const genres = ["Rock", "Pop", "Jazz", "Blues", "Country"];
const genreSelect = document.querySelector("#genre");
genres.forEach((genre) => {
const option = document.createElement("option");
option.value = genre;
option.text = genre;
genreSelect.appendChild(option);
});
</script>
</body>
</html>
profile.ejs:
<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>
<!-- audio player -->
<p><strong>Tracks:</strong>
<div class="audio-player">
<div class="row">
<% tracks.forEach((track, index) => { %>
<div class="col-md-4 mb-3">
<div class="track">
<img src="/img/<%= track.image_filename || 'default-track-image.png' %>" alt="<%= track.title %>" width="200" height="200">
<div class="info">
<h4><%= track.title %></h4>
<p><%= track.album_title || "No Album" %></p>
<div class="progress-bar">
<div class="progress-bar-fill" style="width: 0;"></div>
</div>
<audio id="audio-<%= index %>" src="/tracks/<%= track.filename %>"></audio>
<button class="play-button" data-audio-id="audio-<%= index %>">
<i class="fa fa-play"></i>
</button>
</div>
</div>
</div>
<% }); %>
</div>
</div>
<!-- end -->
<% 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">×</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>
<h2>Upload a new track:</h2>
<form id="upload-form" action="/profile/<%= musician.id %>/upload" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="track">Track file:</label>
<input type="file" id="track" name="track" accept="audio/*" class="form-control-file" required>
<h4>only .mp3 allowed</h4>
</div>
<div class="form-group">
<label for="title">Track title:</label>
<input type="text" id="title" name="title" class="form-control" required>
</div>
<div class="form-group">
<label for="albumTitle">Album title:</label>
<input type="text" id="albumTitle" name="albumTitle" class="form-control">
</div>
<div class="form-group">
<label for="image">Track image:</label>
<input type="file" id="image" name="image" accept="image/*" class="form-control-file">
</div>
<button type="submit" class="btn btn-primary">Upload Track</button>
</form>
</div>
</div>
</div>
</div>
<% } %>
</div>
</div>
</div>
<script>
$(function() {
$('.play-button').on('click', function() {
var audioId = $(this).data('audio-id');
var audio = document.getElementById(audioId);
var isPaused = audio.paused;
$('.play-button').removeClass('active');
if (isPaused) {
audio.play();
$(this).addClass('active');
} else {
audio.pause();
}
});
$('audio').on('timeupdate', function() {
var audio = $(this)[0];
var progress = audio.currentTime / audio.duration * 100;
$(this).siblings('.progress-bar').find('.progress-bar-fill').css('width', progress + '%');
});
});
</script>
|
48e64738a283c8641286698e45af9923
|
{
"intermediate": 0.30425378680229187,
"beginner": 0.5495890974998474,
"expert": 0.14615708589553833
}
|
12,128
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Can you modify the following header file to properly utilise Vulkan.hpp and RAII? We will then begin updating the class source file to conform to the new header and then expand to the broader codebase.
I am in the process of modifying the Renderer class to properly utilise Vulkan.hpp and RAII. Here are the old and new header files:
Old Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
New Renderer.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include “Window.h”
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include “Pipeline.h”
#include “Material.h”
#include “Mesh.h”
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
vk::SurfaceCapabilitiesKHR capabilities;
std::vector<vk::SurfaceFormatKHR> formats;
std::vector<vk::PresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
vk::DescriptorSetLayout CreateDescriptorSetLayout();
vk::DescriptorPool CreateDescriptorPool(uint32_t maxSets);
vk::Device* GetDevice();
vk::PhysicalDevice* GetPhysicalDevice();
vk::CommandPool* GetCommandPool();
vk::Queue* GetGraphicsQueue();
vk::CommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<vk::Buffer, vk::DeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<vk::Buffer> mvpBuffers;
std::vector<vk::DeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<vk::Image> swapChainImages;
std::vector<vk::ImageView> swapChainImageViews;
vk::Extent2D swapChainExtent;
vk::RenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
vk::Format swapChainImageFormat;
std::vector<vk::CommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
vk::Instance instance;
vk::PhysicalDevice physicalDevice;
vk::Device device;
vk::SurfaceKHR surface;
vk::SwapchainKHR swapchain;
vk::CommandPool commandPool;
vk::CommandBuffer currentCommandBuffer;
std::vector<vk::Framebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<vk::Semaphore> imageAvailableSemaphores;
std::vector<vk::Semaphore> renderFinishedSemaphores;
std::vector<vk::Fence> inFlightFences;
size_t currentFrame;
vk::Queue graphicsQueue;
vk::Queue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(vk::PhysicalDevice device, vk::SurfaceKHR surface);
vk::SurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats);
vk::PresentModeKHR chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes);
vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(vk::PhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(vk::PhysicalDevice physicalDevice);
};
Please update the following portion of the Renderer.cpp to conform to the new header and to properly utilise both Vulkan.hpp and RAII. Notify me if there are no changes required.
void Renderer::CreateSurface()
{
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a window surface.");
}
}
void Renderer::DestroySurface()
{
vkDestroySurfaceKHR(instance, surface, nullptr);
}
void Renderer::CreateInstance()
{
// Set up the application info
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Game Engine";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "Game Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_2;
// Set up the instance create info
VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
// Set up the required extensions
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
createInfo.enabledExtensionCount = glfwExtensionCount;
createInfo.ppEnabledExtensionNames = glfwExtensions;
createInfo.enabledLayerCount = 0;
std::vector<const char*> validationLayers;
#ifdef NDEBUG
const bool enableValidationLayers = false;
#else
const bool enableValidationLayers = true;
validationLayers.push_back("VK_LAYER_KHRONOS_validation");
#endif
if (enableValidationLayers) {
// Check if validation layers are supported
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const char* layerName : validationLayers) {
bool layerFound = false;
for (const auto& layerProperties : availableLayers) {
if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
throw std::runtime_error("Validation layer requested, but it’s not available.");
}
}
// Enable the validation layers
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
}
else {
createInfo.enabledLayerCount = 0;
}
// Create the Vulkan instance
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create the Vulkan instance.");
}
}
void Renderer::CleanupInstance()
{
// Destroy the Vulkan instance
vkDestroyInstance(instance, nullptr);
}
void Renderer::ChoosePhysicalDevice()
{
// Enumerate the available physical devices and choose one that supports required features
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0)
{
throw std::runtime_error("Failed to find a GPU with Vulkan support.");
}
std::vector<VkPhysicalDevice> allDevices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data());
for (const auto& testDevice : allDevices)
{
if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) &&
CheckPhysicalDeviceExtensionSupport(testDevice).empty() &&
GetQueueFamilyIndices(testDevice).IsComplete())
{
VkPhysicalDeviceFeatures supportedFeatures;
vkGetPhysicalDeviceFeatures(testDevice, &supportedFeatures);
// Check for anisotropic filtering support
if (supportedFeatures.samplerAnisotropy) {
physicalDevice = testDevice;
break;
}
}
}
if (physicalDevice == VK_NULL_HANDLE)
{
throw std::runtime_error("Failed to find a suitable GPU.");
}
}
void Renderer::CreateDevice()
{
// Get the GPU’s queue family indices
const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice);
// Set up the device queue create info
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() };
float queuePriority = 1.0f;
for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices)
{
VkDeviceQueueCreateInfo queueCreateInfo{};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
// Set up the physical device features
VkPhysicalDeviceFeatures deviceFeatures{};
deviceFeatures.samplerAnisotropy = VK_TRUE; // Enable anisotropic filtering
// Set up the device create info
VkDeviceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
// Create the logical device
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a logical device.");
}
// Retrieve the graphics queue and the present queue
vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
|
abccd70fb13f7e5dd81aa8f0ab95ef45
|
{
"intermediate": 0.35266053676605225,
"beginner": 0.4519357681274414,
"expert": 0.19540365040302277
}
|
12,129
|
The pcolormesh takes as input first and array A, then a second array B, and third a matrix M. how can I plot a pcolormesh using as input a dataframe pandas where i use A from the first column is a datetime, and a number of columns M1,M2,M3 from the dataframe as the matrix M
|
23d68c29e550ea114d1642f5c4c87a66
|
{
"intermediate": 0.6086465716362,
"beginner": 0.16334939002990723,
"expert": 0.22800405323505402
}
|
12,130
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Can you modify the following header file to properly utilise Vulkan.hpp and RAII? We will then begin updating the class source file to conform to the new header and then expand to the broader codebase.
I am in the process of modifying the Renderer class to properly utilise Vulkan.hpp and RAII. Here are the old and new header files:
Old Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
New Renderer.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include “Window.h”
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include “Pipeline.h”
#include “Material.h”
#include “Mesh.h”
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
vk::SurfaceCapabilitiesKHR capabilities;
std::vector<vk::SurfaceFormatKHR> formats;
std::vector<vk::PresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
vk::DescriptorSetLayout CreateDescriptorSetLayout();
vk::DescriptorPool CreateDescriptorPool(uint32_t maxSets);
vk::Device* GetDevice();
vk::PhysicalDevice* GetPhysicalDevice();
vk::CommandPool* GetCommandPool();
vk::Queue* GetGraphicsQueue();
vk::CommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<vk::Buffer, vk::DeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<vk::Buffer> mvpBuffers;
std::vector<vk::DeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<vk::Image> swapChainImages;
std::vector<vk::ImageView> swapChainImageViews;
vk::Extent2D swapChainExtent;
vk::RenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
vk::Format swapChainImageFormat;
std::vector<vk::CommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
vk::Instance instance;
vk::PhysicalDevice physicalDevice;
vk::Device device;
vk::SurfaceKHR surface;
vk::SwapchainKHR swapchain;
vk::CommandPool commandPool;
vk::CommandBuffer currentCommandBuffer;
std::vector<vk::Framebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<vk::Semaphore> imageAvailableSemaphores;
std::vector<vk::Semaphore> renderFinishedSemaphores;
std::vector<vk::Fence> inFlightFences;
size_t currentFrame;
vk::Queue graphicsQueue;
vk::Queue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(vk::PhysicalDevice device, vk::SurfaceKHR surface);
vk::SurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats);
vk::PresentModeKHR chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes);
vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(vk::PhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(vk::PhysicalDevice physicalDevice);
};
Please update and provide the code for the following portion of the Renderer.cpp to conform to the new header and to properly utilise both Vulkan.hpp and RAII. Notify me if there are no changes required.
void Renderer::CreateSurface()
{
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a window surface.");
}
}
void Renderer::DestroySurface()
{
vkDestroySurfaceKHR(instance, surface, nullptr);
}
void Renderer::CreateInstance()
{
// Set up the application info
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Game Engine";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "Game Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_2;
// Set up the instance create info
VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
// Set up the required extensions
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
createInfo.enabledExtensionCount = glfwExtensionCount;
createInfo.ppEnabledExtensionNames = glfwExtensions;
createInfo.enabledLayerCount = 0;
std::vector<const char*> validationLayers;
#ifdef NDEBUG
const bool enableValidationLayers = false;
#else
const bool enableValidationLayers = true;
validationLayers.push_back("VK_LAYER_KHRONOS_validation");
#endif
if (enableValidationLayers) {
// Check if validation layers are supported
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const char* layerName : validationLayers) {
bool layerFound = false;
for (const auto& layerProperties : availableLayers) {
if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
throw std::runtime_error("Validation layer requested, but it’s not available.");
}
}
// Enable the validation layers
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
}
else {
createInfo.enabledLayerCount = 0;
}
// Create the Vulkan instance
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create the Vulkan instance.");
}
}
void Renderer::CleanupInstance()
{
// Destroy the Vulkan instance
vkDestroyInstance(instance, nullptr);
}
void Renderer::ChoosePhysicalDevice()
{
// Enumerate the available physical devices and choose one that supports required features
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0)
{
throw std::runtime_error("Failed to find a GPU with Vulkan support.");
}
std::vector<VkPhysicalDevice> allDevices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data());
for (const auto& testDevice : allDevices)
{
if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) &&
CheckPhysicalDeviceExtensionSupport(testDevice).empty() &&
GetQueueFamilyIndices(testDevice).IsComplete())
{
VkPhysicalDeviceFeatures supportedFeatures;
vkGetPhysicalDeviceFeatures(testDevice, &supportedFeatures);
// Check for anisotropic filtering support
if (supportedFeatures.samplerAnisotropy) {
physicalDevice = testDevice;
break;
}
}
}
if (physicalDevice == VK_NULL_HANDLE)
{
throw std::runtime_error("Failed to find a suitable GPU.");
}
}
|
156f41f3f6f5e27c1840b72e7ffc1dc7
|
{
"intermediate": 0.35266053676605225,
"beginner": 0.4519357681274414,
"expert": 0.19540365040302277
}
|
12,131
|
Please write a code on python to create hexagon
|
2d404a6ef3f4293adb31b13cb3b63dde
|
{
"intermediate": 0.3309507966041565,
"beginner": 0.21941961348056793,
"expert": 0.44962960481643677
}
|
12,132
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Can you modify the following header file to properly utilise Vulkan.hpp and RAII? We will then begin updating the class source file to conform to the new header and then expand to the broader codebase.
I am in the process of modifying the Renderer class to properly utilise Vulkan.hpp and RAII. Here are the old and new header files:
Old Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
New Renderer.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include “Window.h”
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include “Pipeline.h”
#include “Material.h”
#include “Mesh.h”
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
vk::SurfaceCapabilitiesKHR capabilities;
std::vector<vk::SurfaceFormatKHR> formats;
std::vector<vk::PresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
vk::DescriptorSetLayout CreateDescriptorSetLayout();
vk::DescriptorPool CreateDescriptorPool(uint32_t maxSets);
vk::Device* GetDevice();
vk::PhysicalDevice* GetPhysicalDevice();
vk::CommandPool* GetCommandPool();
vk::Queue* GetGraphicsQueue();
vk::CommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<vk::Buffer, vk::DeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<vk::Buffer> mvpBuffers;
std::vector<vk::DeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<vk::Image> swapChainImages;
std::vector<vk::ImageView> swapChainImageViews;
vk::Extent2D swapChainExtent;
vk::RenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
vk::Format swapChainImageFormat;
std::vector<vk::CommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
vk::Instance instance;
vk::PhysicalDevice physicalDevice;
vk::Device device;
vk::SurfaceKHR surface;
vk::SwapchainKHR swapchain;
vk::CommandPool commandPool;
vk::CommandBuffer currentCommandBuffer;
std::vector<vk::Framebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<vk::Semaphore> imageAvailableSemaphores;
std::vector<vk::Semaphore> renderFinishedSemaphores;
std::vector<vk::Fence> inFlightFences;
size_t currentFrame;
vk::Queue graphicsQueue;
vk::Queue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(vk::PhysicalDevice device, vk::SurfaceKHR surface);
vk::SurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats);
vk::PresentModeKHR chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes);
vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(vk::PhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(vk::PhysicalDevice physicalDevice);
};
Please update and provide the code for the following portion of the Renderer.cpp to conform to the new header and to properly utilise both Vulkan.hpp and RAII. Notify me if there are no changes required.
void Renderer::CreateDevice()
{
// Get the GPU’s queue family indices
const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice);
// Set up the device queue create info
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() };
float queuePriority = 1.0f;
for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices)
{
VkDeviceQueueCreateInfo queueCreateInfo{};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
// Set up the physical device features
VkPhysicalDeviceFeatures deviceFeatures{};
deviceFeatures.samplerAnisotropy = VK_TRUE; // Enable anisotropic filtering
// Set up the device create info
VkDeviceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
// Create the logical device
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create a logical device.");
}
// Retrieve the graphics queue and the present queue
vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
void Renderer::CreateSwapchain()
{
// Get swapchain support details
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice,surface);
VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
swapChainImageFormat = surfaceFormat.format; // Initialize the swapChainImageFormat
VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities,window);
// Update the swapChainExtent with the chosen extent
swapChainExtent = extent;
uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount)
{
imageCount = swapChainSupport.capabilities.maxImageCount;
}
// Create the swapchain
// …
VkSwapchainCreateInfoKHR createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
createInfo.surface = surface;
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = extent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice);
uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
if (indices.graphicsFamily != indices.presentFamily) {
createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
createInfo.queueFamilyIndexCount = 2;
createInfo.pQueueFamilyIndices = queueFamilyIndices;
}
else {
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
}
createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE;
if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) {
throw std::runtime_error("failed to create swap chain!");
}
// Retrieve swapchain images (color buffers)
// …
// Retrieve swapchain images
vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr);
swapChainImages.resize(imageCount);
vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data());
// Create image views for swapchain images
CreateImageViews();
}
void Renderer::CleanupSwapchain()
{
// Clean up Vulkan swapchain
if (swapchain != VK_NULL_HANDLE)
{
vkDestroySwapchainKHR(device, swapchain, nullptr);
swapchain = VK_NULL_HANDLE;
}
}
void Renderer::CreateImageViews()
{
swapChainImageViews.resize(swapChainImages.size());
for (size_t i = 0; i < swapChainImages.size(); ++i)
{
VkImageViewCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
createInfo.image = swapChainImages[i];
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
createInfo.format = swapChainImageFormat;
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
createInfo.flags = 0;
if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create an image view.");
}
}
}
void Renderer::CleanupImageViews()
{
for (auto imageView : swapChainImageViews)
{
vkDestroyImageView(device, imageView, nullptr);
}
swapChainImageViews.clear();
}
|
b60ed301491227be8096fe0f4b85ea54
|
{
"intermediate": 0.35266053676605225,
"beginner": 0.4519357681274414,
"expert": 0.19540365040302277
}
|
12,133
|
Напишите программу для вычисления длины окружности на python.
|
c2628919940dbc20a622a9f71093a2d9
|
{
"intermediate": 0.27884820103645325,
"beginner": 0.24908442795276642,
"expert": 0.47206738591194153
}
|
12,134
|
An array with an odd number of elements is said to be centered if all elements (except the middle one) are strictly greater than the value of the middle element. Note that only arrays with an odd number of elements have a middle element. Write a function that accepts an integer array and returns 1 if it is a centered array, otherwise it returns 0.
|
b09b1b14905128c356117e7986642f4b
|
{
"intermediate": 0.33796218037605286,
"beginner": 0.321441650390625,
"expert": 0.34059616923332214
}
|
12,135
|
<?php
date_default_timezone_set('Asia/Tehran');
include("jdf.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>نمایش نتایج</title>
<link rel="stylesheet" href="style/style-00.css">
</head>
<body>
<form method="POST" action="">
<label for="start">تاریخ شروع:</label>
<jb-date-input format="YYYY-MM-DD" id="start" name="start" style="padding: 10px;width: 150px;display:inline-block;"></jb-date-input>
<label for="end">تاریخ پایان:</label>
<jb-date-input format="YYYY-MM-DD" id="end" name="end" style="padding: 10px;width: 150px;display:inline-block;"></jb-date-input>
<button type="submit" name="submit">نمایش نتایج</button>
</form>
<?php
// اتصال به دیتابیس
include 'connection.php';
// بررسی اتصال
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// چک کردن ارسال فرم
if (isset($_POST['submit'])) {
// واکشی دادهها از فرم
$dateStart = $_POST['start'] . ' 00:00:00';
$dateEnd = $_POST['end'] . ' 23:59:59';
//$dateStart = date('Y-m-d H:i:s', strtotime($_POST['start']));
//$dateEnd = date('Y-m-d H:i:s', strtotime($_POST['end']));
// کوئری برای شمارش تعداد رکوردها در بازه تاریخی انتخاب شده
$countSql = "SELECT COUNT(*) as count FROM responses WHERE date_time BETWEEN '$dateStart' AND '$dateEnd'";
//$countSql = "SELECT COUNT(*) as count FROM responses WHERE food_quality IN ('Poor', 'Fair', 'Good', 'Excellent') AND date_time BETWEEN '$dateStart' AND '$dateEnd'";
$countResult = mysqli_query($conn, $countSql);
$countRow = mysqli_fetch_assoc($countResult);
$count = $countRow['count'];
// نمایش بازه تاریخی انتخاب شده
echo '<h1>نمایش نتایج برای بازه تاریخی ' . jdate("d-m-Y", strtotime($dateStart)) . ' تا ' . jdate("d-m-Y", strtotime($dateEnd)) . '</h1>';
// نمایش تعداد رکوردها
echo '<p>تعداد کل رکوردهای استفاده شده: ' . $count . '</p>';
// محاسبه تعداد جوابها برای هر کیفیت
$foodCounts = countResponses($conn, $dateStart, $dateEnd, 'food_quality');
$serviceCounts = countResponses($conn, $dateStart, $dateEnd, 'service_quality');
// محاسبه درصدها
$foodPercentages = calculatePercentages($foodCounts);
$servicePercentages = calculatePercentages($serviceCounts);
// نمایش نتایج
echo '<h2>کیفیت غذا</h2>';
echo '<ul>';
echo '<li>ضعیف: ' . $foodPercentages['Poor'] . '%</li>';
echo '<li>متوسط: ' . $foodPercentages['Fair'] . '%</li>';
echo '<li>خوب: ' . $foodPercentages['Good'] . '%</li>';
echo '<li>عالی: ' . $foodPercentages['Excellent'] . '%</li>';
echo '</ul>';
echo '<h2>کیفیت سرویس</h2>';
echo'<ul>';
echo '<li>ضعیف: ' . $servicePercentages['Poor'] . '%</li>';
echo '<li>متوسط: ' . $servicePercentages['Fair'] . '%</li>';
echo '<li>خوب: ' . $servicePercentages['Good'] . '%</li>';
echo '<li>عالی: ' . $servicePercentages['Excellent'] . '%</li>';
echo '</ul>';
// بستن اتصال به دیتابیس
mysqli_close($conn);
}
// تابع محاسبه تعداد جوابها برای هر کیفیت
function countResponses($conn, $dateStart, $dateEnd, $quality) {
$sql = "SELECT COUNT(*) as count, $quality FROM responses WHERE date_time BETWEEN '$dateStart' AND '$dateEnd' GROUP BY $quality";
$result = mysqli_query($conn, $sql);
$counts = array();
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$counts[$row[$quality]] = $row['count'];
}
}
return $counts;
}
// تابع محاسبه درصدها
function calculatePercentages($counts) {
$total = array_sum($counts);
$percentages = array();
foreach ($counts as $key => $count) {
$percentages[$key] = round(($count / $total) * 100);
}
return $percentages;
}
?>
<script src="JBDateInput.umd.js"></script>
<style>
body{
--jb-date-input-border-radius:5px;
--jb-date-input-border-color: #ccc;
--jb-date-input-bgcolor: #fff;
}
</style>
</body>
</html>
در این کد میخوام اگر بازه تاریخ انتخاب نکردم و دکمه نمایش رو زدم نتایج بازه تاریخی از اول تا آخر هر آنچه در دیتابیس هست رو نشون بده ولی اگر بازه تاریخی رو انتخاب کردم نتایج همون بازه رو نمایش بده
|
4956f4c15bbbd9e89a83d889d16ff28f
|
{
"intermediate": 0.33233705163002014,
"beginner": 0.38232022523880005,
"expert": 0.2853426933288574
}
|
12,136
|
How to create smallest application for Android using Kotlin and GeckoView?
|
c2de7772b381f43f55b98c2e69e6306a
|
{
"intermediate": 0.6224830746650696,
"beginner": 0.19617626070976257,
"expert": 0.18134063482284546
}
|
12,137
|
You will choose one restaurant and research the prices of some menu items. More specifically, you will choose:
3-5 Beverages
5 Main Menu Items (keep it simple - avoid “build your own” kinds of items)
3-5 Sides/Snacks
You should use the names and prices listed from the menus on the site you chose.
Your program will display the purchasing options and prompt the user to select an item from each category, or checkout. For example your prompt could look like this:
Choose a main menu item
Choose a beverage
Choose a side/snack
Checkout
If the user selects option “1”, proceed to print out the main menu options and prices. Same for option 2, or option 3. Print out the food options and their prices.
The user should be continuously prompted to select mains, beverages, and sides until they select the option to “checkout”. At the checkout, you should determine how many combos can be made.
A combo consists of one main item, one beverage, and one side/snack. For each combo, a 5% discount should be applied to the total cost of the order. The user should be provided with a list of the items they purchased, the total applicable discount amount, number of combos in the order, and the total cost of all the items before and after tax.
As an example, assume the user selects the following items at A&W:
Root Beer (beverage)
Onion Rings (side/snack)
Teen Burger (Main menu)
Mama Burger (Main menu)
Then there is only 1 combo that can be created, so the total discount would be 5%.
In this example:
Root Beer (beverage)
Onion Rings (side/snack)
Teen Burger (Main menu)
Mama Burger (Main menu)
Sweet Potato Fries (side/snack)
Orange Juice (beverage)
Onion Rings (side/snack)
Then there are 2 combos and one extra side, so the total discount is 10%.
Your program should make use of 5 functions:
one main function
this function prints out the relevant information about the program and continuously prompts the user to purchase items, or checkout
three functions for the menu options
One function for main menu items, one function for snacks, and one function for beverages. These functions are responsible for prompting the user to select one type of item and will return the item that gets returned
one function that completes the checkout process
This function processes the items purchased, determines the number of combos and applicable discounts, calculates the total costs (before/after tax) and prints the itemized receipt.
|
beb3771a3baed5e14f8610ac2eae7e00
|
{
"intermediate": 0.3481789827346802,
"beginner": 0.36128005385398865,
"expert": 0.2905409634113312
}
|
12,138
|
What should the column definition look like in the model named "activities" and type "integer"? Python Databases
|
81f4a786a82a4cf9103ff39ddb8cb20b
|
{
"intermediate": 0.41367748379707336,
"beginner": 0.16653452813625336,
"expert": 0.4197880029678345
}
|
12,139
|
сейчас обложки песен/карточки вытянуты по вертикали, изображения не равномерны, а должны быть одного размера и аспект сторон должен быть сохранен, у плеера отсутствует дизайн, выглядит все вырвиглазно. Также для кнопки play сделай иконку fa-fa. Сделай красивый дизайн, вот код:
index:
<!-- audio player -->
<div class="selling-right-now">
<h3>Selling right now</h3>
<div class="selling-right-now-track">
<% tracks.forEach((track, index) => { %>
<div class="card">
<img src="/img/<%= track.image_filename || 'default-track-image.png' %>" alt="<%= track.title %>" width="200" height="200" style="object-fit: cover;">
<div class="card-body">
<h4><%= track.title %></h4>
<p><%= track.album_title || "No Album" %></p>
<audio id="audio-<%= index %>" src="/tracks/<%= track.filename %>" controls></audio>
</div>
</div>
<% }); %>
</div>
</div>
<!-- end -->
css:
/* audio player */
.selling-right-now {
margin: 50px 0;
}
.selling-right-now h3 {
font-size: 24px;
margin-bottom: 20px;
}
.selling-right-now-track {
display: flex;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.selling-right-now-track .card {
margin-right: 10px;
flex-shrink: 0;
max-width: 250px;
text-align: center;
position: relative;
}
.selling-right-now-track img {
width: 100%;
height: auto;
object-fit: cover;
}
.card-columns {
margin-right: -10px;
margin-left: -10px;
}
/* audio player styles */
audio {
width: 100%;
margin-top: 10px;
}
audio::-webkit-media-controls-panel {
background-color: #fff;
border-radius: 10px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
}
audio::-webkit-media-controls-play-button {
background-image: url('play-icon.png');
background-size: cover;
height: 30px;
width: 30px;
}
audio::-webkit-media-controls-volume-slider {
width: 80px;
}
@media (max-width: 768px) {
.selling-right-now-track {
flex-wrap: wrap;
justify-content: center;
}
.selling-right-now-track .card {
margin: 10px;
width: calc(50% - 20px);
}
}
|
30acc6ae68fa2ee1873128973f4f612a
|
{
"intermediate": 0.30501559376716614,
"beginner": 0.5261143445968628,
"expert": 0.16887007653713226
}
|
12,140
|
this is AddRoute.jsx
import { useState, useEffect } from 'react';
import { Container, Row, Col } from 'react-bootstrap';
import { BackButton } from './NavigationComponents';
import { BlockList, CreatePage, ActionList, Title } from './AddComponents';
import ErrorRoute from './ErrorRoute';
function AddRoute(props) {
const [list, setList] = useState([]); // Used as array of objects
const [title, setTitle] = useState("");
const [date, setDate] = useState(""); // Used to publish programmed pages
//const [dirtylist, dirtySetList] = useState(true);
return (
props.loggedIn ? ( // If not loggedin view ErrorRoute
<Container fluid>
<p></p>
<Row>
<Col xs={2}>
<BackButton />
</Col>
<Col>
<h2 style={{textAlign: "center"}}>Create Page</h2>
<p></p>
<Title title={title} setTitle={setTitle} />
<p></p>
<CreatePage list={list} setList={setList} />
</Col>
<Col xs={2}>
<Col style={{ position: "relative", paddingRight: "10%", top: "50px" }}>
<BlockList list={list} setList={setList} />
<ActionList date={date} setDate={setDate} setList={setList} title={title} list={list} handleError={props.handleError} />
</Col>
</Col>
</Row>
</Container>
)
: <ErrorRoute />
);
}
export default AddRoute;
this is AddComponents.jsx
import 'bootstrap-icons/font/bootstrap-icons.css';
import { useState, useEffect } from 'react';
import { Col, ListGroup, Button, Form, FormGroup, Accordion, Card, ButtonGroup } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import API from '../API';
import dayjs from 'dayjs';
function BlockList(props) {
function headerBlock() {
this.blockType = "Header";
this.content = "";
}
function paragraphBlock() {
this.blockType = "Paragraph";
this.content = "";
}
function imageBlock() {
this.blockType = "Image";
this.content = "";
}
const addToList = (x) => {
props.setList((oldList) => [...oldList, x]);
};
return (
<>
<h5 style={{ textAlign: "center" }}>Components</h5>
<p></p>
<Card>
<ListGroup>
<ListGroup.Item >Header<Button className="float-end" variant="outline-success"
style={{ fontSize: '21px', display: "flex", justifyContent: 'center', alignItems: 'center', width: '25px', height: '25px', borderRadius: '40px' }}
onClick={() => {
addToList(new headerBlock());
}}>
<i className="bi bi-plus"></i>
</Button>
</ListGroup.Item>
<ListGroup.Item >Paragraph<Button className="float-end" variant="outline-success"
style={{ fontSize: '21px', display: "flex", justifyContent: 'center', alignItems: 'center', width: '25px', height: '25px', borderRadius: '40px' }}
onClick={() => {
addToList(new paragraphBlock());
}}>
<i className="bi bi-plus"></i>
</Button>
</ListGroup.Item>
<ListGroup.Item >Image<Button className="float-end " variant="outline-success"
style={{ fontSize: '21px', display: "flex", justifyContent: 'center', alignItems: 'center', width: '25px', height: '25px', borderRadius: '40px' }}
onClick={() => {
addToList(new imageBlock());
}}>
<i className="bi bi-plus"></i>
</Button>
</ListGroup.Item>
</ListGroup>
</Card>
</>
);
}
function CreatePage(props) {
return (
<Accordion>
{props.list.map((x, index) => <MyBlock x={x} key={index} index={index} list={props.list} setList={props.setList} />)}
</Accordion>
);
}
function MyBlock(props) {
const x = props.x;
const [content, setContent] = useState(""); // When I delete a block (x) I need to re-render the content of the blocks (headers or paragraphs) showed at video.
const [isAligned, setIsAligned] = useState(true); // No matter true or false value, used just to trigger the re-render (setIsAligned(!isAligned))
//Otherwise the block content is ok (x.content) but a video I see all the blocks content shifted by one position.
//This is why useEffect is being used.
const images = [ //Server checks they're correct when submitting a request
{ url: 'http://localhost:3000/images/rome.jpg', alt: 'Image' },
{ url: 'http://localhost:3000/images/brasil.jpg', alt: 'Image' },
];
useEffect(() => {
setContent(x.content); //re-render block content at video
}, [isAligned]);
const removeFromList = (x) => {
props.setList((oldlist) => oldlist.filter((item) => item != x));
setIsAligned(!isAligned); // trigger re-render of content blocks
};
const handleUp = (x) => {
props.setList(oldList => {
const index = props.list.indexOf(x);
const newList = [...oldList];
[newList[index - 1], newList[index]] = [newList[index], newList[index - 1]];
setIsAligned(!isAligned); // trigger re-render of content blocks
return newList;
});
};
const handleDown = (x) => {
props.setList(oldList => {
const index = props.list.indexOf(x);
const newList = [...oldList];
[newList[index], newList[index + 1]] = [newList[index + 1], newList[index]];
setIsAligned(!isAligned); // trigger re-render of content blocks
return newList;
});
};
return (
<Accordion.Item eventKey={props.index.toString()}>
<Accordion.Header >
<div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", width: "100%" }}>
{x.blockType}
<ButtonGroup style={{ paddingRight: "2%" }} >
{props.list.indexOf(x) != 0 && (
<Button as='div' style={{ fontSize: "0.8rem", padding: "0.25rem 0.5rem" }} variant="outline-secondary"
onClick={(ev) => { ev.stopPropagation(); handleUp(x) }}>
<i className="bi bi-arrow-up"></i>
</Button>)}
{props.list.indexOf(x) != (props.list.length - 1) && (
<Button as='div' style={{ fontSize: "0.8rem", padding: "0.25rem 0.5rem" }} variant="outline-secondary"
onClick={(ev) => { ev.stopPropagation(); handleDown(x) }}>
<i className="bi bi-arrow-down"></i>
</Button>)}
<Button as='div' size="sm" variant="outline-danger"
onClick={(ev) => { ev.stopPropagation(); removeFromList(x) }}>
<i className="bi bi-x-lg"></i>
</Button>
</ButtonGroup>
</div>
</Accordion.Header>
<Accordion.Body>
{x.blockType != "Image" ? (
<Form.Control as="textarea" value={content} onChange={(ev) => { x.content = ev.target.value; setContent(ev.target.value); }}></Form.Control>
) : (
<div>
<ImageForm />
</div>
)}
</Accordion.Body>
</Accordion.Item>
);
function ImageForm() {
return (
images.map((image, index) => (
<label key={index} style={{ paddingRight: "20px" }}>
<input checked={x.content == image.url} type="radio" name="image" onClick={() => { x.content = image.url; setIsAligned(!isAligned); }} />
<img style={{ borderRadius: "5%", paddingLeft: "5px", width: '256px', height: '144px' }} src={image.url} alt={image.alt} />
</label>
))
);
}
}
function ActionList(props) {
// Placed here because otherwise handleAction couldn't call navigate.
// Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
const navigate = useNavigate();
const list = props.list;
const title = props.title;
const date = props.date;
return (
<Col className="pt-4">
<Button variant="warning" style={{ marginBottom: "2%", width: "100%" }} onClick={() => handleAction("draft")}>Save as Draft</Button>
<Button variant="success" style={{ marginBottom: "10%", width: "100%" }} onClick={() => handleAction("publish")}>Publish</Button>
<Form.Control type="date" name="date" value={date} onChange={(ev) => props.setDate(ev.target.value)} />
<Button variant="secondary" style={{ marginTop: "2%", width: "100%" }} onClick={() => handleAction("programmed")}>Schedule Publication</Button>
</Col>
);
function handleAction(action) {
////////////////////////////////////CONTROLLO E SETALERT SE NON VA BENE POI RETURN()
let valid = true;
if (title == "") {
console.log("You have to choose a title for the page.");
valid = false;
}
else if (!(list.some(item => item.blockType == 'Header')) ||
(!(list.some(item => item.blockType == 'Paragraph') || list.some(item => item.blockType == 'Image')))
) {
console.log("You have to insert at least a Header and a Paragraph/Image.");
//handleError("You have to insert at least a Header and a Paragraph/Image");
valid = false;
}
else if (list.some(item => (item.content == ""))) {
console.log("At least one block without content!");
valid = false;
}
if (valid) {
const data = { // Data formatted. Ready to send it to the server for Page Creation.
title: title,
blocks: JSON.stringify(list) //saved as json in db
};
switch (action) {
case "draft":
Object.assign(data, { publishDate: null });
break;
case "publish":
Object.assign(data, { publishDate: dayjs().format("YYYY-MM-DD") });
break;
case "programmed":
const formattedDate = dayjs(date);
if (!formattedDate.isValid() || formattedDate.isBefore(dayjs())) { //dayjs() returns today date
console.log("Select a valid date."); // handleError !!
return;
}
Object.assign(data, { publishDate: formattedDate.format("YYYY-MM-DD") });
break;
default:
break;
}
API.createPage(data)
.then(() => {
navigate("/backoffice")
})
.catch((err) => handleError(err));
}
}
}
function Title(props) {
return (
<Form.Control type="text" name="text" value={props.title} placeholder="Page Title" onChange={ev => props.setTitle(ev.target.value)} />
);
}
export { Title, ActionList, BlockList, CreatePage };
I get this error: Cannot update a component (`MyBlock`) while rendering a different component (`AddRoute`).
find the error in the code that causes this.
|
d1d52868aae5d7aaacb48bd7ff2b2206
|
{
"intermediate": 0.389899879693985,
"beginner": 0.48652541637420654,
"expert": 0.12357475608587265
}
|
12,141
|
How can I get a catalog of galaxies from a model in halotools?
|
f30fdd34fe20b3b71e1730eca613ca86
|
{
"intermediate": 0.2841634452342987,
"beginner": 0.06875606626272202,
"expert": 0.6470804810523987
}
|
12,142
|
create a UI to pick a docx file, read the underline text, and write it to an xlsx file with Flutter and show full code
|
3d52a7779456f475caa27a9357aa0806
|
{
"intermediate": 0.5290355086326599,
"beginner": 0.21538981795310974,
"expert": 0.25557461380958557
}
|
12,143
|
package serverUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
public class ConnectionManager {
private static final String ACK_MESSAGE_PREFIX = "<%s>Ack";
private static final int BUFFER_SIZE = 1024 * 1024;
ServerSocketChannel serverSocketChannel;
int port;
public ConnectionManager(int port) {
this.port = port;
}
public void initialize() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
System.out.println("Server started on port " + port);
System.out.println("============ * ============");
}
public void registerSelector(Selector selector) throws ClosedChannelException {
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void processQuery(Selector selector, SelectionKey key) throws IOException {
if (!key.isValid()) {
return;
}
if (key.isAcceptable()) {
acceptConnection(key, selector);
} else if (key.isReadable()) {
handleRead(key);
}
}
private void acceptConnection(SelectionKey key, Selector selector) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel clientSocketChannel = serverSocketChannel.accept();
clientSocketChannel.configureBlocking(false);
clientSocketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("Accepted connection from " + clientSocketChannel.getRemoteAddress());
}
private void handleRead(SelectionKey key) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
SocketChannel clientSocketChannel = (SocketChannel) key.channel();
int bytesRead;
while ((bytesRead = clientSocketChannel.read(buffer)) > 0) {
buffer.flip();
// проверяем наличие данных в буфере
if (buffer.remaining() < 8) {
continue;
}
// читаем длину имени файла в байтах
int nameLength = buffer.getInt();
// проверяем наличие данных в буфере
if (buffer.remaining() < nameLength + 4) {
buffer.position(buffer.position() - 4);
buffer.compact();
continue;
}
// читаем имя файла
byte[] nameBytes = new byte[nameLength];
buffer.get(nameBytes);
String fileName = new String(nameBytes, StandardCharsets.UTF_8);
// читаем длину файла в байтах
int fileLength = buffer.getInt();
// проверяем наличие данных в буфере
if (buffer.remaining() < fileLength + 8) {
buffer.position(buffer.position() - 8);
buffer.compact();
continue;
}
// читаем содержимое файла
byte[] fileContent = new byte[fileLength];
buffer.get(fileContent, 0, fileLength);
// проверяем разделитель
long separator = buffer.getLong();
if (separator != 0) {
throw new RuntimeException("Invalid separator");
}
// очищаем буфер
buffer.clear();
// сохраняем файл
saveFile(fileName, fileContent);
// отправляем подтверждение о сохранении файла
sendAck(clientSocketChannel, fileName);
}
if (bytesRead == -1) {
System.out.println("Closed connection with " + clientSocketChannel.getRemoteAddress());
clientSocketChannel.close();
key.cancel();
System.out.println("============ * ============");
}
}
private void saveFile(String filename, byte[] fileContent) throws IOException {
File file = new File("files\\" + filename);
System.out.println("Saving file " + filename);
try (FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(fileContent);
}
System.out.println("File " + filename + " saved successfully");
}
private void sendAck(SocketChannel clientSocketChannel, String filename) throws IOException {
String ackMessage = String.format(ACK_MESSAGE_PREFIX, filename);
byte[] ackMessageBytes = ackMessage.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(ackMessageBytes.length + Integer.BYTES);
buffer.putInt(ackMessageBytes.length);
buffer.put(ackMessageBytes);
buffer.flip();
while (buffer.hasRemaining()) {
clientSocketChannel.write(buffer);
}
System.out.println("Sent acknowledgement for " + filename);
buffer.clear(); // Очищаем буфер перед чтением новых данных
}
}
1. Необходимо выполнить главное условие: одновременную обработку нескольких клиентов. Например, если один из клиентов остановился на передаче файла где-то на половине, и чтобы не крутиться в холостом цикле, в это время необходимо обрабатывать запросы других клиентов. Для достижения данного условия необходимо создать контекст соединения и связать его с конкретным соединением (Selection Key) и получать его через метод attachment. В этом же контексте можно хранить название файла, текущий состояние буффера, этап передачи файла.
2. Так как сокет в неблокирующем режиме, то он не будет блокироваться при считывании данных в буффер и будет просто крутиться в холостом цикле.
3. Ну и лучше не хранить в памяти файл, так как он может не влезть полностью в оперативку, нужно считывать батчами и загружать в файл.
|
4386b1854927756da1d5ca0b1c70a222
|
{
"intermediate": 0.3234023153781891,
"beginner": 0.5804898738861084,
"expert": 0.09610777348279953
}
|
12,144
|
package serverUtils;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
public class Console {
public void start() throws IOException {
ConnectionManager connectionManager = new ConnectionManager(6789);
connectionManager.initialize();
Selector selector = Selector.open();
connectionManager.registerSelector(selector);
while (true) {
int readyChannelsCount = selector.select();
if (readyChannelsCount == 0) {
continue;
}
Iterator<SelectionKey> selectedKeysIterator = selector.selectedKeys().iterator();
while (selectedKeysIterator.hasNext()) {
SelectionKey key = selectedKeysIterator.next();
selectedKeysIterator.remove();
connectionManager.processQuery(selector, key);
}
}
}
}
package serverUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
public class ConnectionManager {
private static final String ACK_MESSAGE_PREFIX = “<%s>Ack”;
private static final int BUFFER_SIZE = 1024 * 1024;
ServerSocketChannel serverSocketChannel;
int port;
public ConnectionManager(int port) {
this.port = port;
}
public void initialize() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
System.out.println(“Server started on port " + port);
System.out.println(”============ * ============");
}
public void registerSelector(Selector selector) throws ClosedChannelException {
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void processQuery(Selector selector, SelectionKey key) throws IOException {
if (!key.isValid()) {
return;
}
if (key.isAcceptable()) {
acceptConnection(key, selector);
} else if (key.isReadable()) {
handleRead(key);
}
}
private void acceptConnection(SelectionKey key, Selector selector) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel clientSocketChannel = serverSocketChannel.accept();
clientSocketChannel.configureBlocking(false);
clientSocketChannel.register(selector, SelectionKey.OP_READ);
System.out.println(“Accepted connection from " + clientSocketChannel.getRemoteAddress());
}
private void handleRead(SelectionKey key) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
SocketChannel clientSocketChannel = (SocketChannel) key.channel();
int bytesRead;
while ((bytesRead = clientSocketChannel.read(buffer)) > 0) {
buffer.flip();
// проверяем наличие данных в буфере
if (buffer.remaining() < 8) {
continue;
}
// читаем длину имени файла в байтах
int nameLength = buffer.getInt();
// проверяем наличие данных в буфере
if (buffer.remaining() < nameLength + 4) {
buffer.position(buffer.position() - 4);
buffer.compact();
continue;
}
// читаем имя файла
byte[] nameBytes = new byte[nameLength];
buffer.get(nameBytes);
String fileName = new String(nameBytes, StandardCharsets.UTF_8);
// читаем длину файла в байтах
int fileLength = buffer.getInt();
// проверяем наличие данных в буфере
if (buffer.remaining() < fileLength + 8) {
buffer.position(buffer.position() - 8);
buffer.compact();
continue;
}
// читаем содержимое файла
byte[] fileContent = new byte[fileLength];
buffer.get(fileContent, 0, fileLength);
// проверяем разделитель
long separator = buffer.getLong();
if (separator != 0) {
throw new RuntimeException(“Invalid separator”);
}
// очищаем буфер
buffer.clear();
// сохраняем файл
saveFile(fileName, fileContent);
// отправляем подтверждение о сохранении файла
sendAck(clientSocketChannel, fileName);
}
if (bytesRead == -1) {
System.out.println(“Closed connection with " + clientSocketChannel.getRemoteAddress());
clientSocketChannel.close();
key.cancel();
System.out.println(”============ * ============”);
}
}
private void saveFile(String filename, byte[] fileContent) throws IOException {
File file = new File(“files\” + filename);
System.out.println("Saving file " + filename);
try (FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(fileContent);
}
System.out.println(“File " + filename + " saved successfully”);
}
private void sendAck(SocketChannel clientSocketChannel, String filename) throws IOException {
String ackMessage = String.format(ACK_MESSAGE_PREFIX, filename);
byte[] ackMessageBytes = ackMessage.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(ackMessageBytes.length + Integer.BYTES);
buffer.putInt(ackMessageBytes.length);
buffer.put(ackMessageBytes);
buffer.flip();
while (buffer.hasRemaining()) {
clientSocketChannel.write(buffer);
}
System.out.println("Sent acknowledgement for " + filename);
buffer.clear(); // Очищаем буфер перед чтением новых данных
}
}
Есть приложение на java. В серверную часть нужно добавить возможность обработки нескольких клиентов. Например, если один из клиентов остановился на передаче файла где-то на половине, и чтобы не крутиться в холостом цикле, в это время необходимо обрабатывать запросы других клиентов. Для достижения данного условия необходимо создать контекст соединения и связать его с конкретным соединением (Selection Key) и получать его через метод attachment. В этом же контексте можно хранить название файла, текущий состояние буффера, этап передачи файла. Использовать многопоточность нельзя
|
7e0f282d44bb7ca4f07d384c7d10d785
|
{
"intermediate": 0.24517688155174255,
"beginner": 0.5364795923233032,
"expert": 0.21834352612495422
}
|
12,145
|
Есть приложение на java. Вот серверная часть:
package serverUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
public class ConnectionManager {
private static final String ACK_MESSAGE_PREFIX = "<%s>Ack";
private static final int BUFFER_SIZE = 1024 * 1024;
ServerSocketChannel serverSocketChannel;
int port;
public ConnectionManager(int port) {
this.port = port;
}
public void initialize() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
System.out.println("Server started on port " + port);
System.out.println("============ * ============");
}
public void registerSelector(Selector selector) throws ClosedChannelException {
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void processQuery(Selector selector, SelectionKey key) throws IOException {
if (!key.isValid()) {
return;
}
if (key.isAcceptable()) {
acceptConnection(key, selector);
} else if (key.isReadable()) {
handleRead(key);
}
}
private void acceptConnection(SelectionKey key, Selector selector) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel clientSocketChannel = serverSocketChannel.accept();
clientSocketChannel.configureBlocking(false);
clientSocketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("Accepted connection from " + clientSocketChannel.getRemoteAddress());
}
private void handleRead(SelectionKey key) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
SocketChannel clientSocketChannel = (SocketChannel) key.channel();
int bytesRead;
while ((bytesRead = clientSocketChannel.read(buffer)) > 0) {
buffer.flip();
// проверяем наличие данных в буфере
if (buffer.remaining() < 8) {
continue;
}
// читаем длину имени файла в байтах
int nameLength = buffer.getInt();
// проверяем наличие данных в буфере
if (buffer.remaining() < nameLength + 4) {
buffer.position(buffer.position() - 4);
buffer.compact();
continue;
}
// читаем имя файла
byte[] nameBytes = new byte[nameLength];
buffer.get(nameBytes);
String fileName = new String(nameBytes, StandardCharsets.UTF_8);
// читаем длину файла в байтах
int fileLength = buffer.getInt();
// проверяем наличие данных в буфере
if (buffer.remaining() < fileLength + 8) {
buffer.position(buffer.position() - 8);
buffer.compact();
continue;
}
// читаем содержимое файла
byte[] fileContent = new byte[fileLength];
buffer.get(fileContent, 0, fileLength);
// проверяем разделитель
long separator = buffer.getLong();
if (separator != 0) {
throw new RuntimeException("Invalid separator");
}
// очищаем буфер
buffer.clear();
// сохраняем файл
saveFile(fileName, fileContent);
// отправляем подтверждение о сохранении файла
sendAck(clientSocketChannel, fileName);
}
if (bytesRead == -1) {
System.out.println("Closed connection with " + clientSocketChannel.getRemoteAddress());
clientSocketChannel.close();
key.cancel();
System.out.println("============ * ============");
}
}
private void saveFile(String filename, byte[] fileContent) throws IOException {
File file = new File("files\\" + filename);
System.out.println("Saving file " + filename);
try (FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(fileContent);
}
System.out.println("File " + filename + " saved successfully");
}
private void sendAck(SocketChannel clientSocketChannel, String filename) throws IOException {
String ackMessage = String.format(ACK_MESSAGE_PREFIX, filename);
byte[] ackMessageBytes = ackMessage.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(ackMessageBytes.length + Integer.BYTES);
buffer.putInt(ackMessageBytes.length);
buffer.put(ackMessageBytes);
buffer.flip();
while (buffer.hasRemaining()) {
clientSocketChannel.write(buffer);
}
System.out.println("Sent acknowledgement for " + filename);
buffer.clear(); // Очищаем буфер перед чтением новых данных
}
}
package serverUtils;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
public class Console {
public void start() throws IOException {
ConnectionManager connectionManager = new ConnectionManager(6789);
connectionManager.initialize();
Selector selector = Selector.open();
connectionManager.registerSelector(selector);
while (true) {
int readyChannelsCount = selector.select();
if (readyChannelsCount == 0) {
continue;
}
Iterator<SelectionKey> selectedKeysIterator = selector.selectedKeys().iterator();
while (selectedKeysIterator.hasNext()) {
SelectionKey key = selectedKeysIterator.next();
selectedKeysIterator.remove();
connectionManager.processQuery(selector, key);
}
}
}
}
Ее нужно исправить, добавив возможность обработки нескольких клиентов. Например, если один из клиентов остановился на передаче файла где-то на половине, и чтобы не крутиться в холостом цикле, в это время необходимо обрабатывать запросы других клиентов. Для достижения данного условия необходимо создать контекст соединения и связать его с конкретным соединением (Selection Key) и получать его через метод attachment. В этом же контексте можно хранить название файла, текущий состояние буффера, этап передачи файла.
|
df00ed4609914d76e145ca86e4d8518d
|
{
"intermediate": 0.31660863757133484,
"beginner": 0.574708878993988,
"expert": 0.10868241637945175
}
|
12,146
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
import ntplib
import os
import ta
API_KEY = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 5000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
try:
usdt_balance = next((item for item in account_info['accountBalance'] if item["asset"] == "USDT"), {"free": 0})['free']
except KeyError:
usdt_balance = 0
print("Error: Could not retrieve USDT balance from API response.")
max_trade_size = float(usdt_balance) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
def sync_time():
ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org', version=3)
now = time.time()
offset = response.offset
new_time = now + offset
# Set the system clock to the new time
os.system(f'sudo date -s @{int(new_time)}')
print(f'New time: {dt.datetime.now()}')
recv_window = 10000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
return exchange.fetch_time()
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
df = get_klines(symbol, '1m', 44640)
# Define function to generate trading signals
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Calculate EMA indicator
ema = ta.trend.EMAIndicator(df['Close'], window=10)
# Calculate MA indicator
ma = ta.trend.SMAIndicator(df['Close'], window=20)
# Calculate EMA indicator
ema_value = ema.ema_indicator()[-1] #get the EMA indicator value for the last value in the DataFrame
ma_value = ma.sma_indicator()[-1] #get the MA indicator value for the last value in the DataFrame
#Bearish pattern with EMA and MA indicators
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close and
close<ema_value and close<ma_value):
return 'sell'
#Bullish pattern with EMA and MA indicators
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close and
close>ema_value and close>ma_value):
return 'buy'
#No clear pattern with EMA and MA indicators
else:
return ''
df = get_klines(symbol, '1m', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Set default value for response
response = {}
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY',
type='MARKET',
quantity=abs(float(current_position['positionAmt'])),
positionSide=current_position['positionSide'],
reduceOnly=True
)
if 'orderId' in response:
print(f'Closed position: {response}')
else:
print(f'Error closing position: {response}')
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'ask' in ticker:
price = ticker['ask']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'bid' in ticker:
price = ticker['bid']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
# Placing new order
api_method = 'fapiPrivatePostOrder'
params = {
'symbol': symbol,
'side': signal.upper(),
'type': order_type,
'quantity': quantity,
'positionSide': position_side,
'leverage': leverage,
'price': price,
'stopPrice': stop_loss_price,
'takeProfit': take_profit_price
}
response = getattr(binance_futures, api_method)(params=params)
if 'orderId' in response:
print(f'Order placed: {response}')
else:
print(f'Error placing order: {response}')
time.sleep(1)
return response
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:{signal}")
time.sleep(1)
But some time it gives me wrong signals , I need after signal_generator give me signal price doesn't go against my signal more than -0.2%
|
8bc78585f376e87ecf8d016044d74253
|
{
"intermediate": 0.3887886703014374,
"beginner": 0.4982946515083313,
"expert": 0.11291676759719849
}
|
12,147
|
карточки/обложки расползаются, см скриншот: https://yadi.sk/d/EMb3XlXLUeHmFA
нужно, чтобы все было как здесь, см скриншот: https://yadi.sk/d/0evHq4J4eg709A
код:
<!-- audio player -->
<div class="selling-right-now">
<h3>Selling right now</h3>
<div class="selling-right-now-track">
<% tracks.forEach((track, index) => { %>
<div class="card" style="height: auto; display: flex;">
<img src="/img/<%= track.image_filename || 'default-track-image.png' %>" alt="<%= track.title %>" style="object-fit: cover; width: 100%;">
<div class="card-body">
<h4><%= track.title %></h4>
<p><%= track.album_title || "No Album" %></p>
<div class="player-wrapper">
<i class="fas fa-play"></i>
<audio id="audio-<%= index %>" src="/tracks/<%= track.filename %>"></audio>
</div>
</div>
</div>
<% }); %>
</div>
</div> <!-- end -->
main.css:
/* audio player */
.selling-right-now {
margin: 50px auto;
max-width: 800px;
}
.selling-right-now h3 {
text-align: center;
}
.selling-right-now-track {
display: flex;
justify-content: center;
align-items: center;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.card {
margin-right: 20px;
margin-bottom: 20px;
flex-shrink: 0;
max-width: 300px;
text-align: center;
position: relative;
}
.card-img {
position: relative;
width: 100%;
height: 0;
padding-bottom: 100%;
}
.card-img img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.card-body {
padding: 10px;
}
.card-body h4 {
margin-top: 0;
font-size: 18px;
font-weight: bold;
}
.card-body p {
margin-bottom: 0;
font-size: 14px;
}
/* audio player styles */
.player-wrapper {
position: relative;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
.player-wrapper:before {
content: "";
display: block;
padding-top: 100%;
}
.player-wrapper i {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 30px;
color: #333;
cursor: pointer;
}
|
4f55c27c2272788fe9ca26861ed4bbb1
|
{
"intermediate": 0.23560631275177002,
"beginner": 0.45659029483795166,
"expert": 0.3078033924102783
}
|
12,148
|
Microsoft SQL 2008 is working with net frame work 4 right ?
|
1809650c97e44546fa3ad94e68e05677
|
{
"intermediate": 0.5499182343482971,
"beginner": 0.16907960176467896,
"expert": 0.2810021638870239
}
|
12,149
|
8.
Question 8
A USB memory stick is an example of which of the following components of computer architecture?
1 point
Central Processing Unit
Secondary Memory
Output Device
Main Memory
|
8f3801c0bb65870bb275f12166eba5a1
|
{
"intermediate": 0.2634781002998352,
"beginner": 0.4689784348011017,
"expert": 0.2675434648990631
}
|
12,150
|
LibreOffice SDK как сделать AlignCenter для XText используемый в XCell на C++?
|
e746e92ba7630a3f993b2e4a7cd2475e
|
{
"intermediate": 0.8301693797111511,
"beginner": 0.09626030921936035,
"expert": 0.07357030361890793
}
|
12,151
|
enhance terser options to minify the bundle. I am using javascript classes and bundling with rollup.
terser({
compress: {
passes: 2,
pure_getters: true,
unsafe_math: true,
},
mangle: {
properties: {
regex: /^_/,
},
},
}),
|
9bc85e74b8ea16b1b024dd32120c3fd8
|
{
"intermediate": 0.4125078618526459,
"beginner": 0.28921717405319214,
"expert": 0.2982749938964844
}
|
12,152
|
Что делает Awaited в typescript?
|
dd908d1ede44d6dc8a3126beaa2c8972
|
{
"intermediate": 0.1791490614414215,
"beginner": 0.6460154056549072,
"expert": 0.17483551800251007
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.