row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
10,446
|
how can i add image in the form so it saves to the collection of this?
here is my code
import { Text, View, TextInput, Pressable, ScrollView } from 'react-native';
import { gStyle } from '../styles/style';
import React, {useState} from 'react';
import Footer from '../components/Footer';
import Header from '../components/Header';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState, useEffect} from 'react';
import { useNavigation } from '@react-navigation/native';
export default function FormAddMK() {
const [text, setValue] = useState('');
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [price, setPrice] = useState('');
const [time, setTime] = useState('');
const [timeOfMK, setTimeOfMK] = useState('');
const [person, setPerson] = useState('');
const [image, setImage] = useState(null);
const onChangeName = (text) => setName(text);
const onChangeDescription = (text) => setDescription(text);
const onChangePrice = (text) => setPrice(text);
const onChangeTime = (text) => setTime(text);
const onChangeTimeOfMK = (text) => setTimeOfMK(text);
const onChangePerson = (text) => setPerson(text);
const onChangeImage = (event) => {
const file = event.target.files[0];
setImage(file);
};
const addHandler = async () => {
const storageRef = firebase.storage().ref();
const imageRef = storageRef.child(`images/${Date.now()}`);
const uploadTask = imageRef.put(image);
uploadTask.on(
'state_changed',
null,
(error) => {
console.log(error);
},
async () => {
const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
firebase.database().ref('FutureMK').push({
id: Date.now(),
name: name,
description: description,
price: price,
time: time,
timeOfMK: timeOfMK,
person: person,
image: image
})
})}
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.formAdd}>
<Text style={gStyle.header}>Добавить мастер-класс</Text>
<View style={gStyle.formBlock}>
<View>
<Text>Название мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChange}
/>
</View>
<View>
<Text>Дата мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChange}
/>
</View>
<View>
<Text>Описание мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChange}
/>
</View>
<View>
<Text>Изображение</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChange}
/>
</View>
<View>
<Text>Стоимость мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChange}
/>
</View>
<View>
<Text>Кол-во людей на бронирование</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChange}
/>
</View>
<View>
<Text>Продолжительность мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChange}
/>
</View>
<Pressable style={gStyle.btnAddMK} onPress={()=>addHandler(text)}>
<Text style={gStyle.btnAddMKtxt}>Сохранить</Text>
</Pressable>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
|
42e6a06647d2fd6b94f75e68fc26290f
|
{
"intermediate": 0.5024474859237671,
"beginner": 0.35906413197517395,
"expert": 0.1384882926940918
}
|
10,447
|
я хочу добавлять музыку из soundcloud к профилю, чтобы она правильно отображалась в html. Вот код:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width="100%" height="300" scrolling="no" frameborder="no" src="<%= musician.soundcloud %>"></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<!-- Check if the user is logged in and is the owner of the profile -->
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">SoundCloud:</label>
<input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud %>">
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
например, вот ссылка: https://soundcloud.com/ty-segall-official/my-ladys-on-fire?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing
|
eea30b177363917591f8fd2bdafa4d56
|
{
"intermediate": 0.3619075417518616,
"beginner": 0.4706031382083893,
"expert": 0.16748933494091034
}
|
10,448
|
compare two json file in java and output difference
|
f632b2c9d97f8d612e9804a6b657d646
|
{
"intermediate": 0.4945719540119171,
"beginner": 0.2569228708744049,
"expert": 0.24850520491600037
}
|
10,449
|
securityFilterChain in spring 6
|
0744e2aecfadbc61bbba4b11157f27ce
|
{
"intermediate": 0.3632659614086151,
"beginner": 0.2319931536912918,
"expert": 0.4047408998012543
}
|
10,450
|
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 requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# 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)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
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': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
markets = binance_futures.load_markets()
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialze 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 = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
order_params = {
"type": order_type,
"positionSide": position_side,
"quantity": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"reduceOnly": True,
"newOrderRespType": "RESULT",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": leverage
}
try:
order_params['symbol'] = symbol
response = binance_futures.fapiPrivatePostOrder(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: 06/06/2023 10:43:47
Traceback (most recent call last):
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 559, in fetch
response.raise_for_status()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: for url: https://api.binance.com/sapi/v1/capital/config/getall?timestamp=1686037427452&recvWindow=10000&signature=48740c47a1d075cb5f34be8318c1a666721f0157c5850b725f9f058bf2c3a287
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 58, in <module>
markets = binance_futures.load_markets()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 1390, in load_markets
currencies = self.fetch_currencies()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 1705, in fetch_currencies
response = self.sapiGetCapitalConfigGetall(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7274, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2862, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 575, in fetch
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7251, in handle_errors
self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3172, in throw_exactly_matched_exception
raise exact[string](message)
ccxt.base.errors.InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
Please give me right code
|
a430c3443f4cbc5602dc6239a5e4c258
|
{
"intermediate": 0.549864649772644,
"beginner": 0.34405308961868286,
"expert": 0.10608229786157608
}
|
10,451
|
c# word gen document and save window dialog
|
2c8b9624893a55b328da7c8d9d53d9b2
|
{
"intermediate": 0.24134576320648193,
"beginner": 0.26621443033218384,
"expert": 0.49243980646133423
}
|
10,452
|
D3D11CreateDevice怎么使用
|
6c2ed986f3718120389f522f5e98ca4f
|
{
"intermediate": 0.23988692462444305,
"beginner": 0.2484026998281479,
"expert": 0.5117103457450867
}
|
10,453
|
Представь, что ты программист Django. Следующий код вызывает эту ошибку: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
class UserUpdateApi(generics.UpdateAPIView):
serializer_class = UserUpdateSerializer
queryset = CustomUser.objects.all()
permission_classes = [permissions.IsAuthenticated]
def get_object(self):
return self.request.user
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def update(self, request, *args, **kwargs):
user = self.get_object()
serializer = self.get_serializer(user, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
response_data = ''
email = request.data.get('email', None)
phone_number = request.data.get('phone_number', None)
if phone_number:
res = SendOrResendSMSAPIView.as_view()(request._request, *args, **kwargs)
if res.status_code == 200:
response_data = {"detail": _(
"Verification e-mail and SMS sent.")}
elif email and not phone_number:
res = ResendEmailVerificationView.as_view()(request._request, *args, **kwargs)
if res.status_code == 200:
response_data = {"detail": _(
"Verification e-mail sent.")}
else:
res = SendOrResendSMSAPIView.as_view()(request._request, *args, **kwargs)
if res.status_code == 200:
response_data = {"detail": _("Verification SMS sent.")}
self.perform_update(serializer)
return Response(serializer.data, status=status.HTTP_200_OK)
Исправь этот код.
|
09a54582d40fb9b00e857b9984145aa4
|
{
"intermediate": 0.4096064567565918,
"beginner": 0.4033585786819458,
"expert": 0.1870349794626236
}
|
10,454
|
я хочу добавлять музыку из soundcloud к профилю, чтобы она правильно отображалась в html. Вот код:
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”);
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query });
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src=”/img/<%= musician.thumbnail %>" alt=“<%= musician.name %>”>
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” src=“<%= musician.soundcloud %>”></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href=“/profile/<%= musician.id %>/edit”>Edit profile</a>
<!-- Check if the user is logged in and is the owner of the profile -->
<div id=“edit-profile-modal” class=“modal”>
<div class=“modal-content”>
<span class=“close”>×</span>
<h2>Edit Profile</h2>
<form action=“/profile/<%= musician.id %>/edit” method=“POST” enctype=“multipart/form-data”>
<div>
<label for=“name”>Name:</label>
<input type=“text” id=“name” name=“name” value=“<%= musician.name %>”>
</div>
<div>
<label for=“genre”>Genre:</label>
<input type=“text” id=“genre” name=“genre” value=“<%= musician.genre %>”>
</div>
<div>
<label for=“instrument”>Instrument:</label>
<input type=“text” id=“instrument” name=“instrument” value=“<%= musician.instrument %>”>
</div>
<div>
<label for=“location”>Location:</label>
<input type=“text” id=“location” name=“location” value=“<%= musician.location %>”>
</div>
<div>
<label for=“bio”>Bio:</label>
<textarea id=“bio” name=“bio”><%= musician.bio %></textarea>
</div>
<div>
<label for=“soundcloud”>SoundCloud:</label>
<input type=“text” id=“soundcloud” name=“soundcloud” value=“<%= musician.soundcloud %>”>
</div>
<div>
<label for=“thumbnail”>Thumbnail:</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
</div>
<button type=“submit”>Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById(“edit-profile-modal”);
const btn = document.getElementsByTagName(“a”)[0];
const span = document.getElementsByClassName(“close”)[0];
btn.onclick = function() {
modal.style.display = “block”;
}
span.onclick = function() {
modal.style.display = “none”;
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = “none”;
}
}
</script>
</body>
</html>
Мне нужно преобразовать ссылку типа https://soundcloud.com/ty-segall-official/saturday-pt-2-live?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing в embded типа: <iframe width="100%" height="300" scrolling="no" frameborder="no" allow="autoplay" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/1431306373&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe><div style="font-size: 10px; color: #cccccc;line-break: anywhere;word-break: normal;overflow: hidden;white-space: nowrap;text-overflow: ellipsis; font-family: Interstate,Lucida Grande,Lucida Sans Unicode,Lucida Sans,Garuda,Verdana,Tahoma,sans-serif;font-weight: 100;"><a href="https://soundcloud.com/ty-segall-official" title="Ty Segall" target="_blank" style="color: #cccccc; text-decoration: none;">Ty Segall</a> · <a href="https://soundcloud.com/ty-segall-official/saturday-pt-2-live" title="Saturday Pt. 2 (Live)" target="_blank" style="color: #cccccc; text-decoration: none;">Saturday Pt. 2 (Live)</a></div>
чтобы пользователь мог просто вставить НОРМАЛЬНУЮ ссылку типа https://soundcloud.com/ty-segall-official/saturday-pt-2-live?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing и вставлялся плеер в profile.ejs
Учти, что API soundcloud больше не предоставляет
|
ae2cc48cc9c931c7c4e2346299ae3f8b
|
{
"intermediate": 0.4417024254798889,
"beginner": 0.42180517315864563,
"expert": 0.13649241626262665
}
|
10,455
|
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”);
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query });
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src=”/img/<%= musician.thumbnail %>" alt=“<%= musician.name %>”>
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” src=“<%= musician.soundcloud %>”></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href=“/profile/<%= musician.id %>/edit”>Edit profile</a>
<!-- Check if the user is logged in and is the owner of the profile -->
<div id=“edit-profile-modal” class=“modal”>
<div class=“modal-content”>
<span class=“close”>×</span>
<h2>Edit Profile</h2>
<form action=“/profile/<%= musician.id %>/edit” method=“POST” enctype=“multipart/form-data”>
<div>
<label for=“name”>Name:</label>
<input type=“text” id=“name” name=“name” value=“<%= musician.name %>”>
</div>
<div>
<label for=“genre”>Genre:</label>
<input type=“text” id=“genre” name=“genre” value=“<%= musician.genre %>”>
</div>
<div>
<label for=“instrument”>Instrument:</label>
<input type=“text” id=“instrument” name=“instrument” value=“<%= musician.instrument %>”>
</div>
<div>
<label for=“location”>Location:</label>
<input type=“text” id=“location” name=“location” value=“<%= musician.location %>”>
</div>
<div>
<label for=“bio”>Bio:</label>
<textarea id=“bio” name=“bio”><%= musician.bio %></textarea>
</div>
<div>
<label for=“soundcloud”>SoundCloud:</label>
<input type=“text” id=“soundcloud” name=“soundcloud” value=“<%= musician.soundcloud %>”>
</div>
<div>
<label for=“thumbnail”>Thumbnail:</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
</div>
<button type=“submit”>Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById(“edit-profile-modal”);
const btn = document.getElementsByTagName(“a”)[0];
const span = document.getElementsByClassName(“close”)[0];
btn.onclick = function() {
modal.style.display = “block”;
}
span.onclick = function() {
modal.style.display = “none”;
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = “none”;
}
}
</script>
</body>
</html>
Мне нужно преобразовать ссылку типа https://soundcloud.com/ty-segall-official/saturday-pt-2-live?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing в embded типа: <iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” allow=“autoplay” src=“https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/1431306373&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true”></iframe><div style=“font-size: 10px; color: #cccccc;line-break: anywhere;word-break: normal;overflow: hidden;white-space: nowrap;text-overflow: ellipsis; font-family: Interstate,Lucida Grande,Lucida Sans Unicode,Lucida Sans,Garuda,Verdana,Tahoma,sans-serif;font-weight: 100;”><a href=“https://soundcloud.com/ty-segall-official” title=“Ty Segall” target=“_blank” style=“color: #cccccc; text-decoration: none;”>Ty Segall</a> · <a href=“https://soundcloud.com/ty-segall-official/saturday-pt-2-live” title=“Saturday Pt. 2 (Live)” target=“_blank” style=“color: #cccccc; text-decoration: none;”>Saturday Pt. 2 (Live)</a></div>
чтобы пользователь мог просто вставить НОРМАЛЬНУЮ ссылку типа https://soundcloud.com/ty-segall-official/saturday-pt-2-live?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing и вставлялся плеер в profile.ejs
Учти, что API soundcloud больше не предоставляет
|
e48fa56cb80509ca29852b9189e45d70
|
{
"intermediate": 0.4536873996257782,
"beginner": 0.36664488911628723,
"expert": 0.17966769635677338
}
|
10,456
|
how to create trend plot from a set of data
|
69d4ebc8470862a98e7d8e47099fea09
|
{
"intermediate": 0.3417595326900482,
"beginner": 0.23120346665382385,
"expert": 0.42703700065612793
}
|
10,457
|
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”);
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query });
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src=”/img/<%= musician.thumbnail %>" alt=“<%= musician.name %>”>
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” src=“<%= musician.soundcloud %>”></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href=“/profile/<%= musician.id %>/edit”>Edit profile</a>
<!-- Check if the user is logged in and is the owner of the profile -->
<div id=“edit-profile-modal” class=“modal”>
<div class=“modal-content”>
<span class=“close”>×</span>
<h2>Edit Profile</h2>
<form action=“/profile/<%= musician.id %>/edit” method=“POST” enctype=“multipart/form-data”>
<div>
<label for=“name”>Name:</label>
<input type=“text” id=“name” name=“name” value=“<%= musician.name %>”>
</div>
<div>
<label for=“genre”>Genre:</label>
<input type=“text” id=“genre” name=“genre” value=“<%= musician.genre %>”>
</div>
<div>
<label for=“instrument”>Instrument:</label>
<input type=“text” id=“instrument” name=“instrument” value=“<%= musician.instrument %>”>
</div>
<div>
<label for=“location”>Location:</label>
<input type=“text” id=“location” name=“location” value=“<%= musician.location %>”>
</div>
<div>
<label for=“bio”>Bio:</label>
<textarea id=“bio” name=“bio”><%= musician.bio %></textarea>
</div>
<div>
<label for=“soundcloud”>SoundCloud:</label>
<input type=“text” id=“soundcloud” name=“soundcloud” value=“<%= musician.soundcloud %>”>
</div>
<div>
<label for=“thumbnail”>Thumbnail:</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
</div>
<button type=“submit”>Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById(“edit-profile-modal”);
const btn = document.getElementsByTagName(“a”)[0];
const span = document.getElementsByClassName(“close”)[0];
btn.onclick = function() {
modal.style.display = “block”;
}
span.onclick = function() {
modal.style.display = “none”;
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = “none”;
}
}
</script>
</body>
</html>
Мне нужно преобразовать ссылку типа https://soundcloud.com/ty-segall-official/saturday-pt-2-live?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing в embded типа: <iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” allow=“autoplay” src=“https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/1431306373&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true”></iframe><div style=“font-size: 10px; color: #cccccc;line-break: anywhere;word-break: normal;overflow: hidden;white-space: nowrap;text-overflow: ellipsis; font-family: Interstate,Lucida Grande,Lucida Sans Unicode,Lucida Sans,Garuda,Verdana,Tahoma,sans-serif;font-weight: 100;”><a href=“https://soundcloud.com/ty-segall-official” title=“Ty Segall” target=“_blank” style=“color: #cccccc; text-decoration: none;”>Ty Segall</a> · <a href=“https://soundcloud.com/ty-segall-official/saturday-pt-2-live” title=“Saturday Pt. 2 (Live)” target=“_blank” style=“color: #cccccc; text-decoration: none;”>Saturday Pt. 2 (Live)</a></div>
чтобы пользователь мог просто вставить НОРМАЛЬНУЮ ссылку типа https://soundcloud.com/ty-segall-official/saturday-pt-2-live?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing и вставлялся плеер в profile.ejs
Учти, что API soundcloud больше не предоставляет. например, можно использовать player.js
|
fc4d7901fb2ff07962cd50a95057295f
|
{
"intermediate": 0.4536873996257782,
"beginner": 0.36664488911628723,
"expert": 0.17966769635677338
}
|
10,458
|
import { Text, View, TextInput, Pressable, ScrollView } from ‘react-native’;
import { gStyle } from ‘…/styles/style’;
import Footer from ‘…/components/Footer’;
import Header from ‘…/components/Header’;
import { firebase } from ‘…/Firebase/firebase’;
import ‘firebase/compat/auth’;
import ‘firebase/compat/database’;
import ‘firebase/compat/firestore’;
import React, {useState, useEffect} from ‘react’;
import { useNavigation } from ‘@react-navigation/native’;
import ImagePicker from ‘react-native-image-crop-picker’;
export default function FormAddMK() {
const [imageData, setImageData] = useState(null);
const chooseImage = () => {
const options = {
mediaType: ‘photo’,
quality: 0.5,
};
ImagePicker.launchImageLibrary(options, (response) => {
if (response.uri) {
setImageData(response);
}
});
};
const [text, setValue] = useState(‘’);
const [name, setName] = useState(‘’);
const [description, setDescription] = useState(‘’);
const [price, setPrice] = useState(‘’);
const [time, setTime] = useState(‘’);
const [timeOfMK, setTimeOfMK] = useState(‘’);
const [person, setPerson] = useState(‘’);
const [image, setImage] = useState(null);
const onChangeName = (text) => setName(text);
const onChangeDescription = (text) => setDescription(text);
const onChangePrice = (text) => setPrice(text);
const onChangeTime = (text) => setTime(text);
const onChangeTimeOfMK = (text) => setTimeOfMK(text);
const onChangePerson = (text) => setPerson(text);
const onChangeImage = (event) => {
const file = event.target.files[0];
setImage(file);
};
const addHandler = async () => {
const storageRef = firebase.storage().ref();
const imageRef = storageRef.child(images/${Date.now()});
const uploadTask = imageRef.putFile(imageData.uri);
uploadTask.on(
‘state_changed’,
null,
(error) => {
console.log(error);
},
async () => {
const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
firebase.database().ref(‘FutureMK’).push({
id: Date.now(),
name: name,
description: description,
price: price,
time: time,
timeOfMK: timeOfMK,
person: person,
image: downloadURL
})
})}
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.formAdd}>
<Text style={gStyle.header}>Добавить мастер-класс</Text>
<View style={gStyle.formBlock}>
<View>
<Text>Название мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeName}
/>
</View>
<View>
<Text>Дата мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeTime}
/>
</View>
<View>
<Text>Описание мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeDescription}
/>
</View>
<View>
<Text>Изображение</Text>
{imageData ? (
<Image source={{ uri: imageData.uri }} style={gStyle.imagePreview} />
) : null}
<Pressable onPress={chooseImage}>
<Text>Выбрать изображение</Text>
</Pressable>
</View>
<View>
<Text>Стоимость мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangePrice}
/>
</View>
<View>
<Text>Кол-во людей на бронирование</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangePerson}
/>
</View>
<View>
<Text>Продолжительность мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeTimeOfMK}
/>
</View>
<Pressable style={gStyle.btnAddMK} onPress={()=>addHandler(text)}>
<Text style={gStyle.btnAddMKtxt}>Сохранить</Text>
</Pressable>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
like this?
|
0f3c06f2e107d15132a90cc35bc40766
|
{
"intermediate": 0.4025595486164093,
"beginner": 0.44877374172210693,
"expert": 0.14866673946380615
}
|
10,459
|
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”);
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query });
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src=”/img/<%= musician.thumbnail %>" alt=“<%= musician.name %>”>
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” src=“<%= musician.soundcloud %>”></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href=“/profile/<%= musician.id %>/edit”>Edit profile</a>
<!-- Check if the user is logged in and is the owner of the profile -->
<div id=“edit-profile-modal” class=“modal”>
<div class=“modal-content”>
<span class=“close”>×</span>
<h2>Edit Profile</h2>
<form action=“/profile/<%= musician.id %>/edit” method=“POST” enctype=“multipart/form-data”>
<div>
<label for=“name”>Name:</label>
<input type=“text” id=“name” name=“name” value=“<%= musician.name %>”>
</div>
<div>
<label for=“genre”>Genre:</label>
<input type=“text” id=“genre” name=“genre” value=“<%= musician.genre %>”>
</div>
<div>
<label for=“instrument”>Instrument:</label>
<input type=“text” id=“instrument” name=“instrument” value=“<%= musician.instrument %>”>
</div>
<div>
<label for=“location”>Location:</label>
<input type=“text” id=“location” name=“location” value=“<%= musician.location %>”>
</div>
<div>
<label for=“bio”>Bio:</label>
<textarea id=“bio” name=“bio”><%= musician.bio %></textarea>
</div>
<div>
<label for=“soundcloud”>SoundCloud:</label>
<input type=“text” id=“soundcloud” name=“soundcloud” value=“<%= musician.soundcloud %>”>
</div>
<div>
<label for=“thumbnail”>Thumbnail:</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
</div>
<button type=“submit”>Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById(“edit-profile-modal”);
const btn = document.getElementsByTagName(“a”)[0];
const span = document.getElementsByClassName(“close”)[0];
btn.onclick = function() {
modal.style.display = “block”;
}
span.onclick = function() {
modal.style.display = “none”;
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = “none”;
}
}
</script>
</body>
</html>
Мне нужно преобразовать ссылку типа https://soundcloud.com/ty-segall-official/saturday-pt-2-live?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing в embded типа: <iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” allow=“autoplay” src=“https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/1431306373&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true”></iframe><div style=“font-size: 10px; color: #cccccc;line-break: anywhere;word-break: normal;overflow: hidden;white-space: nowrap;text-overflow: ellipsis; font-family: Interstate,Lucida Grande,Lucida Sans Unicode,Lucida Sans,Garuda,Verdana,Tahoma,sans-serif;font-weight: 100;”><a href=“https://soundcloud.com/ty-segall-official” title=“Ty Segall” target=“_blank” style=“color: #cccccc; text-decoration: none;”>Ty Segall</a> · <a href=“https://soundcloud.com/ty-segall-official/saturday-pt-2-live” title=“Saturday Pt. 2 (Live)” target=“_blank” style=“color: #cccccc; text-decoration: none;”>Saturday Pt. 2 (Live)</a></div>
чтобы пользователь мог просто вставить НОРМАЛЬНУЮ ссылку типа https://soundcloud.com/ty-segall-official/saturday-pt-2-live?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing и вставлялся плеер в profile.ejs
Учти, что API soundcloud больше не предоставляет. например, можно использовать player.js
|
a07ac9ebd50544717c6ff7b99b01eb3a
|
{
"intermediate": 0.4536873996257782,
"beginner": 0.36664488911628723,
"expert": 0.17966769635677338
}
|
10,460
|
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”);
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query });
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src=”/img/<%= musician.thumbnail %>" alt=“<%= musician.name %>”>
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” src=“<%= musician.soundcloud %>”></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href=“/profile/<%= musician.id %>/edit”>Edit profile</a>
<!-- Check if the user is logged in and is the owner of the profile -->
<div id=“edit-profile-modal” class=“modal”>
<div class=“modal-content”>
<span class=“close”>×</span>
<h2>Edit Profile</h2>
<form action=“/profile/<%= musician.id %>/edit” method=“POST” enctype=“multipart/form-data”>
<div>
<label for=“name”>Name:</label>
<input type=“text” id=“name” name=“name” value=“<%= musician.name %>”>
</div>
<div>
<label for=“genre”>Genre:</label>
<input type=“text” id=“genre” name=“genre” value=“<%= musician.genre %>”>
</div>
<div>
<label for=“instrument”>Instrument:</label>
<input type=“text” id=“instrument” name=“instrument” value=“<%= musician.instrument %>”>
</div>
<div>
<label for=“location”>Location:</label>
<input type=“text” id=“location” name=“location” value=“<%= musician.location %>”>
</div>
<div>
<label for=“bio”>Bio:</label>
<textarea id=“bio” name=“bio”><%= musician.bio %></textarea>
</div>
<div>
<label for=“soundcloud”>SoundCloud:</label>
<input type=“text” id=“soundcloud” name=“soundcloud” value=“<%= musician.soundcloud %>”>
</div>
<div>
<label for=“thumbnail”>Thumbnail:</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
</div>
<button type=“submit”>Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById(“edit-profile-modal”);
const btn = document.getElementsByTagName(“a”)[0];
const span = document.getElementsByClassName(“close”)[0];
btn.onclick = function() {
modal.style.display = “block”;
}
span.onclick = function() {
modal.style.display = “none”;
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = “none”;
}
}
</script>
</body>
</html>
Мне нужно преобразовать ссылку типа https://soundcloud.com/ty-segall-official/saturday-pt-2-live?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing в embded типа: <iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” allow=“autoplay” src=“https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/1431306373&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true”></iframe><div style=“font-size: 10px; color: #cccccc;line-break: anywhere;word-break: normal;overflow: hidden;white-space: nowrap;text-overflow: ellipsis; font-family: Interstate,Lucida Grande,Lucida Sans Unicode,Lucida Sans,Garuda,Verdana,Tahoma,sans-serif;font-weight: 100;”><a href=“https://soundcloud.com/ty-segall-official” title=“Ty Segall” target=“_blank” style=“color: #cccccc; text-decoration: none;”>Ty Segall</a> · <a href=“https://soundcloud.com/ty-segall-official/saturday-pt-2-live” title=“Saturday Pt. 2 (Live)” target=“_blank” style=“color: #cccccc; text-decoration: none;”>Saturday Pt. 2 (Live)</a></div>
чтобы пользователь мог просто вставить НОРМАЛЬНУЮ ссылку типа https://soundcloud.com/ty-segall-official/saturday-pt-2-live?utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing и вставлялся плеер в profile.ejs
Учти, что API soundcloud больше не предоставляет, поэтому api ключ получить не получится. например, можно использовать player.js
|
071b5007bd10a1d471b9afa264c02921
|
{
"intermediate": 0.4536873996257782,
"beginner": 0.36664488911628723,
"expert": 0.17966769635677338
}
|
10,461
|
aws kafkaconnect update-connector
|
a6e6d1cb2bc8020ff47b5448659a1c50
|
{
"intermediate": 0.41362500190734863,
"beginner": 0.1714063286781311,
"expert": 0.41496866941452026
}
|
10,462
|
import { Text, View, TextInput, Pressable, ScrollView } from 'react-native';
import { gStyle } from '../styles/style';
import Footer from '../components/Footer';
import Header from '../components/Header';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState, useEffect} from 'react';
import { useNavigation } from '@react-navigation/native';
import ImagePicker from 'expo-image-picker';
export default function FormAddMK() {
const [imageData, setImageData] = useState(null);
const chooseImage = () => {
const options = {
mediaType: 'photo',
quality: 0.5,
};
ImagePicker.launchImageLibrary(options, (response) => {
if (response.uri) {
setImageData(response);
}
});
};
const [text, setValue] = useState('');
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [price, setPrice] = useState('');
const [time, setTime] = useState('');
const [timeOfMK, setTimeOfMK] = useState('');
const [person, setPerson] = useState('');
const [image, setImage] = useState(null);
const onChangeName = (text) => setName(text);
const onChangeDescription = (text) => setDescription(text);
const onChangePrice = (text) => setPrice(text);
const onChangeTime = (text) => setTime(text);
const onChangeTimeOfMK = (text) => setTimeOfMK(text);
const onChangePerson = (text) => setPerson(text);
const onChangeImage = (event) => {
const file = event.target.files[0];
setImage(file);
};
const addHandler = async () => {
const storageRef = firebase.storage().ref();
const imageRef = storageRef.child(`images/${Date.now()}`);
const uploadTask = imageRef.putFile(imageData.uri);
uploadTask.on(
'state_changed',
null,
(error) => {
console.log(error);
},
async () => {
const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
firebase.database().ref('FutureMK').push({
id: Date.now(),
name: name,
description: description,
price: price,
time: time,
timeOfMK: timeOfMK,
person: person,
image: downloadURL
})
})}
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.formAdd}>
<Text style={gStyle.header}>Добавить мастер-класс</Text>
<View style={gStyle.formBlock}>
<View>
<Text>Название мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeName}
/>
</View>
<View>
<Text>Дата мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeTime}
/>
</View>
<View>
<Text>Описание мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeDescription}
/>
</View>
<View>
<Text>Изображение</Text>
{imageData ? (
<Image source={{ uri: imageData.uri }} style={gStyle.imagePreview} />
) : null}
<Pressable onPress={chooseImage}>
<Text>Выбрать изображение</Text>
</Pressable>
</View>
<View>
<Text>Стоимость мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangePrice}
/>
</View>
<View>
<Text>Кол-во людей на бронирование</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangePerson}
/>
</View>
<View>
<Text>Продолжительность мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeTimeOfMK}
/>
</View>
<Pressable style={gStyle.btnAddMK} onPress={()=>addHandler(text)}>
<Text style={gStyle.btnAddMKtxt}>Сохранить</Text>
</Pressable>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
i got en err TypeError: Cannot read property 'launchImageLibrary' of undefined, js engine: hermes
|
684b6008485568c86ac8738a1e8b3b6f
|
{
"intermediate": 0.34267470240592957,
"beginner": 0.5273690223693848,
"expert": 0.12995624542236328
}
|
10,463
|
aws kafkaconnect update-connector --connector-arn --capacity provisionedCapacity mcuCount
|
a3213bdf43a43218f865b2bf983aae24
|
{
"intermediate": 0.4057060778141022,
"beginner": 0.24064980447292328,
"expert": 0.35364407300949097
}
|
10,464
|
docker-compose.yaml
|
3febd7d915198ed5b3d6ce4428f91f4d
|
{
"intermediate": 0.4264681041240692,
"beginner": 0.23792371153831482,
"expert": 0.3356081545352936
}
|
10,465
|
Мне нужно добавить секцию, где музыкант может добавлять несколько треков с soundcloud путем заполнения формы и нажатия кнопки "add music" в области редактирования профиля. Сейчас есть возможность добавить только одну песню к профилю. Работать должно так: добавил одну песню, дальше можно добавить другую, после чего появляется возможность добавить третью и так далее, заранее поля с песнями не должны быть показаны
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width="100%" height="300" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">SoundCloud:</label>
<input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud %>">
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
|
719b587624e94c1f50c5f3a8a7aca01e
|
{
"intermediate": 0.43395835161209106,
"beginner": 0.4390942454338074,
"expert": 0.12694740295410156
}
|
10,466
|
<div class="header__actions-card">
<div :class="{active: !isSetTable}">
<svg-icon
name="card-theme"
width="32"
height="32"
@click="setIsTable('')"
/>
</div>
<div :class="{active: isSetTable}">
<svg-icon
name="table-theme"
width="32"
height="32"
@click="setIsTable('true')"
/>
</div>
</div>
.active {
width: 46px;
height: 46px;
background: #FAFAFA;
box-shadow: inset 1px 2px 3px rgba(0, 0, 0, 0.25);
border-radius: 100px;
display: flex;
align-items: center;
justify-content: center;
.svg-icon {
circle {
stroke: $darkGray;
}
rect {
stroke: $darkGray;
}
line {
stroke: $darkGray;
}
}
}
Почему иконка не перекрашивается?
|
a42ca8570a093b8776e42080e5693000
|
{
"intermediate": 0.31391027569770813,
"beginner": 0.3770696222782135,
"expert": 0.30902013182640076
}
|
10,467
|
const configQueries = {
/**
* Config object
*/
async configs(_root, _args, { models }: IContext) {
const configs = (await models.Configs.find({})) || [];
const configsWithCodeKey = configs.reduce((acc, config) => {
acc[config.code] = config.value;
return acc;
}, {});
//init default configs for first start
const promises = Object.keys(configDefaults).map(async (configKey) => {
let doc: IConfig = { code: '', value: '' };
if (!(configKey in configsWithCodeKey)) {
doc = { code: configKey, value: configDefaults[configKey] };
return models.Configs.createOrUpdateConfig(doc);
// const newConfig = await models.Configs.createOrUpdateConfig(doc);
// configs.push(newConfig);
}
})
const newConfig = await Promise.all(promises);
configs.concat(...newConfig);
return configs;
}, typescript сообщает о том что newConfig может равняться undefined
|
95d2e13b21b0363c2040c85d49e30cde
|
{
"intermediate": 0.5277632474899292,
"beginner": 0.29062390327453613,
"expert": 0.18161284923553467
}
|
10,468
|
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width="100%" height="300" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for=“soundcloud”>SoundCloud:</label>
<div id=“music-fields”>
<% if (musician.soundcloud) { %>
<% if (Array.isArray(musician.soundcloud)) { musician.soundcloud.forEach(function(url) { %>
<div>
<input type=“text” name=“soundcloud[]” value=“<%= url %>”>
<button type=“button” class=“delete-music-button”>×</button>
</div>
<% }); %>
<% } %>
<div>
<input type=“text” name=“soundcloud[]” placeholder=“SoundCloud track URL”>
<button type=“button” class=“add-music-button”>Add Music</button>
</div>
</div>
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
const musicFields = document.getElementById(“music-fields”);
const addMusicButton = document.querySelector(“.add-music-button”);
addMusicButton.addEventListener(“click”, (event) => {
event.preventDefault();
const musicField = document.createElement(“div”);
musicField.innerHTML = <br/> <input type="text" name="soundcloud[]" placeholder="SoundCloud track URL"><br/> <button type="button" class="delete-music-button">×</button><br/> ;
musicFields.insertBefore(musicField, addMusicButton.parentNode);
});
musicFields.addEventListener(“click”, (event) => {
if (event.target.classList.contains(“delete-music-button”)) {
event.preventDefault();
event.target.parentNode.remove();
}
});
</script>
</body>
</html>
ошибка:
SyntaxError: Unexpected token 'catch' in C:\Users\Ilya\Downloads\my-musician-network\views\profile.ejs while compiling ejs
|
da390c82b8853fcf7e11392ed3734b0c
|
{
"intermediate": 0.3856944441795349,
"beginner": 0.4416373372077942,
"expert": 0.1726682335138321
}
|
10,469
|
I want to double click on cel D1 and show a message, how do I write the vba code
|
a891c9dd20b95a7ef60ae72965622aeb
|
{
"intermediate": 0.5545008778572083,
"beginner": 0.22079448401927948,
"expert": 0.2247045934200287
}
|
10,470
|
I have configured the daemon.json for docker with "bip":"10.17.2.1/24". I now want to change that configuration to the usage of "default-address-pools". Can you tell me how to map the existing configuration to the new one?
|
23782192fa8a257fd7a3f1c0abdd90c4
|
{
"intermediate": 0.38412752747535706,
"beginner": 0.3085768222808838,
"expert": 0.30729562044143677
}
|
10,471
|
I have this function:
|
066d27339f1efc174cf8756745894c0c
|
{
"intermediate": 0.3317982256412506,
"beginner": 0.3524143397808075,
"expert": 0.3157874643802643
}
|
10,472
|
import { Text, View, TextInput, Pressable, ScrollView } from 'react-native';
import { gStyle } from '../styles/style';
import Footer from '../components/Footer';
import Header from '../components/Header';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState, useEffect} from 'react';
import { useNavigation } from '@react-navigation/native';
import * as ImagePicker from 'expo-image-picker';
import Constants from 'expo-constants';
export default function FormAddMK() {
const [imageData, setImageData] = useState(null);
const chooseImage = () => {
const options = {
mediaType: 'photo',
quality: 0.5,
};
ImagePicker.launchImageLibrary(options, (response) => {
if (response.uri) {
setImageData(response);
}
});
};
if (Constants.platform.ios || Constants.platform.android) {
ImagePicker.requestMediaLibraryPermissionsAsync().then(() => {
console.log('Media permissions have been granted.');
}).catch((error) => {
console.log('Error getting media permissions:', error);
});
}
const [text, setValue] = useState('');
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [price, setPrice] = useState('');
const [time, setTime] = useState('');
const [timeOfMK, setTimeOfMK] = useState('');
const [person, setPerson] = useState('');
const [image, setImage] = useState(null);
const onChangeName = (text) => setName(text);
const onChangeDescription = (text) => setDescription(text);
const onChangePrice = (text) => setPrice(text);
const onChangeTime = (text) => setTime(text);
const onChangeTimeOfMK = (text) => setTimeOfMK(text);
const onChangePerson = (text) => setPerson(text);
const onChangeImage = (event) => {
const file = event.target.files[0];
setImage(file);
};
const addHandler = async () => {
try {
const storageRef = firebase.storage().ref();
const imageRef = storageRef.child(`images/${Date.now()}`);
const response = await fetch(imageData);
const blob = await response.blob();
const uploadTask = imageRef.putString(blob, 'data_url');
uploadTask.on(
'state_changed',
null,
(error) => {
console.log('Error uploading image:', error);
},
async () => {
const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
firebase
.database()
.ref('FutureMK')
.push({
id: Date.now(),
name: name,
description: description,
price: price,
time: time,
timeOfMK: timeOfMK,
person: person,
image: downloadURL,
});
}
);
} catch (error) {
console.log('Error adding MK:', error);
}
};
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.formAdd}>
<Text style={gStyle.header}>Добавить мастер-класс</Text>
<View style={gStyle.formBlock}>
<View>
<Text>Название мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeName}
/>
</View>
<View>
<Text>Дата мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeTime}
/>
</View>
<View>
<Text>Описание мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeDescription}
/>
</View>
<View>
<Text>Изображение</Text>
{imageData ? (
<Image source={{ uri: imageData.uri }} style={gStyle.imagePreview} />
) : null}
<Pressable onPress={chooseImage}>
<Text>Выбрать изображение</Text>
</Pressable>
</View>
<View>
<Text>Стоимость мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangePrice}
/>
</View>
<View>
<Text>Кол-во людей на бронирование</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangePerson}
/>
</View>
<View>
<Text>Продолжительность мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeTimeOfMK}
/>
</View>
<Pressable style={gStyle.btnAddMK}
onPress={addHandler}
>
<Text style={gStyle.btnAddMKtxt}>Сохранить</Text>
</Pressable>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
but i have an err TypeError: undefined is not a function, js engine: hermes
what did i do wrong?
|
c701ab1a8f708e4330276699e70b5801
|
{
"intermediate": 0.3885614275932312,
"beginner": 0.5091806054115295,
"expert": 0.1022578701376915
}
|
10,473
|
In Python, how does printing a class know to use the __str__ method?
|
464cad4b08773923154acd012d969e29
|
{
"intermediate": 0.16131727397441864,
"beginner": 0.7829475402832031,
"expert": 0.055735260248184204
}
|
10,474
|
import { Text, View, TextInput, Pressable, ScrollView, Image } from 'react-native';
import { gStyle } from '../styles/style';
import Footer from '../components/Footer';
import Header from '../components/Header';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState,} from 'react';
import * as ImagePicker from 'expo-image-picker';
export default function FormAddMK() {
const [imageData, setImageData] = useState(null);
const chooseImage = async() => {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
console.log('Permission to access media library was denied')
return; // exit the function if permission is not granted
}
const options = {
mediaType: ImagePicker.MediaTypeOptions.Images,
quality: 0.5,
};
let result = await ImagePicker.launchImageLibraryAsync(options); // use launchImageLibraryAsync
if (!result.canceled) { // check if the user selected an image
setImageData(result);
}
};
if (Platform.OS !== 'web') { // use Platform.OS instead of Constants.platform
ImagePicker.requestMediaLibraryPermissionsAsync().then(() => {
console.log('Media permissions have been granted.');
}).catch((error) => {
console.log('Error getting media permissions:', error);
});
}
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [price, setPrice] = useState('');
const [time, setTime] = useState('');
const [timeOfMK, setTimeOfMK] = useState('');
const [person, setPerson] = useState('');
const [image, setImage] = useState(null);
const onChangeName = (text) => setName(text);
const onChangeDescription = (text) => setDescription(text);
const onChangePrice = (text) => setPrice(text);
const onChangeTime = (text) => setTime(text);
const onChangeTimeOfMK = (text) => setTimeOfMK(text);
const onChangePerson = (text) => setPerson(text);
const onChangeImage = (event) => {
const file = event.target.files[0];
setImage(file);
};
const addHandler = async () => {
try {
const storageRef = firebase.storage().ref();
const imageRef = storageRef.child(`images/${Date.now()}`);
const response = await fetch(imageData.uri);
const blob = await response.blob();
const uploadTask = imageRef.put(blob);
uploadTask.on(
'state_changed',
null,
(error) => {
console.log('Error uploading image:', error);
},
async () => {
const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
firebase
.database()
.ref('FutureMK')
.push({
id: Date.now(),
name: name,
description: description,
price: price,
time: time,
timeOfMK: timeOfMK,
person: person,
image: downloadURL,
});
}
);
} catch (error) {
console.log('Error adding MK:', error);
}
};
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.formAdd}>
<Text style={gStyle.header}>Добавить мастер-класс</Text>
<View style={gStyle.formBlock}>
<View>
<Text>Название мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeName}
/>
</View>
<View>
<Text>Дата мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeTime}
/>
</View>
<View>
<Text>Описание мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeDescription}
/>
</View>
<View>
<Text>Изображение</Text>
{imageData ? (
<Image source={{ uri: imageData.uri }} style={gStyle.imagePreview} />
) : null}
<Pressable onPress={chooseImage}>
<Text>Выбрать изображение</Text>
</Pressable>
</View>
<View>
<Text>Стоимость мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangePrice}
/>
</View>
<View>
<Text>Кол-во людей на бронирование</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangePerson}
/>
</View>
<View>
<Text>Продолжительность мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeTimeOfMK}
/>
</View>
<Pressable style={gStyle.btnAddMK}
onPress={addHandler}
>
<Text style={gStyle.btnAddMKtxt}>Сохранить</Text>
</Pressable>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
it says that key uri in the image picker result is deprecated and will be removed in sdk 48, you can access selected assets through the assets array instead
|
bcce5acf7376bfbd315096a0b4008cc4
|
{
"intermediate": 0.3263646960258484,
"beginner": 0.5300642848014832,
"expert": 0.14357098937034607
}
|
10,475
|
#include <iostream>
#include <vector>
#include <iomanip>
class Gun {
public:
virtual ~Gun() {} // Virtual destructor
virtual float calculate_total_damage(int t) const = 0;
virtual std::string get_name() const = 0;
};
class Pistol : public Gun {
public:
Pistol(int number, int mag_count, float wear_ratio)
: mag_count(mag_count), wear_ratio(wear_ratio) {
if (number == 1) {
name = "G18";
mag_size = 12;
damage = 2;
rate = 1;
} else {
name = "M500";
mag_size = 5;
damage = 4;
rate = 0.5;
}
reload = 2;
}
std::string get_name() const {
return name;
}
float calculate_total_damage(int t) const {
float new_damage = wear_ratio * damage;
float new_rate = rate / (2 - wear_ratio);
return new_damage * new_rate * (mag_count * mag_size * reload);
}
private:
int mag_count, mag_size, damage;
float rate, wear_ratio, reload;
std::string name;
};
class AssaultRifle : public Gun {
public:
AssaultRifle(int number, int mag_count, float wear_ratio, float extra_damage)
: mag_count(mag_count), wear_ratio(wear_ratio), extra_damage(extra_damage) {
if (number == 3) {
name = "MP40";
mag_size = 20;
damage = 3;
rate = 5;
} else {
name = "AK";
mag_size = 30;
damage = 5;
rate = 1;
}
reload = 2;
}
std::string get_name() const {
return name;
}
float calculate_total_damage(int t) const {
float new_damage = wear_ratio * damage + extra_damage;
float new_rate = rate / (2 - wear_ratio);
return new_damage * new_rate * (mag_count * mag_size * reload);
}
private:
int mag_count, mag_size, damage;
float rate, wear_ratio, reload, extra_damage;
std::string name;
};
class SniperRifle : public Gun {
public:
SniperRifle(int number, int mag_count, float wear_ratio)
: mag_count(mag_count), wear_ratio(wear_ratio) {
if (number == 5) {
name = "SVD";
mag_size = 10;
damage = 5;
rate = 0.5;
} else {
name = "AWM";
mag_size = 5;
damage = 10;
rate = 0.5;
}
reload = 3;
}
std::string get_name() const {
return name;
}
float calculate_total_damage(int t) const {
float new_damage = wear_ratio * damage;
float new_rate = rate / (2 - wear_ratio);
float time_to_deplete_magazines = static_cast<float>(mag_count * mag_size) / new_rate;
float reload_time = reload * (mag_count - 1);
float num_full_cycles = t / (time_to_deplete_magazines + reload_time);
float leftover_time = t - num_full_cycles * (time_to_deplete_magazines + reload_time);
float total_damage = num_full_cycles * (mag_count * mag_size * new_damage);
total_damage += (leftover_time / (mag_size / new_rate)) * new_damage;
return total_damage;
}
private:
int mag_count, mag_size, damage;
float rate, wear_ratio, reload;
std::string name;
};
int main() {
int num_guns;
std::cin >> num_guns;
std::vector<Gun*> guns;
for (int i = 0; i < num_guns; i++) {
int gun_type, mag_count;
float wear_ratio, extra_damage;
std::cin >> gun_type >> mag_count >> wear_ratio;
if (gun_type == 1 || gun_type == 2) {
guns.push_back(new Pistol(gun_type, mag_count, wear_ratio));
} else if (gun_type == 3 || gun_type == 4) {
std::cin >> extra_damage;
guns.push_back(new AssaultRifle(gun_type, mag_count, wear_ratio, extra_damage));
} else {
guns.push_back(new SniperRifle(gun_type, mag_count, wear_ratio));
}
}
int t;
std::cin >> t;
for (Gun* gun : guns) {
std::cout << gun->get_name() << ": " << std::fixed << std::setprecision(1) << gun->calculate_total_damage(t) << std::endl;
delete gun;
}
return 0;
}Fix
Your code did not pass this test case.
Input (stdin)
3
1 3 0.9
3 2 0.8 2
4 1 1 2
15
Your Output (stdout)
G18: 117.8
MP40: 1466.7
AK: 420.0
Expected Output
G18: 14.4
MP40: 145.2
AK: 105
Compiler Message
Wrong Answer
|
e517f6b06087e657d2d8312451f40322
|
{
"intermediate": 0.2717103362083435,
"beginner": 0.4518352746963501,
"expert": 0.2764543890953064
}
|
10,476
|
Este es mi Dockerfile:
# Establece la imagen base de ubuntu
FROM ubuntu:latest
# Actualiza los paquetes e instala las herramientas básicas
RUN apt-get clean update && DEBIAN_FRONTEND=noninteractive apt-get clean install -y build-essential curl git vim wget php-cli curl
# Configura la zona horaria a Madrid (Europe/Madrid)
RUN ln -snf /usr/share/zoneinfo/TZ /etc/localtime && echo TZ > /etc/timezone
# Instala PHP, tzdata, y las extensiones necesarias para Laravel
RUN DEBIAN_FRONTEND=noninteractive apt-get clean install -y php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
# Instala Composer (gestor de paquetes de PHP)
RUN curl -sS -o composer-setup.php https://getcomposer.org/installer && php composer-setup.php --install-dir=/usr/local/bin --filename=composer && rm composer-setup.php
# Instala Node.js, NPM, Yarn, Angular CLI, Gulp, Bootstrap y Webpack
RUN curl -sL https://deb.nodesource.com/setup_14.x | bash && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && echo “deb https://dl.yarnpkg.com/debian/ stable main” | tee /etc/apt/sources.list.d/yarn.list && apt-get clean update && apt-get clean install -y nodejs yarn && npm install -g @angular/cli gulp webpack webpack-cli bootstrap
# Instala Python y pip
RUN apt-get clean install -y python3 python3-pip
# Instala XAMPP
RUN wget -q https://www.apachefriends.org/xampp-files/8.0.10/xampp-linux-x64-8.0.10-0-installer.run -O xampp-installer.run && chmod +x xampp-installer.run && ./xampp-installer.run --mode unattended && rm xampp-installer.run
ENV PATH /opt/lampp/bin:PATH
# Instala Visual Studio Code y Visual Studio Codium
RUN wget -q https://packages.microsoft.com/keys/microsoft.asc -O- | apt-key add - && \
echo "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list && \
apt-get clean update && \
apt-get clean install -y \
code \
codium
# Instala PyCharm
RUN wget -q https://download.jetbrains.com/python/pycharm-community-2021.2.2.tar.gz -O pycharm.tar.gz && \
tar xzvf pycharm.tar.gz -C /opt && \
rm pycharm.tar.gz
ENV PATH /opt/pycharm-community-2021.2.2/bin:PATH
# Instala Laravel en ~/laravel
RUN composer global require laravel/installer && echo “export PATH=”$PATH:$HOME/.composer/vendor/bin"" >> ~/.bashrc && . ~/.bashrc
# Instala LXDE (entorno de escritorio) y servidor VNC (TightVNC)
RUN apt-get clean update && apt-get install -y lxde && apt-get clean install -y tightvncserver
# Reemplaza Vim con NeoVim
RUN apt-get clean install -y neovim
# Instala NVChad
RUN apt-get clean install -y curl xclip xsel fzf && git clone https://github.com/NvChad/NvChad.git ~/.config/nvim && nvim +silent +PlugInstall +qall && echo “alias vim=‘nvim’” >> ~/.bashrc
# Instala Tmux
RUN apt-get clean install -y tmux
# Instala GitKraken (cliente de Git con UI)
RUN apt-get clean install -y gconf2 gconf-service libgtk2.0-0 libnotify4 libappindicator1 libxtst6 libnss3 python3 libgconf-2-4 libxkbfile1 && wget -q https://release.gitkraken.com/linux/gitkraken-amd64.deb -O gitkraken.deb && dpkg -i gitkraken.deb && apt-get clean install -f -y && rm gitkraken.deb
# Volumen compartido entre host y contenedor
# En tu máquina host, crea la carpeta donde se montará el volumen: mkdir -p D:\Docker\Ubuntu
VOLUME [“/home/host”]
# Establece el directorio de trabajo en el volumen compartido
WORKDIR /home/host
# Comando a ejecutar cuando se inicia el contenedor (inicia el servidor VNC)
CMD [“vncserver”, “:1”, “-geometry”, “1280x800”, “-localhost”, “no”]
Recibo este error:
=> ERROR [ 5/17] RUN curl -sS -o composer-setup.php https://getcomposer.org/installer && php composer-setup.php 0.3s
------
> [ 5/17] RUN curl -sS -o composer-setup.php https://getcomposer.org/installer && php composer-setup.php --install-dir=/usr/local/bin --filename=composer && rm composer-setup.php:
#0 0.320 /bin/sh: 1: curl: not found
------
Dockerfile:14
--------------------
12 |
13 | # Instala Composer (gestor de paquetes de PHP)
14 | >>> RUN curl -sS -o composer-setup.php https://getcomposer.org/installer && php composer-setup.php --install-dir=/usr/local/bin --filename=composer && rm composer-setup.php
15 |
16 | # Instala Node.js, NPM, Yarn, Angular CLI, Gulp, Bootstrap y Webpack
--------------------
ERROR: failed to solve: process "/bin/sh -c curl -sS -o composer-setup.php https://getcomposer.org/installer && php composer-setup.php --install-dir=/usr/local/bin --filename=composer && rm composer-setup.php" did not complete successfully: exit code: 127
|
87bd336699edabd7a1563be7f45cb7f9
|
{
"intermediate": 0.33992326259613037,
"beginner": 0.5162555575370789,
"expert": 0.1438211351633072
}
|
10,477
|
c# ArrayList 分组
|
93f0110ad5f821a2bab3d31303225060
|
{
"intermediate": 0.379006952047348,
"beginner": 0.38227784633636475,
"expert": 0.23871520161628723
}
|
10,478
|
При добавлении ссылки с soundcloud в профиле возникает ошибка: You have not provided a valid SoundCloud URL. Learn more about using SoundCloud players.
ссылка такого типа: https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=eeb0108b59c14736ad1f38f2383ffb95&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width="100%" height="300" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">SoundCloud:</label>
<div id="music-fields">
<% if (musician.soundcloud) { %>
<% if (Array.isArray(musician.soundcloud)) { musician.soundcloud.forEach(function(url) { %>
<div>
<input type="text" name="soundcloud[]" value="<%= url %>">
<button type="button" class="delete-music-button">×</button>
</div>
<% }); %> <!-- Add this closing tag -->
<% } %>
<% } %>
<div>
<input type="text" name="soundcloud[]" placeholder="SoundCloud track URL">
<button type="button" class="add-music-button">Add Music</button>
</div>
</div>
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
const musicFields = document.getElementById("music-fields");
const addMusicButton = document.querySelector(".add-music-button");
addMusicButton.addEventListener("click", (event) => {
event.preventDefault();
const musicField = document.createElement("div");
musicField.innerHTML = '<br/> <input type="text" name="soundcloud[]" placeholder="SoundCloud track URL"><br/> <button type="button" class="delete-music-button">×</button><br/>';
musicFields.insertBefore(musicField, addMusicButton.parentNode);
});
musicFields.addEventListener("click", (event) => {
if (event.target.classList.contains("delete-music-button")) {
event.preventDefault();
event.target.parentNode.remove();
}
});
</script>
</body>
</html>
|
d07cadb944d420a3675d27c7eea20c59
|
{
"intermediate": 0.4213133752346039,
"beginner": 0.4151209592819214,
"expert": 0.16356568038463593
}
|
10,479
|
How can I login into Slack workspace on the web using Cypress
|
6aba02d5225ec7f48a6fc15ef59e566d
|
{
"intermediate": 0.5638311505317688,
"beginner": 0.15798699855804443,
"expert": 0.27818185091018677
}
|
10,480
|
При добавлении ссылки с soundcloud в профиле возникает ошибка: You have not provided a valid SoundCloud URL. Learn more about using SoundCloud players (это сообщение в самом плеере SoundCloud).
ссылка такого типа: https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=eeb0108b59c14736ad1f38f2383ffb95&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”);
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query });
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src=”/img/<%= musician.thumbnail %>" alt=“<%= musician.name %>”>
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width=“100%” height=“300” scrolling=“no” frameborder=“no” src=“https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true”></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href=“/profile/<%= musician.id %>/edit”>Edit profile</a>
<div id=“edit-profile-modal” class=“modal”>
<div class=“modal-content”>
<span class=“close”>×</span>
<h2>Edit Profile</h2>
<form action=“/profile/<%= musician.id %>/edit” method=“POST” enctype=“multipart/form-data”>
<div>
<label for=“name”>Name:</label>
<input type=“text” id=“name” name=“name” value=“<%= musician.name %>”>
</div>
<div>
<label for=“genre”>Genre:</label>
<input type=“text” id=“genre” name=“genre” value=“<%= musician.genre %>”>
</div>
<div>
<label for=“instrument”>Instrument:</label>
<input type=“text” id=“instrument” name=“instrument” value=“<%= musician.instrument %>”>
</div>
<div>
<label for=“location”>Location:</label>
<input type=“text” id=“location” name=“location” value=“<%= musician.location %>”>
</div>
<div>
<label for=“bio”>Bio:</label>
<textarea id=“bio” name=“bio”><%= musician.bio %></textarea>
</div>
<div>
<label for=“soundcloud”>SoundCloud:</label>
<div id=“music-fields”>
<% if (musician.soundcloud) { %>
<% if (Array.isArray(musician.soundcloud)) { musician.soundcloud.forEach(function(url) { %>
<div>
<input type=“text” name=“soundcloud[]” value=“<%= url %>”>
<button type=“button” class=“delete-music-button”>×</button>
</div>
<% }); %> <!-- Add this closing tag -->
<% } %>
<% } %>
<div>
<input type=“text” name=“soundcloud[]” placeholder=“SoundCloud track URL”>
<button type=“button” class=“add-music-button”>Add Music</button>
</div>
</div>
</div>
<div>
<label for=“thumbnail”>Thumbnail:</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
</div>
<button type=“submit”>Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById(“edit-profile-modal”);
const btn = document.getElementsByTagName(“a”)[0];
const span = document.getElementsByClassName(“close”)[0];
btn.onclick = function() {
modal.style.display = “block”;
}
span.onclick = function() {
modal.style.display = “none”;
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = “none”;
}
}
const musicFields = document.getElementById(“music-fields”);
const addMusicButton = document.querySelector(“.add-music-button”);
addMusicButton.addEventListener(“click”, (event) => {
event.preventDefault();
const musicField = document.createElement(“div”);
musicField.innerHTML = ‘<br/> <input type=“text” name=“soundcloud[]” placeholder=“SoundCloud track URL”><br/> <button type=“button” class=“delete-music-button”>×</button><br/>’;
musicFields.insertBefore(musicField, addMusicButton.parentNode);
});
musicFields.addEventListener(“click”, (event) => {
if (event.target.classList.contains(“delete-music-button”)) {
event.preventDefault();
event.target.parentNode.remove();
}
});
</script>
</body>
</html>
|
5b703bac965b93244e27b360b67a6bc7
|
{
"intermediate": 0.434321790933609,
"beginner": 0.4089941680431366,
"expert": 0.1566840559244156
}
|
10,481
|
how to add, substract, multiplication, divison two arrays in javascript?
|
f20b007e8768843fc40ab9fbe5c84f81
|
{
"intermediate": 0.4603179097175598,
"beginner": 0.18553084135055542,
"expert": 0.35415127873420715
}
|
10,482
|
import requests
API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
TOKEN_CONTRACT = '0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e'
def get_transaction_list(api_key, contract_address, start_block=28269140, end_block=29812249, page=1, offset=150):
url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={contract_address}&startblock={start_block}&endblock={end_block}&page={page}&offset={offset}&apikey={api_key}'
response = requests.get(url)
if response.status_code == 200:
result = response.json()
return result['result']
else:
return None
def get_all_transaction_hashes(api_key, contract_address):
all_hashes = []
page = 1
while True:
transactions = get_transaction_list(api_key, contract_address, page=page)
if transactions:
hashes = [tx['hash'] for tx in transactions]
all_hashes.extend(hashes)
if len(transactions) < 100:
break
page += 1
else:
print('Error getting transactions')
break
return all_hashes
all_transaction_hashes = get_all_transaction_hashes(API_KEY, TOKEN_CONTRACT)
for txn_hash in all_transaction_hashes:
print(txn_hash)
Modify the above code to display only hashes of transactions whose decoded item in method id is 0xf305d719
|
de43c6ded44857849f5159bfbcbdc692
|
{
"intermediate": 0.4374791979789734,
"beginner": 0.3589654862880707,
"expert": 0.20355534553527832
}
|
10,483
|
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.
Here is a portion of the code:
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
Camera.h:
#pragma once
#include <glm/glm.hpp>
class Camera
{
public:
Camera();
~Camera();
void Initialize(float aspectRatio);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
const glm::mat4& GetViewMatrix() const;
const glm::mat4& GetProjectionMatrix() const;
private:
glm::vec3 position;
glm::vec3 rotation;
glm::mat4 viewMatrix;
glm::mat4 projectionMatrix;
void UpdateViewMatrix();
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Initialize2(Renderer& renderer);
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
VkDeviceMemory mvpBufferMemory;
VkBuffer mvpBuffer;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Pipeline.h:
#pragma once
#include <vulkan/vulkan.h>
#include <vector>
#include <array>
#include <stdexcept>
#include "Shader.h"
class Pipeline
{
public:
Pipeline();
~Pipeline();
void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions,
const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions,
VkExtent2D swapchainExtent,
const std::vector<Shader*>& shaders,
VkRenderPass renderPass,
VkPipelineLayout pipelineLayout,
VkDevice device);
void Cleanup();
VkPipeline GetPipeline() const;
bool IsInitialized() const;
private:
VkDevice device;
VkPipeline pipeline;
bool initialized;
void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages);
};
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);
};
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Shader.h:
#pragma once
#include <vulkan/vulkan.h>
#include <string>
class Shader
{
public:
Shader();
~Shader();
void LoadFromFile(const std::string& filename, VkDevice device, VkShaderStageFlagBits stage);
VkPipelineShaderStageCreateInfo GetPipelineShaderStageCreateInfo() const;
static void Cleanup(Shader* shader);
private:
VkDevice device;
VkShaderModule shaderModule;
VkShaderStageFlagBits stage;
};
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
void Cleanup();
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Window.h:
#pragma once
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
class Window
{
public:
Window(int width = 800, int height = 600, const char* title = "Game Engine");
~Window();
void Initialize();
void PollEvents();
void Shutdown();
bool ShouldClose() const;
GLFWwindow* GetWindow() const;
float GetDeltaTime();
private:
static void FramebufferResizeCallback(GLFWwindow* window, int width, int height);
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
int width;
int height;
const char* title;
GLFWwindow* window;
double lastFrameTime;
};
Texture.cpp:
#include "Texture.h"
#include "BufferUtils.h"
#include <iostream>
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
Cleanup();
}
void Texture::LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->physicalDevice = physicalDevice;
this->commandPool = commandPool;
this->graphicsQueue = graphicsQueue;
this->initialized = true;
// Load image from file using stb_image
int width, height, channels;
stbi_uc* pixels = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if (!pixels)
{
throw std::runtime_error("Failed to load texture image!");
}
// Calculate the number of mip levels
uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
// Create a buffer to store the image data
VkDeviceSize imageSize = width * height * 4;
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
// Create the staging buffer for transferring image data
BufferUtils::CreateBuffer(device, physicalDevice, imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory);
// Copy image data to the buffer
void* bufferData;
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &bufferData);
memcpy(bufferData, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(device, stagingBufferMemory);
// Free the stb_image buffer
stbi_image_free(pixels);
// Create vkImage, copy buffer to image, and create imageView and sampler
// …
CreateImage(width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
CreateImageView(VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels);
CreateSampler(mipLevels);
TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels, VK_SAMPLE_COUNT_1_BIT); // Add this call
CopyBufferToImage(stagingBuffer, width, height);
// Cleanup the staging buffer and staging buffer memory
// …
// Destroy the staging buffer and free the staging buffer memory
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
void Texture::Cleanup()
{
if (!initialized) {
return;
}
if (sampler != VK_NULL_HANDLE) {
vkDestroySampler(device, sampler, nullptr);
sampler = VK_NULL_HANDLE;
}
if (imageView != VK_NULL_HANDLE) {
vkDestroyImageView(device, imageView, nullptr);
imageView = VK_NULL_HANDLE;
}
if (image != VK_NULL_HANDLE) {
vkDestroyImage(device, image, nullptr);
image = VK_NULL_HANDLE;
}
if (imageMemory != VK_NULL_HANDLE) {
vkFreeMemory(device, imageMemory, nullptr);
imageMemory = VK_NULL_HANDLE;
}
initialized = false;
}
VkImageView Texture::GetImageView() const
{
return imageView;
}
VkSampler Texture::GetSampler() const
{
return sampler;
}
void Texture::CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties)
{
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = numSamples;
imageInfo.flags = 0;
if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create image!");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate image memory!");
}
vkBindImageMemory(device, image, imageMemory, 0);
}
void Texture::TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkImageMemoryBarrier barrier{};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.oldLayout = oldLayout;
barrier.newLayout = newLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = mipLevels;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
VkPipelineStageFlags sourceStage;
VkPipelineStageFlags destinationStage;
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
barrier.srcAccessMask = 0;
barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
sourceStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
destinationStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
sourceStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
destinationStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
else {
throw std::invalid_argument("Unsupported layout transition!");
}
vkCmdPipelineBarrier(
commandBuffer,
sourceStage, destinationStage,
0,
0, nullptr,
0, nullptr,
1, &barrier
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
void Texture::CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels)
{
VkImageViewCreateInfo viewInfo{};
viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
viewInfo.image = image;
viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
viewInfo.format = format;
viewInfo.subresourceRange.aspectMask = aspectFlags;
viewInfo.subresourceRange.baseMipLevel = 0;
viewInfo.subresourceRange.levelCount = mipLevels;
viewInfo.subresourceRange.baseArrayLayer = 0;
viewInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture image view!");
}
}
void Texture::CreateSampler(uint32_t mipLevels)
{
VkSamplerCreateInfo samplerInfo{};
samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
samplerInfo.magFilter = VK_FILTER_LINEAR;
samplerInfo.minFilter = VK_FILTER_LINEAR;
samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
samplerInfo.anisotropyEnable = VK_TRUE;
samplerInfo.maxAnisotropy = 16;
samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerInfo.unnormalizedCoordinates = VK_FALSE;
samplerInfo.compareEnable = VK_FALSE;
samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
samplerInfo.mipLodBias = 0.0f;
samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = static_cast<float>(mipLevels);
if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create texture sampler!");
}
}
void Texture::CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height)
{
// Create a one-time-use command buffer
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// Record buffer to image copy command in the command buffer
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferImageCopy region{};
region.bufferOffset = 0;
region.bufferRowLength = 0;
region.bufferImageHeight = 0;
region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
region.imageSubresource.mipLevel = 0;
region.imageSubresource.baseArrayLayer = 0;
region.imageSubresource.layerCount = 1;
region.imageOffset = { 0, 0, 0 };
region.imageExtent = {
width,
height,
1
};
vkCmdCopyBufferToImage(
commandBuffer,
buffer,
image,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1,
®ion
);
// End command buffer recording
vkEndCommandBuffer(commandBuffer);
// Submit command buffer
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
// Free command buffer
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
Can you rewrite the Texture class to work more optimally?
|
e3918d5af212c37fdc945b63a65e6657
|
{
"intermediate": 0.4166281521320343,
"beginner": 0.35532474517822266,
"expert": 0.22804704308509827
}
|
10,484
|
I want to make a 3D plot of four variables form DataFrame k in Julia. constraint1 constraint2 constraint3 are parameters (axis) for global_best_value.
|
30effc8632027b90c841d1cd641ff1a6
|
{
"intermediate": 0.3684386610984802,
"beginner": 0.2993277609348297,
"expert": 0.33223363757133484
}
|
10,485
|
Сохраняется только одна песня в профиле музыканта. Вот код:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = [req.body.soundcloud];
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width="100%" height="300" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">SoundCloud:</label>
<div id="music-fields">
<% if (musician.soundcloud) { %>
<% if (Array.isArray(musician.soundcloud)) { musician.soundcloud.forEach(function(url) { %>
<div>
<input type="text" name="soundcloud[]" value="<%= url %>">
<button type="button" class="delete-music-button">×</button>
</div>
<% }); %> <!-- Add this closing tag -->
<% } %>
<% } %>
<div>
<input type="text" name="soundcloud" value="<%= musician.soundcloud %>" placeholder="Soundcloud track URL">
<button type="button" class="add-music-button">Add Music</button>
</div>
</div>
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
const musicFields = document.getElementById("music-fields");
const addMusicButton = document.querySelector(".add-music-button");
addMusicButton.addEventListener("click", (event) => {
event.preventDefault();
const musicField = document.createElement("div");
musicField.innerHTML = '<br/> <input type="text" name="soundcloud[]" placeholder="SoundCloud track URL"><br/> <button type="button" class="delete-music-button">×</button><br/>';
musicFields.insertBefore(musicField, addMusicButton.parentNode);
});
musicFields.addEventListener("click", (event) => {
if (event.target.classList.contains("delete-music-button")) {
event.preventDefault();
event.target.parentNode.remove();
}
});
</script>
</body>
</html>
musicians.json:
{"musicians":[{"id":1,"name":"sukaAAAAAAA","genre":"BluesZ","instrument":"Guitar","soundcloud":"http://soundcloud.com/dasdasdasd","password":"password123","location":"New York","login":"suka","bio":""},{"id":2,"name":"Aerosmith111114446","genre":"Blues","password":"1111","location":"EnglandDdD","thumbnail":"musician_2_jX7hQvfoT2g (2).jpg","instrument":"","bio":"","soundcloud":["https://soundcloud.com/ty-segall-official/every-1s-a-winner?si=dcd35e9230b7403d93a24b9ccb287739&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing"]},{"id":3,"name":"Britpop","genre":"Pop","instrument":"bass","soundcloud":"http://google.com","password":"1111","location":"Sahara","login":"SS1VCSS@gmail.com","thumbnail":"musician_3_photo_2023-02-27_01-16-44.jpg"},{"id":4,"name":"Bobq","genre":"Hip hop","instrument":"keys","soundcloud":"http://cloudnine.ru","password":"1111","location":"Dallas","login":"SSSS1VYTFFSDDD@gmail.com","thumbnail":"musician_4_1mxwr7Ravu4.jpg"}]}
|
4d9f0f5f969c09d1de4606557937a79d
|
{
"intermediate": 0.35865283012390137,
"beginner": 0.4775499403476715,
"expert": 0.16379724442958832
}
|
10,486
|
it says
possible unhandled promise rejection (id:1):
typeerror: undefined is not a function
there is my firebase rules
{
"rules": {
"users":{
"$uid":{
".read":
"$uid===auth.uid",
".write":
"$uid===auth.uid"
}
}
}
}
its my js file
import { Text, View, TextInput, Pressable, ScrollView, Image } from 'react-native';
import { gStyle } from '../styles/style';
import Footer from '../components/Footer';
import Header from '../components/Header';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState,} from 'react';
import * as ImagePicker from 'expo-image-picker';
export default function FormAddMK() {
const [imageData, setImageData] = useState(null);
const chooseImage = async() => {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
console.log('Permission to access media library was denied')
return; // exit the function if permission is not granted
}
const options = {
mediaType: ImagePicker.MediaTypeOptions.Images,
quality: 0.5,
};
let result = await ImagePicker.launchImageLibraryAsync(options); // use launchImageLibraryAsync
if (!result.canceled) { // check if the user selected an image
const imageAssetPath = await ImagePicker.getAssetPathAsync(result.assets[0].uri);
setImageData({...result, uri: imageAssetPath});
}
};
if (Platform.OS !== 'web') { // use Platform.OS instead of Constants.platform
ImagePicker.requestMediaLibraryPermissionsAsync().then(() => {
console.log('Media permissions have been granted.');
}).catch((error) => {
console.log('Error getting media permissions:', error);
});
}
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [price, setPrice] = useState('');
const [time, setTime] = useState('');
const [timeOfMK, setTimeOfMK] = useState('');
const [person, setPerson] = useState('');
const [image, setImage] = useState(null);
const onChangeName = (text) => setName(text);
const onChangeDescription = (text) => setDescription(text);
const onChangePrice = (text) => setPrice(text);
const onChangeTime = (text) => setTime(text);
const onChangeTimeOfMK = (text) => setTimeOfMK(text);
const onChangePerson = (text) => setPerson(text);
const onChangeImage = (event) => {
const file = event.target.files[0];
setImage(file);
};
const addHandler = async () => {
try {
const storageRef = firebase.storage().ref();
const imageRef = storageRef.child('images').child(Date.now().toString());
const response = await fetch(imageData.uri);
const blob = await response.blob();
const uploadTask = imageRef.put(blob);
uploadTask.on(
'state_changed',
null,
(error) => {
console.log('Error uploading image:', error);
},
async () => {
const downloadURL = await uploadTask.snapshot.ref.getDownloadURL();
firebase
.database()
.ref('FutureMK')
.push({
id: Date.now(),
name: name,
description: description,
price: price,
time: time,
timeOfMK: timeOfMK,
person: person,
image: downloadURL,
});
}
);
} catch (error) {
console.log('Error adding MK:', error);
}
};
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.formAdd}>
<Text style={gStyle.header}>Добавить мастер-класс</Text>
<View style={gStyle.formBlock}>
<View>
<Text>Название мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeName}
/>
</View>
<View>
<Text>Дата мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeTime}
/>
</View>
<View>
<Text>Описание мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeDescription}
/>
</View>
<View>
<Text>Изображение</Text>
{imageData ? (
<Image source={{ uri: imageData.uri }} style={gStyle.imagePreview} />
) : null}
<Pressable onPress={chooseImage}>
<Text>Выбрать изображение</Text>
</Pressable>
</View>
<View>
<Text>Стоимость мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangePrice}
/>
</View>
<View>
<Text>Кол-во людей на бронирование</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangePerson}
/>
</View>
<View>
<Text>Продолжительность мастер-класса</Text>
<TextInput style={gStyle.inputForm} onChangeText={onChangeTimeOfMK}
/>
</View>
<Pressable style={gStyle.btnAddMK}
onPress={addHandler}
>
<Text style={gStyle.btnAddMKtxt}>Сохранить</Text>
</Pressable>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
|
ac5f10feb66ee28fc29ae4f9e793b2a1
|
{
"intermediate": 0.3744572401046753,
"beginner": 0.3989834189414978,
"expert": 0.2265593409538269
}
|
10,487
|
Write a step by step, detailed and specific guide on how I would self host a Coming Soon page with a modern, slick design on my own Linux device. I want to use the domain 'leo.kritica.xyz', and I want to use Cloudflare for performance, protection and general DNS. Include full code. By following the guide I should have a complete version of what I asked for.
|
b5890a35eae61a7f1db08863e5a7f987
|
{
"intermediate": 0.3214636445045471,
"beginner": 0.3347494900226593,
"expert": 0.3437868654727936
}
|
10,488
|
I need to create an Excel macro (VBA code) that all .csv files in a folder and writes all content in the same excel worksheet
|
878b4acdc55a913f2adbe1f659f3040a
|
{
"intermediate": 0.4618223011493683,
"beginner": 0.2633185386657715,
"expert": 0.27485916018486023
}
|
10,489
|
Hi i need to add some css syntax editor from npm to use in textarea in my react project
|
9960d355e8a4e708cd1dbe9a97f455ec
|
{
"intermediate": 0.3660762310028076,
"beginner": 0.45827537775039673,
"expert": 0.17564834654331207
}
|
10,490
|
async importQuotation(req: Request, res: Response, next: NextFunction) {
try {
console.log("Importing quotations...");
const body: ImportCleanQuotations = req.body;
const regionCode = getRegionCode(req.user!, req.query);
console.log("User", req.user!);
console.log("RegionCode: ", regionCode);
if (!regionCode) {
console.log("Region code is required for this operation");
return res
.status(httpStatusCodes.BAD_REQUEST)
.json(
new ResponseJSON(
"Region code is required for this operation",
true,
httpStatusCodes.BAD_REQUEST
)
);
}
const items = await Promise.all(
body.quotations.map((quotation) =>
prisma.item
.findUnique({
where: {
code: quotation.itemCode,
},
select: {
UoMCode: true,
SmUCode: true,
},
})
// .filter((item) => item)
.catch(() => {
throw new Error(`Item '${quotation.itemCode}' not found`);
})
)
);
// ); //filter out null items
console.log("Items: ", items);
const createMany = await prisma.$transaction(async (tx) => {
const quotations = await Promise.all(
body.quotations.map((quotation, index) => {
if (!quotation.itemCode || !items[index]) return null; //skip if item code is not found
(quotation as any).status = QuotationStatus.BRANCH_APPROVED;
(quotation as any).creationStatus =
QuotationCreationStatus.IMPORTED;
if (!quotation.collectorId) quotation.collectorId = req.user!.id;
return tx.quotation.create({
data: {
questionnaireId: quotation.questionnaireId,
collectorId: req.user!.id,
itemCode: quotation!.itemCode,
marketplaceCode: quotation.marketplaceCode!,
quotes: {
createMany: {
data: quotation.quotes!.map((quote) => ({
...quote,
shopContactName: "Imported",
shopContactPhone: "Imported",
shopLatitude: "Imputated",
shopLongitude: "Imputated",
measurementUnit: items?.[index]!?.UoMCode,
})),
},
// quotation.quotes?.map((quote) => { return {...quote,quantity: items[index]?.measurementQuantity,
// measurmentId: items[index]?.measurement,};}),
},
},
select: {
id: true,
questionnaireId: true,
itemCode: true,
quotes: true,
},
});
})
);
await Promise.all(
quotations.reduce((acc: any, quotation, index) => {
if (!quotation) return acc; //skip if quotation is not found
quotation.quotes.forEach((quote) => {
if (!quote) return; //skip if quote is not found
acc.push(
tx.interpolatedQuote.create({
data: {
quoteId: quote.id,
quotationId: quotation.id,
price: quote.price,
measurementUnit: items[index]!.SmUCode,
quantity: quote.quantity,
},
})
);
acc.push(
tx.cleanedQuote.create({
data: {
quoteId: quote.id,
quotationId: quotation.id,
price: quote.price,
measurementUnit: items[index]!.SmUCode,
quantity: quote.quantity,
questionnaireId: quotation.questionnaireId,
itemCode: quotation.itemCode,
},
})
);
});
return acc;
}, [])
// quotations.reduce((acc: any, quotation, index) => {
// if (!quotation || !quotation.quotes[index]) return acc; //skip if quotation or quote is not found
// acc.push(
// tx.interpolatedQuote.create({
// data: {
// quoteId: quotation.quotes[index].id,
// quotationId: quotation.id,
// price: quotation.quotes[index].price,
// measurementUnit: items[index]!.SmUCode,
// quantity: quotation.quotes[index].quantity,
// },
// })
// );
// acc.push(
// tx.cleanedQuote.create({
// data: {
// quoteId: quotation.quotes[index].id,
// quotationId: quotation.id,
// price: quotation.quotes[index].price,
// measurementUnit: items[index]!.SmUCode,
// quantity: quotation.quotes[index].quantity,
// questionnaireId: quotation.questionnaireId,
// itemCode: quotation.itemCode,
// },
// })
// );
// return acc;
// }, [])
);
await tx.itemRegionalMean.createMany({
data: body.geomeans.map((mean) => ({
itemCode: mean.itemCode,
variation: mean.variation,
stdev: mean.stdev,
geomean: mean.geomean,
min: mean.min,
max: mean.max,
questionnaireId: mean.questionnaireId,
regionCode,
})),
});
return quotations.filter((quotation) => !!quotation); //Filter out null/undefined quotations
});
console.log("Quotations created: ", createMany);
return res
.status(httpStatusCodes.OK)
.json(
new ResponseJSON(
"Quotations Created",
false,
httpStatusCodes.OK,
createMany
)
);
} catch (err) {
// console.log("Error message: ", );
console.log("Error --- ", err);
next(
apiErrorHandler(
err,
req,
errorMessages.INTERNAL_SERVER,
httpStatusCodes.INTERNAL_SERVER
)
);
}
} based on the above fucntion add a prisma query to update the export const questionnaireQuotationsStatus = {
PENDING: "PENDING",
INTERPOLATED: "INTERPOLATED",
CLEANED: "CLEANED",
}; status to QuestionnarieQuotationStatus.CLEANED with the following prisma schema model QuestionnaireRegionStatus {
questionnaireId Int
questionnaire Questionnaire @relation(fields: [questionnaireId], references: [id], onDelete: Cascade)
regionCode Int
region Region @relation(fields: [regionCode], references: [code])
status QuestionnaireQuotationsStatus
@@id([questionnaireId, regionCode])
} upon importing quoatations
|
6fbe153378eb60d6fabe49940d766d22
|
{
"intermediate": 0.46730905771255493,
"beginner": 0.4099898338317871,
"expert": 0.12270110845565796
}
|
10,491
|
Write a step by step, detailed and specific guide on how I would self host a Coming Soon page with a modern, slick design on my own Windows 10 device. I want to use the domain ‘leo.kritica.xyz’, and I want to use Cloudflare for performance, protection and general DNS. Include full code. By following the guide I should have a complete version of what I asked for.
|
8ff93720afc3a8a0183a1977c3bb280e
|
{
"intermediate": 0.313215047121048,
"beginner": 0.3364817500114441,
"expert": 0.35030320286750793
}
|
10,492
|
remove from an array of interface Parte {
id: number;
attiParteFigura: AttoParteFigura[];
partiLegate: ParteLegata[];
anagraficaParte: AnagraficaParte;
tipo: CivileParam;
avvocati: AnagraficaAvvocato[];
}
interface AttoParteFigura {
id: number;
tipoFigura: CivileParam;
avvocatiRicorsoParte: AvvocatoRicorsoParte[];
atto: AttoSic;
oggi: number;
}
interface AttoSic {
id: number;
dataIscr: number;
anagAtti: CivileAnagAtti;
}
interface CivileAnagAtti {
idAnagAtti: number;
sigla: string;
descrizione: string;
dataFineValidita: Date;
}
all the elements that have attiParteFigura.atto.anagAtti.sigla === 'D' using possibily lodash
|
bc0318e3223520a29460c844a5449413
|
{
"intermediate": 0.3665015995502472,
"beginner": 0.3860914409160614,
"expert": 0.2474069446325302
}
|
10,493
|
试图从下列CTF竞赛的代码解出FLAG值,并给出详细的解答步骤和说明:
#!/usr/bin/env sage
from secret import a, b, p
from hashlib import sha256
E = EllipticCurve(GF(p), [a, b])
P = E(68363894779467582714652102427890913001389987838216664654831170787294073636806, 48221249755015813573951848125928690100802610633961853882377560135375755871325)
assert (E(P[0] + 1, P[1]))
assert (E(P[0] + 2, P[1]))
Q = P * 0x1234567890abcdef
# print("The FLAG is NeSE{" + sha256(str(Q[0]).encode()).hexdigest() + "}")
|
6207f4e4863a76fb1126ef15b3a79b28
|
{
"intermediate": 0.3550107479095459,
"beginner": 0.45139965415000916,
"expert": 0.19358953833580017
}
|
10,494
|
const createMany = await prisma.$transaction(async (tx) => {
const quotations = await Promise.all(
body.quotations.map((quotation, index) => {
if (!quotation.itemCode || !items[index]) return null; //skip if item code is not found
(quotation as any).status = QuotationStatus.BRANCH_APPROVED;
(quotation as any).creationStatus =
QuotationCreationStatus.IMPORTED;
if (!quotation.collectorId) quotation.collectorId = req.user!.id;
return tx.quotation.create({
data: {
questionnaireId: quotation.questionnaireId,
collectorId: req.user!.id,
itemCode: quotation!.itemCode,
marketplaceCode: quotation.marketplaceCode!,
quotes: {
createMany: {
data: quotation.quotes!.map((quote) => ({
...quote,
shopContactName: "Imported",
shopContactPhone: "Imported",
shopLatitude: "Imputated",
shopLongitude: "Imputated",
measurementUnit: items?.[index]!?.UoMCode,
})),
},
// quotation.quotes?.map((quote) => { return {...quote,quantity: items[index]?.measurementQuantity,
// measurmentId: items[index]?.measurement,};}),
},
},
select: {
id: true,
questionnaireId: true,
itemCode: true,
quotes: true,
},
});
})
); on the above prisma query the status and creationStatus is not being assigned , any suggestions
|
f88b2583c63ad58418a3599cd666f592
|
{
"intermediate": 0.2632613182067871,
"beginner": 0.6067690849304199,
"expert": 0.1299695372581482
}
|
10,495
|
привет помоги пожалуйста с рефакторингом этого метода
protected virtual void UpdateTransform()
{
CheckDeviceIndex();
if (playerTransform != null)
{
transform.position = playerTransform.TransformPoint(poseAction[inputSource].localPosition);
if (isFireExtinguisher && !isFireExtinguisherUse)
{
transform.localEulerAngles = fireExtinguisherAngles;
return;
}
if (IsBoxFireExtinguisher)
{
var angle = playerTransform.rotation * poseAction[inputSource].localRotation;
transform.rotation = Quaternion.Euler(0, angle.eulerAngles.y, 0);
}
else
{
if (fireExtinguisherCalibration)
{
localRotationStart = poseAction[inputSource].localRotation;
}
if (calibrationRotationImplemented)
{
transform.rotation = playerTransform.rotation * (poseAction[inputSource].localRotation * Quaternion.Inverse(localRotationStart));
}
else
{
transform.rotation = playerTransform.rotation * poseAction[inputSource].localRotation;
}
}
}
}
|
f72ff50a2c91f5f989e068374f67f47a
|
{
"intermediate": 0.2694230079650879,
"beginner": 0.4735374450683594,
"expert": 0.25703954696655273
}
|
10,496
|
import requests
API_KEY = ‘CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS’
TOKEN_CONTRACT = ‘0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e’
def get_transaction_list(api_key, contract_address, start_block=28269140, end_block=29812249, page=1, offset=150):
url = f’https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={contract_address}&startblock={start_block}&endblock={end_block}&page={page}&offset={offset}&apikey={api_key}'
response = requests.get(url)
if response.status_code == 200:
result = response.json()
return result[‘result’]
else:
return None
def get_all_transaction_hashes(api_key, contract_address, method_id_filter=None):
all_hashes = []
page = 1
while True:
transactions = get_transaction_list(api_key, contract_address, page=page)
if transactions:
for tx in transactions:
method_id = tx[‘input’][:10]
if not method_id_filter or method_id.lower() == method_id_filter.lower():
all_hashes.append(tx[‘hash’])
if len(transactions) < 100:
break
page += 1
else:
print(‘Error getting transactions’)
break
return all_hashes
all_transaction_hashes = get_all_transaction_hashes(API_KEY, TOKEN_CONTRACT, “0xf305d719”)
for txn_hash in all_transaction_hashes:
print(txn_hash)
The code above produces a null result and does not filter the address of a hash with the specified decoded element, although there is such a hash in the list
|
deaf894ede5baec0c22ae533a71c220a
|
{
"intermediate": 0.48371416330337524,
"beginner": 0.2921935021877289,
"expert": 0.2240923047065735
}
|
10,497
|
how can i write that only admin can add posts in db firebase but users can only register and read these posts?
here is my code in firebase rules:
{
"rules": {
"users":{
"$uid":{
".read":
"$uid===auth.uid",
".write":
"$uid===auth.uid"
}
}
}
}
i have already made an admin in realtime database by adding a boolean field named admin
|
5cccf21914b85d1aa15e1e88876660f1
|
{
"intermediate": 0.6131024956703186,
"beginner": 0.24650590121746063,
"expert": 0.14039169251918793
}
|
10,498
|
c program to determine if a number is prime
|
6caab6f6c07882fbc311ad581ad39a2e
|
{
"intermediate": 0.33973079919815063,
"beginner": 0.16985295712947845,
"expert": 0.4904162287712097
}
|
10,499
|
write c program to determine if a number is prime
|
a07fbb56532fa1a5f4c9bfe120eef7ef
|
{
"intermediate": 0.3385753929615021,
"beginner": 0.21916241943836212,
"expert": 0.442262202501297
}
|
10,500
|
please provide me with the Java code that will connect RabbitMQ on the server 192.168.0.137
|
614d224c84366659e0a3c8a417f4085f
|
{
"intermediate": 0.68391352891922,
"beginner": 0.12290339916944504,
"expert": 0.19318309426307678
}
|
10,501
|
Não quero usar vetores, e para usar apenas nós, modifique o codigo
------------ main.cpp--------------
#include <iostream>
#include <fstream>
#include "SparseMatrix.h"
SparseMatrix* readSparseMatrix(std::string file_name) {
std::ifstream file(file_name);
if (!file) {
std::cout << "Error opening file: " << file_name << std::endl;
return nullptr;
}
int rows, cols;
file >> rows >> cols;
SparseMatrix* matrix = new SparseMatrix(rows, cols);
int row, col;
double value;
while (file >> row >> col >> value) {
matrix->insert(row, col, value);
}
file.close();
return matrix;
}
SparseMatrix* sum(SparseMatrix* A, SparseMatrix* B) {
if (A->getRows() != B->getRows() || A->getCols() != B->getCols()) {
std::cout << "Matrices must have the same dimensions for addition." << std::endl;
return nullptr;
}
SparseMatrix* result = new SparseMatrix(A->getRows(), A->getCols());
for (int i = 0; i < A->getRows(); i++) {
for (int j = 0; j < A->getCols(); j++) {
double valueA = A->get(i, j);
double valueB = B->get(i, j);
result->insert(i, j, valueA + valueB);
}
}
return result;
}
SparseMatrix* multiply(SparseMatrix* A, SparseMatrix* B) {
if (A->getCols() != B->getRows()) {
std::cout << "The number of columns in matrix A must be equal to the number of rows in matrix B for multiplication." << std::endl;
return nullptr;
}
SparseMatrix* result = new SparseMatrix(A->getRows(), B->getCols());
for (int i = 0; i < A->getRows(); i++) {
for (int j = 0; j < B->getCols(); j++) {
double value = 0.0;
for (int k = 0; k < A->getCols(); k++) {
value += A->get(i, k) * B->get(k, j);
}
result->insert(i, j, value);
}
}
return result;
}
int main() {
// Exemplo de uso
SparseMatrix* A = readSparseMatrix("matrixA.txt");
SparseMatrix* B = readSparseMatrix("matrixB.txt");
if (A != nullptr && B != nullptr) {
std::cout << "Matrix A:" << std::endl;
A->print();
std::cout << "Matrix B:" << std::endl;
B->print();
SparseMatrix* sumResult = sum(A, B);
if (sumResult != nullptr) {
std::cout << "Sum of matrices:" << std::endl;
sumResult->print();
delete sumResult;
}
SparseMatrix* multiplyResult = multiply(A, B);
if (multiplyResult != nullptr) {
std::cout << "Multiplication of matrices:" << std::endl;
multiplyResult->print();
delete multiplyResult;
}
}
delete A;
delete B;
return 0;
}
---------------SparseMatrix.cpp------------------
#include <iostream>
#include "SparseMatrix.h"
SparseMatrix::SparseMatrix(int m, int n) {
if (m <= 0 || n <= 0) {
std::cout << "Invalid matrix dimensions: " << m << " x " << n << std::endl;
rows = 0;
cols = 0;
return;
}
rows = m;
cols = n;
rowsArray.resize(rows, nullptr);
}
SparseMatrix::~SparseMatrix() {
// Liberar a memória alocada para a matriz esparsa
for (int i = 0; i < rows; i++) {
Node* current = rowsArray[i];
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
}
void SparseMatrix::insert(int i, int j, double value) {
if (i < 0 || i >= rows || j < 0 || j >= cols) {
std::cout << "Invalid matrix cell: (" << i << ", " << j << ")" << std::endl;
return;
}
Node* newNode = new Node(i, j, value);
newNode->next = rowsArray[i];
rowsArray[i] = newNode;
}
double SparseMatrix::get(int i, int j) {
if (i < 0 || i >= rows || j < 0 || j >= cols) {
std::cout << "Invalid matrix cell: (" << i << ", " << j << ")" << std::endl;
return 0.0;
}
Node* current = rowsArray[i];
while (current != nullptr) {
if (current->col == j) {
return current->value;
}
current = current->next;
}
return 0.0; // Valor padrão para células não encontradas
}
void SparseMatrix::print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
double value = get(i, j);
std::cout << value << " ";
}
std::cout << std::endl;
}
}
------------ SparseMatrix.h--------------
#ifndef SPARSE_MATRIX_H
#define SPARSE_MATRIX_H
#include <vector>
class SparseMatrix {
public:
SparseMatrix(int m, int n);
~SparseMatrix();/chatgpt4
void insert(int i, int j, double value);
double get(int i, int j);
void print();
int getRows() { return rows; }
int getCols() { return cols; }
private:
struct Node {
int row;
int col;
double value;
Node* next;
Node(int r, int c, double v)
: row(r), col(c), value(v), next(nullptr) {}
};
int rows;
int cols;
std::vector<Node*> rowsArray;
};
#endif
|
67f8ab0875ef2d072489ff6eeb2ec958
|
{
"intermediate": 0.30963781476020813,
"beginner": 0.35631799697875977,
"expert": 0.3340441584587097
}
|
10,502
|
Please continue your code: I apologize for the confusion. It looks like the ccxt library has some differences in the naming of fields compared to Binance’s own API. Instead of changing type to side, we should replace all the side fields with sideEffectType to match the Binance API.
Please replace the following lines:
‘type’: ‘future’,
‘adjustForTimeDifference’: True
}
to:
‘defaultType’: ‘future’,
‘adjustForTimeDifference’: True
},
‘future’: {
‘sideEffectType’: ‘MARGIN_BUY’, # MARGIN_BUY, AUTO_REPAY, etc…
}
and in the order_execution function, modify positionSide, reduceOnly, newOrderRespType, workingType, and priceProtect fields to match the Binance API naming standards.
Replace the following lines:
“type”: order_type,
“positionSide”: position_side,
“quantity”: quantity,
“price”: price,
“stopPrice”: stop_loss_price if signal == “buy” else take_profit_price,
“reduceOnly”: True,
“newOrderRespType”: “RESULT”,
“workingType”: “MARK_PRICE”,
“priceProtect”: False,
“leverage”: leverage
to:
“sideEffectType”: “MARGIN_BUY” if signal == “buy” else “MARGIN_SELL”,
“positionSide”: position_side,
“quantity”: quantity,
“price”: price,
“stopPrice”: stop_loss_price if signal == “buy” else take_profit_price,
“closePosition”: True,
“newClientOrderId”: ‘bot’,
“type”:
|
ea9e6dc8360e79dd62c0d7eb15cafe68
|
{
"intermediate": 0.6872996687889099,
"beginner": 0.15430280566215515,
"expert": 0.15839752554893494
}
|
10,503
|
Is there a way to enforce usage of ipv6 for docker compose?
|
60eaf23d30fc641409c298d8e307a0eb
|
{
"intermediate": 0.4535076916217804,
"beginner": 0.22525207698345184,
"expert": 0.32124027609825134
}
|
10,504
|
code in r with packages. for array "00001111110000" "00000111000" find the first and last position for the area that is 1
|
539623d8d7ffdda2acf1dc36e1b1efed
|
{
"intermediate": 0.3857065439224243,
"beginner": 0.28155985474586487,
"expert": 0.3327336311340332
}
|
10,505
|
Привет помоги с рефакторингом
protected virtual void UpdateTransform()
{
CheckDeviceIndex();
if (playerTransform == null) return;
UpdatePosition();
UpdateRotation();
}
private void UpdatePosition()
{
transform.position = playerTransform.TransformPoint(poseAction[inputSource].localPosition);
}
private void UpdateRotation()
{
if (isFireExtinguisher && !isFireExtinguisherUse)
{
SetFireExtinguisherRotation();
return;
}
if (IsBoxFireExtinguisher)
{
SetBoxRotation();
}
else
{
SetDefaultRotation();
}
}
private void SetFireExtinguisherRotation()
{
transform.localEulerAngles = fireExtinguisherAngles;
}
private void SetBoxRotation()
{
var angle = playerTransform.rotation * poseAction[inputSource].localRotation;
transform.rotation = Quaternion.Euler(0, angle.eulerAngles.y, 0);
}
private void SetDefaultRotation()
{
if (fireExtinguisherCalibration)
{
localRotationStart = poseAction[inputSource].localRotation;
var angle = playerTransform.rotation * poseAction[inputSource].localRotation * Quaternion.Inverse(localRotationStart);
var y = playerTransform.rotation * poseAction[inputSource].localRotation;
transform.rotation = Quaternion.Euler(angle.eulerAngles.x, y.eulerAngles.y, angle.eulerAngles.z);
return;
}
Quaternion modifier;
if (calibrationRotationImplemented)
{
modifier = poseAction[inputSource].localRotation * Quaternion.Inverse(localRotationStart);
}
else
{
modifier = poseAction[inputSource].localRotation;
}
transform.rotation = playerTransform.rotation * modifier;
}
|
833257ae77f280360d883cefc8d678ef
|
{
"intermediate": 0.3115902841091156,
"beginner": 0.509265661239624,
"expert": 0.179144024848938
}
|
10,506
|
import requests
API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
TOKEN_CONTRACT = '0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e'
def get_transaction_list(api_key, contract_address, start_block=28269140, end_block=29812249, page=1, offset=150):
url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={contract_address}&startblock={start_block}&endblock={end_block}&page={page}&offset={offset}&apikey={api_key}'
response = requests.get(url)
if response.status_code == 200:
result = response.json()
return result['result']
else:
return None
def get_all_transaction_hashes(api_key, contract_address):
all_hashes = []
page = 1
while True:
transactions = get_transaction_list(api_key, contract_address, page=page)
if transactions:
hashes = [tx['hash'] for tx in transactions]
all_hashes.extend(hashes)
if len(transactions) < 100:
break
page += 1
else:
print('Error getting transactions')
break
return all_hashes
all_transaction_hashes = get_all_transaction_hashes(API_KEY, TOKEN_CONTRACT)
for txn_hash in all_transaction_hashes:
print(txn_hash)
Change the code above so that in addition to the hash, it also outputs data from the id, From and To method columns that correspond to the hashes
|
9ac27bed95afa91cdabe520e60c3d40d
|
{
"intermediate": 0.4136648178100586,
"beginner": 0.38736242055892944,
"expert": 0.19897276163101196
}
|
10,507
|
does CockroachDB support any consistency level other than linearizable?
|
8ea71e7e8254dad71bd8d27c45bd4e43
|
{
"intermediate": 0.4220240116119385,
"beginner": 0.20381398499011993,
"expert": 0.37416204810142517
}
|
10,508
|
Provide the C++ code for merging two maps
|
c73caa3f089eb96f5b97505cbcc53d7c
|
{
"intermediate": 0.36576321721076965,
"beginner": 0.1946021169424057,
"expert": 0.4396347105503082
}
|
10,509
|
is it possible for a partition in c++ module to have its own partitions?
|
e43386fd9cdfde40ac47b9605b9b2128
|
{
"intermediate": 0.46346011757850647,
"beginner": 0.18689624965190887,
"expert": 0.3496435880661011
}
|
10,510
|
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 requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# 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)
# API keys and other configuration
API_KEY = ''
client = Client(API_KEY, API_SECRET)
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': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
markets = binance_futures.load_markets()
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialze 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 = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
order_params = {
"type": "MARKET" if signal == "buy" else "MARKET",
"side": "BUY" if signal == "buy" else "SELL",
"quantity": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"closePosition": True,
"newClientOrderId": 'bot',
"type":order_type.upper(),
"responseType": "RESULT",
"timeInForce": "GTC",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": leverage
}
try:
order_params['symbol'] = symbol
response = binance_futures.create_order(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR:The signal time is: 2023-06-06 17:04:23 :
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 257, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 244, in order_execution
response = binance_futures.create_order(**order_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: binance.create_order() got an unexpected keyword argument 'quantity'
|
5dbf7d518febdcb2947e0a5c3d51b818
|
{
"intermediate": 0.3867127597332001,
"beginner": 0.5137419104576111,
"expert": 0.09954527020454407
}
|
10,511
|
i want a c# code that can read and extract farsi(persian) text of images
|
7c83ee4b116c2039e064bfd60bb2c745
|
{
"intermediate": 0.6102433204650879,
"beginner": 0.14197368919849396,
"expert": 0.24778303503990173
}
|
10,512
|
Can you write a hello world program that would run on an arduino
|
0d72b1fc3e6d92b00a6424c5ffc7eb76
|
{
"intermediate": 0.39614930748939514,
"beginner": 0.3094819486141205,
"expert": 0.2943687438964844
}
|
10,513
|
Can you make an arduino program that controls a stepper motor
|
7a44a0c7fd874b8109e3da9564b3f202
|
{
"intermediate": 0.4016590714454651,
"beginner": 0.17745985090732574,
"expert": 0.42088112235069275
}
|
10,514
|
i need to add a new foncitonalty to a visual force page that can trasnlate the entire page based on language selected how i can make it
|
b0fcfb17b7712a8dd7dae1342517b245
|
{
"intermediate": 0.3431170582771301,
"beginner": 0.2969609200954437,
"expert": 0.35992196202278137
}
|
10,515
|
Can you make a program for arduino that reads a temperature from a sensor and controls a stepper such that the stepper moves until the temperature is above 20 degrees
|
cfafec26d869f353c1d46ee18eb02336
|
{
"intermediate": 0.4238145053386688,
"beginner": 0.1054949015378952,
"expert": 0.47069063782691956
}
|
10,516
|
import requests
API_KEY = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
TOKEN_CONTRACT = '0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e'
def get_transaction_list(api_key, contract_address, start_block=28269140, end_block=29812249, page=1, offset=150):
url = f'https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={contract_address}&startblock={start_block}&endblock={end_block}&page={page}&offset={offset}&apikey={api_key}'
response = requests.get(url)
if response.status_code == 200:
result = response.json()
return result['result']
else:
return None
def get_all_transaction_hashes(api_key, contract_address):
all_hashes = []
page = 1
while True:
transactions = get_transaction_list(api_key, contract_address, page=page)
if transactions:
hashes = [tx['hash'] for tx in transactions]
all_hashes.extend(hashes)
if len(transactions) < 100:
break
page += 1
else:
print('Error getting transactions')
break
return all_hashes
all_transaction_hashes = get_all_transaction_hashes(API_KEY, TOKEN_CONTRACT)
for txn_hash in all_transaction_hashes:
print(txn_hash)
Modify the code above so that in addition to the data in the hash column, it also displays the following data:
Data in the Method column
Data in the Age column
Data in the From column
Data in column To
|
8a62f76845ef940f86c3695768bb804a
|
{
"intermediate": 0.40338975191116333,
"beginner": 0.34999141097068787,
"expert": 0.24661879241466522
}
|
10,517
|
im making a roblox game in Roblox Studio, I have created a hitbox for a fighting game. How would I make it so whenever a player is inside the created hitbox part, they receive a "stun" effect where they cannot make any inputs and I play an animation of my choice (one that I have uploaded into roblox)
|
90abe006f51aae96dda107abf58f4246
|
{
"intermediate": 0.5163098573684692,
"beginner": 0.25405895709991455,
"expert": 0.2296311855316162
}
|
10,518
|
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 requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# 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)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
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': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
markets = binance_futures.load_markets()
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialze 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 = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
order_params = {
"type": "MARKET" if signal == "buy" else "MARKET",
"side": "BUY" if signal == "buy" else "SELL",
"amount": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"closePosition": True,
"newClientOrderId": 'bot',
"type":order_type.upper(),
"responseType": "RESULT",
"timeInForce": "GTC",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": leverage
}
try:
order_params['symbol'] = symbol
response = binance_futures.create_order(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR:The signal time is: 2023-06-06 17:09:14 :
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 257, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 244, in order_execution
response = binance_futures.create_order(**order_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: binance.create_order() got an unexpected keyword argument 'stopPrice'
|
a2584a1348903ff3e87a1a9b222b2d11
|
{
"intermediate": 0.45047304034233093,
"beginner": 0.44051292538642883,
"expert": 0.10901406407356262
}
|
10,519
|
MATLAB code to calculate the relative humidity percentage of air using dry and wet temperature
|
ca1d205f64e29eb324acf7ebba9c17e0
|
{
"intermediate": 0.37377360463142395,
"beginner": 0.2299262285232544,
"expert": 0.39630013704299927
}
|
10,520
|
请帮我完善代码,杜绝内存泄漏以及优化错误的地方
push.cpp:
#include "Pusher.h"
#include <iostream>
#include "Common/config.h"
#include "appPublic.h"
#include "FifoMsg.h"
using namespace std;
using namespace mediakit;
using namespace toolkit;
enum AVCodeConst {
AV_CODER_NONE = 0,
AV_VIDEO_CODER_H264 = 1,
AV_VIDEO_CODER_HEVC = 2,
AV_AUDIO_CODER_AAC = 3
};
enum EnumFrameType {
FRAME_TYPE_VIDEO = 0,
FRAME_TYPE_AUDIO = 1,
};
#define PUSH_FIELD "push."
const string kEnableAAC2G711A = PUSH_FIELD"EnableAAC2G711A";
#define MAX_WRITE_FAILED_TIME (10)
Pusher::Pusher(const SdpInfo &p_SdpInfo)
:m_bIsInitOK(false)
,m_SdpInfo(p_SdpInfo)
,m_audioIdx(0)
,m_videoIdx(0)
,m_ofmt_ctx(NULL)
,aac_swr_ctx(NULL)
,pAcodecContext(NULL)
,alaw_codecContext(NULL)
,m_writeFailedTime(0){
int nInitFlag = init();
if (nInitFlag == 0){
m_bIsInitOK = true;
InfoL<<"create pusher success,dev:"<<m_SdpInfo.szPlayUrl;
}
else{
nInitFlag = false;
InfoL<<"create pusher failed,dev:"<<m_SdpInfo.szPlayUrl;
release();
return;
}
}
Pusher::~Pusher(){
release();
InfoL<<m_SdpInfo.szPlayUrl<<" pusher is released";
}
void Pusher::release(){
if(m_ofmt_ctx == NULL)
return;
av_write_trailer(m_ofmt_ctx);
if (!(m_ofmt_ctx->flags & AVFMT_NOFILE)) {
avio_close(m_ofmt_ctx->pb);
}
avformat_free_context(m_ofmt_ctx);
m_ofmt_ctx = NULL;
if(pAcodecContext){
avcodec_free_context(&pAcodecContext);
pAcodecContext = NULL;
}
if (alaw_codecContext){
avcodec_free_context(&alaw_codecContext);
alaw_codecContext = NULL;
}
}
void Pusher::ffLogCallback(void *ptr, int level, const char *fmt, va_list vl)
{
if (level > av_log_get_level())
return;
char temp[1024];
vsprintf(temp, fmt, vl);
size_t len = strlen(temp);
if (len > 0 && len < 1024&&temp[len - 1] == '\n')
{
temp[len - 1] = '\0';
}
DebugL << (char *)temp;
}
/* select layout with the highest channel count */
uint64_t Pusher::select_channel_layout(const AVCodec *codec)
{
if (!codec)
return AV_CH_LAYOUT_STEREO;
const uint64_t *p;
uint64_t best_ch_layout = 0;
int best_nb_channels = 0;
if (!codec->channel_layouts)
return AV_CH_LAYOUT_STEREO;
p = codec->channel_layouts;
while (*p) {
int nb_channels = av_get_channel_layout_nb_channels(*p);
if (nb_channels > best_nb_channels) {
best_ch_layout = *p;
best_nb_channels = nb_channels;
}
p++;
}
return best_ch_layout;
}
int Pusher::select_sample_rate(const AVCodec *codec)
{
if (!codec)
return 44100;
const int *p;
int best_samplerate = 0;
if (!codec->supported_samplerates)
return 44100;
p = codec->supported_samplerates;
while (*p) {
if (!best_samplerate || abs(44100 - *p) < abs(44100 - best_samplerate))
best_samplerate = *p;
p++;
}
return best_samplerate;
}
bool Pusher::init(){
if (strlen(m_SdpInfo.szPlayUrl) <= 0){
ErrorL<<"输出URL不能为空";
return false;
}
av_register_all();
avformat_network_init();
av_log_set_level(AV_LOG_INFO);
av_log_set_callback(ffLogCallback);
AVDictionary *pDict = NULL;
int ret = avformat_alloc_output_context2(&m_ofmt_ctx, NULL, m_SdpInfo.szFmt, m_SdpInfo.szPlayUrl);
if (ret < 0){
ErrorL<<"avformat_alloc_output_context2 failed, output:"<<m_SdpInfo.szFmt;
return -1;
}
AVCodec *pEnCodeV = NULL;
if (m_SdpInfo.nVideoCodec == AV_VIDEO_CODER_H264)
pEnCodeV = avcodec_find_encoder(AV_CODEC_ID_H264);
else
pEnCodeV = avcodec_find_encoder(AV_CODEC_ID_H265);
if(pEnCodeV)
InfoL<<"The video codec is:"<<pEnCodeV->name;
//设置视频输出格式
AVStream *pStreamO = avformat_new_stream(m_ofmt_ctx, pEnCodeV);
pStreamO->id = m_ofmt_ctx->nb_streams - 1;
pStreamO->codec->codec_tag = 0;
pStreamO->codec->width = 1280;
pStreamO->codec->height = 1080;
pStreamO->codec->pix_fmt = AV_PIX_FMT_YUV420P;
AVRational tb{ 1, 90000 };
pStreamO->time_base = tb;
AVRational fr{ 25, 1 };
pStreamO->r_frame_rate = fr; //(tbr)
pStreamO->avg_frame_rate = fr; //(fps)
AVRational sar{ 1, 1 };
pStreamO->sample_aspect_ratio = sar;
AVRational ctb{ 1, 25 };
pStreamO->codec->time_base = ctb;
pStreamO->codec->sample_aspect_ratio = sar;
pStreamO->codec->gop_size = 12;
if (m_ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) {
pStreamO->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
if (avcodec_open2(pStreamO->codec, pEnCodeV, NULL) != 0) {
ErrorL << "avcodec_open2 video error";
}
AVStream *pAStreamO = NULL;
bool bEnableAAC2G711AFlag = mINI::Instance()[kEnableAAC2G711A];
if (bEnableAAC2G711AFlag){
//设置音频输出格式
AVCodec *pEnCodeA = avcodec_find_encoder(::AV_CODEC_ID_PCM_ALAW);
pAStreamO = avformat_new_stream(m_ofmt_ctx, pEnCodeA);
pAStreamO->id = m_ofmt_ctx->nb_streams - 1;
pAStreamO->codec->codec_tag = 0;
pAStreamO->codec->sample_fmt = ::AV_SAMPLE_FMT_S16;
pAStreamO->codec->channel_layout = AV_CH_LAYOUT_MONO;
pAStreamO->codec->sample_rate = 8000;
pAStreamO->codec->channels = 1;
pAStreamO->codec->frame_size = 160/2;
if (avcodec_open2(pAStreamO->codec, pEnCodeA, NULL) != 0) {
ErrorL<<"avcodec_open2 audio error" ;
}
}else{
AVCodec *pEnCodeA = avcodec_find_encoder(::AV_CODEC_ID_AAC);
AVStream *pAStreamO = avformat_new_stream(m_ofmt_ctx, pEnCodeA);
pAStreamO->id = m_ofmt_ctx->nb_streams - 1;
pAStreamO->codec->codec_tag = 0;
pAStreamO->codec->sample_fmt = ::AV_SAMPLE_FMT_FLTP;
pAStreamO->codec->channel_layout = select_channel_layout(pAStreamO->codec->codec);
pAStreamO->codec->sample_rate = select_sample_rate(pAStreamO->codec->codec);
pAStreamO->codec->channels = ::av_get_channel_layout_nb_channels(pAStreamO->codec->channel_layout);
if (avcodec_open2(pAStreamO->codec, pEnCodeA, NULL) != 0) {
ErrorL<<"avcodec_open2 audio error" ;
}
}
if (!(m_ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
ret = avio_open(&m_ofmt_ctx->pb, m_SdpInfo.szPlayUrl, AVIO_FLAG_WRITE);
}
if (0 == strcasecmp(m_SdpInfo.szFmt, "rtsp")){
av_dict_set(&pDict, "rtsp_transport", "tcp", 0);
av_dict_set(&pDict, "muxdelay", "0.1", 0);
}
ret = avformat_write_header(m_ofmt_ctx, &pDict);
av_dump_format(m_ofmt_ctx, 0, m_SdpInfo.szPlayUrl, 1);
if (!bEnableAAC2G711AFlag){
InfoL<<"新建国标流推流器,设备:"<<m_SdpInfo.szPlayUrl;
return ret;
}
InfoL<<"使能AAC转G711A,初始化AAC解码器和G711A编码器";
//以下为aac->alaw相关
//aac音频格式
int64_t in_channel_layout = AV_CH_LAYOUT_STEREO;
enum AVSampleFormat in_sample_fmt = AV_SAMPLE_FMT_FLTP;
int in_sample_rate = 44100;
int in_channels = 2;
AVRational in_timeBase = {1,44100};
//alaw音频格式
uint64_t out_channel_layout = AV_CH_LAYOUT_MONO;
enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
int out_sample_rate = 8000;
int out_nb_samples = 160;
int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);
//aac->alaw重采样器
aac_swr_ctx = swr_alloc();
aac_swr_ctx = swr_alloc_set_opts(aac_swr_ctx, out_channel_layout, out_sample_fmt, out_sample_rate,in_channel_layout, in_sample_fmt, in_sample_rate, 0, NULL);
swr_init(aac_swr_ctx);
//初始化AAC解码器
AVCodec *pAcodec = avcodec_find_decoder(AV_CODEC_ID_AAC);
pAcodecContext = avcodec_alloc_context3(pAcodec);
pAcodecContext->sample_rate = in_sample_rate;
pAcodecContext->channels = in_channels;
pAcodecContext->sample_fmt = in_sample_fmt;
pAcodecContext->time_base = in_timeBase;
avcodec_open2(pAcodecContext, pAcodec, NULL);
//初始化alaw编码器
AVCodec* alaw_codec = avcodec_find_encoder(AV_CODEC_ID_PCM_ALAW);
alaw_codecContext = avcodec_alloc_context3(alaw_codec);
alaw_codecContext->codec_type = AVMEDIA_TYPE_AUDIO;
alaw_codecContext->sample_rate = 8000;
alaw_codecContext->channels = 1;
alaw_codecContext->sample_fmt = out_sample_fmt; // ALAW编码需要16位采样,U8在目前ff版本不支持
alaw_codecContext->channel_layout = AV_CH_LAYOUT_MONO;
alaw_codecContext->height = pStreamO->codec->height;
alaw_codecContext->width = pStreamO->codec->width;
alaw_codecContext->codec_id = AV_CODEC_ID_PCM_ALAW;
alaw_codecContext->bit_rate = 64000;
//alaw_codecContext->frame_size = 160/2;
ret = avcodec_open2(alaw_codecContext, alaw_codec, NULL);
if (ret < 0)
ErrorL<<"avcodec_open2 alaw_codecContext failed";
else
InfoL<<"avcodec_open2 alaw_codecContext ok";
av_init_packet(&m_pkt);
return ret;
}
int Pusher::WriteFrame(const int p_nFrameType,const uint8_t *p_frame_data, const int p_frame_len){
if (!m_bIsInitOK)
return -1;
int64_t currentTimeStamp = 0;
if (p_nFrameType == FRAME_TYPE_VIDEO) {
currentTimeStamp = m_videoIdx * 3600;
if(strlen(m_SdpInfo.szFileName) > 0 && (m_videoIdx % 25 == 0)){
int ndownloadProgress = (int)(m_videoIdx * 100 / m_SdpInfo.nHistoryTotalFrameNum);
if(ndownloadProgress >= 100){
ndownloadProgress = 100;
}
InfoL<<"download file:"<<m_SdpInfo.szFileName<<" download progress:"<<ndownloadProgress;
m_SdpInfo.nDownloadProgress = ndownloadProgress;
m_SdpInfo.nEventType = DevProcessType_upload_download_progress;
sendFifoMsg(m_SdpInfo);
}
m_videoIdx++;
}
if (p_nFrameType == FRAME_TYPE_AUDIO) {
currentTimeStamp= m_audioIdx * 1024;
m_audioIdx++;
}
AVPacket pkt;
av_init_packet(&pkt);
pkt.data = (uint8_t*)p_frame_data;
pkt.size = p_frame_len;
pkt.pts = currentTimeStamp;
pkt.dts = currentTimeStamp;
pkt.duration = 3600;
pkt.pos = -1;
pkt.stream_index = p_nFrameType;
int ret = -1;
if (p_nFrameType == FRAME_TYPE_VIDEO) {
//std::cout<<"=====lgo 1==="<<std::endl;
if (m_ofmt_ctx){
ret = av_write_frame(m_ofmt_ctx, &pkt);
//std::cout<<"=====lgo 2===ret:"<<ret<<std::endl;
if(ret < 0){
m_writeFailedTime++;
if (MAX_WRITE_FAILED_TIME < m_writeFailedTime || ret == -32){
m_SdpInfo.nEventType = DevProcessType_stop_stream;
sendFifoMsg(m_SdpInfo);
return -1;
}
}
m_writeFailedTime = 0;
}
av_packet_unref(&pkt);
return ret;
}
bool bEnableAAC2G711AFlag = mINI::Instance()[kEnableAAC2G711A];
if (!bEnableAAC2G711AFlag){
if (m_ofmt_ctx){
ret = av_write_frame(m_ofmt_ctx, &pkt);
}
av_packet_unref(&pkt);
return ret;
}
if (p_nFrameType == FRAME_TYPE_AUDIO) {
int got_frame;
AVFrame *pAACFrame=av_frame_alloc();
ret = avcodec_decode_audio4(pAcodecContext, pAACFrame, &got_frame, &pkt);
if(ret < 0){
ErrorL<<"avcodec_decode_audio4 failed";
return -1;
}else if (got_frame){
//解码aac成功后,重采样得到alaw数据
uint64_t out_channel_layout = AV_CH_LAYOUT_MONO;
enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
int out_nb_samples = 160;
int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);
int alaw_buffer_size = av_samples_get_buffer_size(NULL, out_channels, out_nb_samples, out_sample_fmt, 1);
//44.1KHZ,16bit,2声道的pcm转换成pcma 8khz,16bit,1声道
uint8_t *alaw_buffer = (uint8_t *)av_malloc(pAACFrame->nb_samples);
swr_convert(aac_swr_ctx, &alaw_buffer, alaw_buffer_size, (const uint8_t **)pAACFrame->data, pAACFrame->nb_samples);
//构造alawFrame
AVFrame * alawFrame = av_frame_alloc();
//设置AVFrame的基本信息
alawFrame->sample_rate = 8000;
alawFrame->channels = 1;
alawFrame->format = AV_SAMPLE_FMT_S16;
alawFrame->channel_layout = AV_CH_LAYOUT_MONO;
alawFrame->nb_samples = alaw_buffer_size/2;
av_frame_get_buffer(alawFrame, 0);
memcpy(alawFrame->data[0], alaw_buffer, alaw_buffer_size);
int got_packet = 0;
AVPacket* packet = av_packet_alloc();
av_init_packet(packet);
packet->data = alaw_buffer;
packet->size = alaw_buffer_size;
packet->stream_index = 1;
ret = avcodec_encode_audio2(alaw_codecContext, packet, alawFrame, &got_packet);
av_frame_free(&alawFrame);
if (ret < 0){
ErrorL<<"avcodec_encode_audio2 failed";
}else if (got_packet){
//成功编码出音频包后,写输出流
int nbSamplesPerPacket = 160;
int sampleRate = 8000;
packet->pts = (m_audioIdx-1) *160;
packet->dts = packet->pts;
packet->duration = 160;
packet->stream_index = 1;
packet->pos = 1;
ret = ::av_write_frame(m_ofmt_ctx, packet);
}
av_packet_free(&packet);
av_free(alaw_buffer);
}
av_frame_free(&pAACFrame);
}
av_packet_unref(&pkt);
return 0;
}
void Pusher::sendFifoMsg(const SdpInfo &p_objSdpInfo){
if (p_objSdpInfo.nSrcPort <= 0 || strlen(p_objSdpInfo.szDevid) <= 0)
return;
char szFifoName[128] = {0};
snprintf(szFifoName, sizeof(szFifoName), FORMAT_PORT_DISPATCH_THREAD_MSG_FIFO,p_objSdpInfo.nSrcPort);
std::string strJson;
SdpParse::makeFifoMsgJson(p_objSdpInfo, strJson);
DebugL<<"send msg, fifo:"<<szFifoName<<", msg:"<<strJson;
FifoMsg::fifo_send_msg(szFifoName, strJson);
}
push.h
#ifndef PUSHER_H
#define PUSHER_H
#include <string>
#include <string.h>
#include "SdpParse.h"
extern "C" {
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libavutil/avutil.h>
#include <libswscale/swscale.h>
#include <libavcodec/avcodec.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libavutil/time.h>
#include <libswresample/swresample.h>
}
class Pusher {
public:
Pusher(const SdpInfo &p_SdpInfo);
~Pusher();
int WriteFrame(const int p_nFrameType,const uint8_t *p_frame_data, const int p_frame_len);
private:
bool init();
static void ffLogCallback(void *ptr, int level, const char *fmt, va_list vl);
uint64_t select_channel_layout(const AVCodec *codec);
int select_sample_rate(const AVCodec *codec);
void release();
void sendFifoMsg(const SdpInfo &p_objSdpInfo);
private:
AVFormatContext *m_ofmt_ctx;
struct SwrContext *aac_swr_ctx;
AVCodecContext *pAcodecContext;
AVCodecContext* alaw_codecContext;
int m_audioIdx;
int m_videoIdx;
AVPacket m_pkt;
int m_writeFailedTime;
private:
bool m_bIsInitOK;
SdpInfo m_SdpInfo;
};
#endif
|
cd4f47d16f6ec0847159cf20cb0aaa55
|
{
"intermediate": 0.44234588742256165,
"beginner": 0.3449488878250122,
"expert": 0.21270522475242615
}
|
10,521
|
How would I go about creating active frames for my hitbox part on roblox studios
|
2466dd8c5bf4358dd9063e8001c32e2f
|
{
"intermediate": 0.39929503202438354,
"beginner": 0.1621910184621811,
"expert": 0.4385139048099518
}
|
10,522
|
请帮我完善代码
push.cpp:
#include "Pusher.h"
#include <iostream>
#include "Common/config.h"
#include "appPublic.h"
#include "FifoMsg.h"
using namespace std;
using namespace mediakit;
using namespace toolkit;
enum AVCodeConst {
AV_CODER_NONE = 0,
AV_VIDEO_CODER_H264 = 1,
AV_VIDEO_CODER_HEVC = 2,
AV_AUDIO_CODER_AAC = 3
};
enum EnumFrameType {
FRAME_TYPE_VIDEO = 0,
FRAME_TYPE_AUDIO = 1,
};
#define PUSH_FIELD "push."
const string kEnableAAC2G711A = PUSH_FIELD"EnableAAC2G711A";
#define MAX_WRITE_FAILED_TIME (10)
Pusher::Pusher(const SdpInfo &p_SdpInfo)
:m_bIsInitOK(false)
,m_SdpInfo(p_SdpInfo)
,m_audioIdx(0)
,m_videoIdx(0)
,m_ofmt_ctx(NULL)
,aac_swr_ctx(NULL)
,pAcodecContext(NULL)
,alaw_codecContext(NULL)
,m_writeFailedTime(0){
int nInitFlag = init();
if (nInitFlag == 0){
m_bIsInitOK = true;
InfoL<<"create pusher success,dev:"<<m_SdpInfo.szPlayUrl;
}
else{
nInitFlag = false;
InfoL<<"create pusher failed,dev:"<<m_SdpInfo.szPlayUrl;
release();
return;
}
}
Pusher::~Pusher(){
release();
InfoL<<m_SdpInfo.szPlayUrl<<" pusher is released";
}
void Pusher::release(){
if(m_ofmt_ctx == NULL)
return;
av_write_trailer(m_ofmt_ctx);
if (!(m_ofmt_ctx->flags & AVFMT_NOFILE)) {
avio_close(m_ofmt_ctx->pb);
}
avformat_free_context(m_ofmt_ctx);
m_ofmt_ctx = NULL;
if(pAcodecContext){
avcodec_free_context(&pAcodecContext);
pAcodecContext = NULL;
}
if (alaw_codecContext){
avcodec_free_context(&alaw_codecContext);
alaw_codecContext = NULL;
}
}
void Pusher::ffLogCallback(void *ptr, int level, const char *fmt, va_list vl)
{
if (level > av_log_get_level())
return;
char temp[1024];
vsprintf(temp, fmt, vl);
size_t len = strlen(temp);
if (len > 0 && len < 1024&&temp[len - 1] == '\n')
{
temp[len - 1] = '\0';
}
DebugL << (char *)temp;
}
/* select layout with the highest channel count */
uint64_t Pusher::select_channel_layout(const AVCodec *codec)
{
if (!codec)
return AV_CH_LAYOUT_STEREO;
const uint64_t *p;
uint64_t best_ch_layout = 0;
int best_nb_channels = 0;
if (!codec->channel_layouts)
return AV_CH_LAYOUT_STEREO;
p = codec->channel_layouts;
while (*p) {
int nb_channels = av_get_channel_layout_nb_channels(*p);
if (nb_channels > best_nb_channels) {
best_ch_layout = *p;
best_nb_channels = nb_channels;
}
p++;
}
return best_ch_layout;
}
int Pusher::select_sample_rate(const AVCodec *codec)
{
if (!codec)
return 44100;
const int *p;
int best_samplerate = 0;
if (!codec->supported_samplerates)
return 44100;
p = codec->supported_samplerates;
while (*p) {
if (!best_samplerate || abs(44100 - *p) < abs(44100 - best_samplerate))
best_samplerate = *p;
p++;
}
return best_samplerate;
}
bool Pusher::init(){
if (strlen(m_SdpInfo.szPlayUrl) <= 0){
ErrorL<<"输出URL不能为空";
return false;
}
av_register_all();
avformat_network_init();
av_log_set_level(AV_LOG_INFO);
av_log_set_callback(ffLogCallback);
AVDictionary *pDict = NULL;
int ret = avformat_alloc_output_context2(&m_ofmt_ctx, NULL, m_SdpInfo.szFmt, m_SdpInfo.szPlayUrl);
if (ret < 0){
ErrorL<<"avformat_alloc_output_context2 failed, output:"<<m_SdpInfo.szFmt;
return -1;
}
AVCodec *pEnCodeV = NULL;
if (m_SdpInfo.nVideoCodec == AV_VIDEO_CODER_H264)
pEnCodeV = avcodec_find_encoder(AV_CODEC_ID_H264);
else
pEnCodeV = avcodec_find_encoder(AV_CODEC_ID_H265);
if(pEnCodeV)
InfoL<<"The video codec is:"<<pEnCodeV->name;
//设置视频输出格式
AVStream *pStreamO = avformat_new_stream(m_ofmt_ctx, pEnCodeV);
pStreamO->id = m_ofmt_ctx->nb_streams - 1;
pStreamO->codec->codec_tag = 0;
pStreamO->codec->width = 1280;
pStreamO->codec->height = 1080;
pStreamO->codec->pix_fmt = AV_PIX_FMT_YUV420P;
AVRational tb{ 1, 90000 };
pStreamO->time_base = tb;
AVRational fr{ 25, 1 };
pStreamO->r_frame_rate = fr; //(tbr)
pStreamO->avg_frame_rate = fr; //(fps)
AVRational sar{ 1, 1 };
pStreamO->sample_aspect_ratio = sar;
AVRational ctb{ 1, 25 };
pStreamO->codec->time_base = ctb;
pStreamO->codec->sample_aspect_ratio = sar;
pStreamO->codec->gop_size = 12;
if (m_ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER) {
pStreamO->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
if (avcodec_open2(pStreamO->codec, pEnCodeV, NULL) != 0) {
ErrorL << "avcodec_open2 video error";
}
AVStream *pAStreamO = NULL;
bool bEnableAAC2G711AFlag = mINI::Instance()[kEnableAAC2G711A];
if (bEnableAAC2G711AFlag){
//设置音频输出格式
AVCodec *pEnCodeA = avcodec_find_encoder(::AV_CODEC_ID_PCM_ALAW);
pAStreamO = avformat_new_stream(m_ofmt_ctx, pEnCodeA);
pAStreamO->id = m_ofmt_ctx->nb_streams - 1;
pAStreamO->codec->codec_tag = 0;
pAStreamO->codec->sample_fmt = ::AV_SAMPLE_FMT_S16;
pAStreamO->codec->channel_layout = AV_CH_LAYOUT_MONO;
pAStreamO->codec->sample_rate = 8000;
pAStreamO->codec->channels = 1;
pAStreamO->codec->frame_size = 160/2;
if (avcodec_open2(pAStreamO->codec, pEnCodeA, NULL) != 0) {
ErrorL<<"avcodec_open2 audio error" ;
}
}else{
AVCodec *pEnCodeA = avcodec_find_encoder(::AV_CODEC_ID_AAC);
AVStream *pAStreamO = avformat_new_stream(m_ofmt_ctx, pEnCodeA);
pAStreamO->id = m_ofmt_ctx->nb_streams - 1;
pAStreamO->codec->codec_tag = 0;
pAStreamO->codec->sample_fmt = ::AV_SAMPLE_FMT_FLTP;
pAStreamO->codec->channel_layout = select_channel_layout(pAStreamO->codec->codec);
pAStreamO->codec->sample_rate = select_sample_rate(pAStreamO->codec->codec);
pAStreamO->codec->channels = ::av_get_channel_layout_nb_channels(pAStreamO->codec->channel_layout);
if (avcodec_open2(pAStreamO->codec, pEnCodeA, NULL) != 0) {
ErrorL<<"avcodec_open2 audio error" ;
}
}
if (!(m_ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
ret = avio_open(&m_ofmt_ctx->pb, m_SdpInfo.szPlayUrl, AVIO_FLAG_WRITE);
}
if (0 == strcasecmp(m_SdpInfo.szFmt, "rtsp")){
av_dict_set(&pDict, "rtsp_transport", "tcp", 0);
av_dict_set(&pDict, "muxdelay", "0.1", 0);
}
ret = avformat_write_header(m_ofmt_ctx, &pDict);
av_dump_format(m_ofmt_ctx, 0, m_SdpInfo.szPlayUrl, 1);
if (!bEnableAAC2G711AFlag){
InfoL<<"新建国标流推流器,设备:"<<m_SdpInfo.szPlayUrl;
return ret;
}
InfoL<<"使能AAC转G711A,初始化AAC解码器和G711A编码器";
//以下为aac->alaw相关
//aac音频格式
int64_t in_channel_layout = AV_CH_LAYOUT_STEREO;
enum AVSampleFormat in_sample_fmt = AV_SAMPLE_FMT_FLTP;
int in_sample_rate = 44100;
int in_channels = 2;
AVRational in_timeBase = {1,44100};
//alaw音频格式
uint64_t out_channel_layout = AV_CH_LAYOUT_MONO;
enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
int out_sample_rate = 8000;
int out_nb_samples = 160;
int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);
//aac->alaw重采样器
aac_swr_ctx = swr_alloc();
aac_swr_ctx = swr_alloc_set_opts(aac_swr_ctx, out_channel_layout, out_sample_fmt, out_sample_rate,in_channel_layout, in_sample_fmt, in_sample_rate, 0, NULL);
swr_init(aac_swr_ctx);
//初始化AAC解码器
AVCodec *pAcodec = avcodec_find_decoder(AV_CODEC_ID_AAC);
pAcodecContext = avcodec_alloc_context3(pAcodec);
pAcodecContext->sample_rate = in_sample_rate;
pAcodecContext->channels = in_channels;
pAcodecContext->sample_fmt = in_sample_fmt;
pAcodecContext->time_base = in_timeBase;
avcodec_open2(pAcodecContext, pAcodec, NULL);
//初始化alaw编码器
AVCodec* alaw_codec = avcodec_find_encoder(AV_CODEC_ID_PCM_ALAW);
alaw_codecContext = avcodec_alloc_context3(alaw_codec);
alaw_codecContext->codec_type = AVMEDIA_TYPE_AUDIO;
alaw_codecContext->sample_rate = 8000;
alaw_codecContext->channels = 1;
alaw_codecContext->sample_fmt = out_sample_fmt; // ALAW编码需要16位采样,U8在目前ff版本不支持
alaw_codecContext->channel_layout = AV_CH_LAYOUT_MONO;
alaw_codecContext->height = pStreamO->codec->height;
alaw_codecContext->width = pStreamO->codec->width;
alaw_codecContext->codec_id = AV_CODEC_ID_PCM_ALAW;
alaw_codecContext->bit_rate = 64000;
//alaw_codecContext->frame_size = 160/2;
ret = avcodec_open2(alaw_codecContext, alaw_codec, NULL);
if (ret < 0)
ErrorL<<"avcodec_open2 alaw_codecContext failed";
else
InfoL<<"avcodec_open2 alaw_codecContext ok";
av_init_packet(&m_pkt);
return ret;
}
int Pusher::WriteFrame(const int p_nFrameType,const uint8_t *p_frame_data, const int p_frame_len){
if (!m_bIsInitOK)
return -1;
int64_t currentTimeStamp = 0;
if (p_nFrameType == FRAME_TYPE_VIDEO) {
currentTimeStamp = m_videoIdx * 3600;
if(strlen(m_SdpInfo.szFileName) > 0 && (m_videoIdx % 25 == 0)){
int ndownloadProgress = (int)(m_videoIdx * 100 / m_SdpInfo.nHistoryTotalFrameNum);
if(ndownloadProgress >= 100){
ndownloadProgress = 100;
}
InfoL<<"download file:"<<m_SdpInfo.szFileName<<" download progress:"<<ndownloadProgress;
m_SdpInfo.nDownloadProgress = ndownloadProgress;
m_SdpInfo.nEventType = DevProcessType_upload_download_progress;
sendFifoMsg(m_SdpInfo);
}
m_videoIdx++;
}
if (p_nFrameType == FRAME_TYPE_AUDIO) {
currentTimeStamp= m_audioIdx * 1024;
m_audioIdx++;
}
AVPacket pkt;
av_init_packet(&pkt);
pkt.data = (uint8_t*)p_frame_data;
pkt.size = p_frame_len;
pkt.pts = currentTimeStamp;
pkt.dts = currentTimeStamp;
pkt.duration = 3600;
pkt.pos = -1;
pkt.stream_index = p_nFrameType;
int ret = -1;
if (p_nFrameType == FRAME_TYPE_VIDEO) {
//std::cout<<"=====lgo 1==="<<std::endl;
if (m_ofmt_ctx){
ret = av_write_frame(m_ofmt_ctx, &pkt);
//std::cout<<"=====lgo 2===ret:"<<ret<<std::endl;
if(ret < 0){
m_writeFailedTime++;
if (MAX_WRITE_FAILED_TIME < m_writeFailedTime || ret == -32){
m_SdpInfo.nEventType = DevProcessType_stop_stream;
sendFifoMsg(m_SdpInfo);
return -1;
}
}
m_writeFailedTime = 0;
}
av_packet_unref(&pkt);
return ret;
}
bool bEnableAAC2G711AFlag = mINI::Instance()[kEnableAAC2G711A];
if (!bEnableAAC2G711AFlag){
if (m_ofmt_ctx){
ret = av_write_frame(m_ofmt_ctx, &pkt);
}
av_packet_unref(&pkt);
return ret;
}
if (p_nFrameType == FRAME_TYPE_AUDIO) {
int got_frame;
AVFrame *pAACFrame=av_frame_alloc();
ret = avcodec_decode_audio4(pAcodecContext, pAACFrame, &got_frame, &pkt);
if(ret < 0){
ErrorL<<"avcodec_decode_audio4 failed";
return -1;
}else if (got_frame){
//解码aac成功后,重采样得到alaw数据
uint64_t out_channel_layout = AV_CH_LAYOUT_MONO;
enum AVSampleFormat out_sample_fmt = AV_SAMPLE_FMT_S16;
int out_nb_samples = 160;
int out_channels = av_get_channel_layout_nb_channels(out_channel_layout);
int alaw_buffer_size = av_samples_get_buffer_size(NULL, out_channels, out_nb_samples, out_sample_fmt, 1);
//44.1KHZ,16bit,2声道的pcm转换成pcma 8khz,16bit,1声道
uint8_t *alaw_buffer = (uint8_t *)av_malloc(pAACFrame->nb_samples);
swr_convert(aac_swr_ctx, &alaw_buffer, alaw_buffer_size, (const uint8_t **)pAACFrame->data, pAACFrame->nb_samples);
//构造alawFrame
AVFrame * alawFrame = av_frame_alloc();
//设置AVFrame的基本信息
alawFrame->sample_rate = 8000;
alawFrame->channels = 1;
alawFrame->format = AV_SAMPLE_FMT_S16;
alawFrame->channel_layout = AV_CH_LAYOUT_MONO;
alawFrame->nb_samples = alaw_buffer_size/2;
av_frame_get_buffer(alawFrame, 0);
memcpy(alawFrame->data[0], alaw_buffer, alaw_buffer_size);
int got_packet = 0;
AVPacket* packet = av_packet_alloc();
av_init_packet(packet);
packet->data = alaw_buffer;
packet->size = alaw_buffer_size;
packet->stream_index = 1;
ret = avcodec_encode_audio2(alaw_codecContext, packet, alawFrame, &got_packet);
av_frame_free(&alawFrame);
if (ret < 0){
ErrorL<<"avcodec_encode_audio2 failed";
}else if (got_packet){
//成功编码出音频包后,写输出流
int nbSamplesPerPacket = 160;
int sampleRate = 8000;
packet->pts = (m_audioIdx-1) *160;
packet->dts = packet->pts;
packet->duration = 160;
packet->stream_index = 1;
packet->pos = 1;
ret = ::av_write_frame(m_ofmt_ctx, packet);
}
av_packet_free(&packet);
av_free(alaw_buffer);
}
av_frame_free(&pAACFrame);
}
av_packet_unref(&pkt);
return 0;
}
void Pusher::sendFifoMsg(const SdpInfo &p_objSdpInfo){
if (p_objSdpInfo.nSrcPort <= 0 || strlen(p_objSdpInfo.szDevid) <= 0)
return;
char szFifoName[128] = {0};
snprintf(szFifoName, sizeof(szFifoName), FORMAT_PORT_DISPATCH_THREAD_MSG_FIFO,p_objSdpInfo.nSrcPort);
std::string strJson;
SdpParse::makeFifoMsgJson(p_objSdpInfo, strJson);
DebugL<<"send msg, fifo:"<<szFifoName<<", msg:"<<strJson;
FifoMsg::fifo_send_msg(szFifoName, strJson);
}
push.h
#ifndef PUSHER_H
#define PUSHER_H
#include <string>
#include <string.h>
#include "SdpParse.h"
extern "C" {
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libavutil/avutil.h>
#include <libswscale/swscale.h>
#include <libavcodec/avcodec.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libavutil/time.h>
#include <libswresample/swresample.h>
}
class Pusher {
public:
Pusher(const SdpInfo &p_SdpInfo);
~Pusher();
int WriteFrame(const int p_nFrameType,const uint8_t *p_frame_data, const int p_frame_len);
private:
bool init();
static void ffLogCallback(void *ptr, int level, const char *fmt, va_list vl);
uint64_t select_channel_layout(const AVCodec *codec);
int select_sample_rate(const AVCodec *codec);
void release();
void sendFifoMsg(const SdpInfo &p_objSdpInfo);
private:
AVFormatContext *m_ofmt_ctx;
struct SwrContext *aac_swr_ctx;
AVCodecContext *pAcodecContext;
AVCodecContext* alaw_codecContext;
int m_audioIdx;
int m_videoIdx;
AVPacket m_pkt;
int m_writeFailedTime;
private:
bool m_bIsInitOK;
SdpInfo m_SdpInfo;
};
#endif
要求:
1.请找出上面例子内存泄露的地方有哪些?并且改善
2.请用c11,c++完善
3.请找出上面错误的地方有哪些?并且改善
|
d0d20a00b022bf5871e292592b647b20
|
{
"intermediate": 0.3305986821651459,
"beginner": 0.3153392970561981,
"expert": 0.35406193137168884
}
|
10,523
|
"% Enter the dry and wet temperatures in Celsius
Tdry = input('Enter the dry temperature in Celsius: ');
Twet = input('Enter the wet temperature in Celsius: ');
% Constants
a = 17.27;
b = 237.7;
% Calculations
alpha = ((a*Tdry)/(b+Tdry))+log((Twet+(237.7))/(Tdry+(237.7)));
Tdew = (b*alpha)/(a-alpha);
RH = 100*(exp((a*Tdry)/(b+Tdry)-a*Tdew/(b+Tdew)));
% Display the result
fprintf('Relative Humidity is %.2f%%\n', RH);"
what is the answer for 19.8 dry bulb and 13.7 wet bulb
|
f4a0b899211f74259c6c379aa5f8ecad
|
{
"intermediate": 0.33514654636383057,
"beginner": 0.33602914214134216,
"expert": 0.32882431149482727
}
|
10,524
|
create mindmap for full stack development in markdown format
|
df92ece62adedbdd52c59e32e7b52f13
|
{
"intermediate": 0.5466249585151672,
"beginner": 0.12720531225204468,
"expert": 0.3261697292327881
}
|
10,525
|
Must have arch packages for programmers
|
14c1e13e662a073f4e0e6c500973c55d
|
{
"intermediate": 0.6520853042602539,
"beginner": 0.19561649858951569,
"expert": 0.15229816734790802
}
|
10,526
|
Write Api bcscan , which will display which method id was used in the transaction
|
cfff80260df65ab88857ff538d652d09
|
{
"intermediate": 0.5341086387634277,
"beginner": 0.15025241672992706,
"expert": 0.3156388998031616
}
|
10,527
|
write a qr code generator using python
|
611143d6ba6da07c10d851b71e6f0c0d
|
{
"intermediate": 0.23793604969978333,
"beginner": 0.18673588335514069,
"expert": 0.5753281116485596
}
|
10,528
|
Warning: Possibly SSL/TLS issue. Update or install Python SSL root certificates (2048-bit or greater) supplied in Python folder or https://pypi.org/project/certifi/ and try again.
error: installation failed!
怎么解决
|
a35ca0eb68f037ca38a4b505c4368903
|
{
"intermediate": 0.32561439275741577,
"beginner": 0.22244428098201752,
"expert": 0.4519413113594055
}
|
10,529
|
I have created two mysql tables with below sql:
CREATE TABLE sg_businesstype (
businesstypeid int not null auto_increment,
businesstype varchar(80),
primary key (businesstypeid)
);
insert into sg_businesstype ( businesstype ) values
('Buying Agent'), ('Dealer / Reseller'), ('Distributor'), ('Manufacturer / OEM'), ('Not Known'), ('Retailer'), ('Service Provider');
CREATE TABLE sg_users (
sgid int not null auto_increment,
email varchar(80) not null,
name varchar(60) not null,
usertype int not null default 1,
company varchar(80) null,
tel varchar(25) null,
mobile varchar(25) null,
businesstypeid int null,
newsletter boolean default false,
status boolean default true,
rating int default 0,
registerdate timestamp not null default CURRENT_TIMESTAMP,
logo varchar(255) null,
primary key (sgid),
foreign key (businesstypeid) references sg_businesstype (businesstypeid)
);
I have make a php file and use PDO connected to database and the database handler is $DB. Please give me bootstrap form to maintain table sg_users.
|
6f49a4ed9a6385ee0f90ba81c52488f1
|
{
"intermediate": 0.4074879586696625,
"beginner": 0.2985602915287018,
"expert": 0.29395171999931335
}
|
10,530
|
write the code for matlab to calculate Relative humidity by using dry bulb and wet bulb temperature
|
da4deae4cecd27a6616e8a13dc2cf1a8
|
{
"intermediate": 0.4411093294620514,
"beginner": 0.09738044440746307,
"expert": 0.4615102708339691
}
|
10,531
|
function RH = calculate_RH(Tdry, Twet, P)
% Tdry: dry bulb temperature in °C
% Twet: wet bulb temperature in °C
% P: atmospheric pressure in kPa
% Constants for water vapor pressure calculation
Tn = 273.15; % Triple point of water
a = 6.116441; % Constant a
b = 17.502; % Constant b
c = 240.97; % Constant c
% Calculate saturation vapor pressure
gamma = b * Tdry / (c + Tdry);
es_0 = a * 10^(gamma);
% Correct for atmospheric pressure
pws = es_0 * (1.0007 + 3.46e-6*P); % Saturation vapor pressure at given pressure
% Calculate vapor pressure from wet bulb temperature
ew = a * 10^(b * Twet /(c + Twet));
% Calculate relative humidity
RH = ew / pws * 100;
end
you didn't use Tn to calculate Relative humidity
|
736f8de4bcd5b3a7879471a0474d8d34
|
{
"intermediate": 0.3313707113265991,
"beginner": 0.422577828168869,
"expert": 0.24605144560337067
}
|
10,532
|
I have a decompiled cocos2d project, how can I turn it into a real project
|
a2369b1d6493d716b723b6668bcd0144
|
{
"intermediate": 0.5427483916282654,
"beginner": 0.23166713118553162,
"expert": 0.2255844920873642
}
|
10,533
|
whats the command for running a migration inside migrations folder with a name
|
0c6ed6b3cd1d644c72ce265e309ee6ec
|
{
"intermediate": 0.37786880135536194,
"beginner": 0.2804463803768158,
"expert": 0.3416847884654999
}
|
10,534
|
I want you to write Excel function to calculate unique values in a column. For instance, for this set:
A-1
A2
A2
A-1
A3
It should return 3. Also it should have a parameter for checking if first row is header or not.
Also give me instruction on how to embed this function into Excel so that I could use it like any other function (type it in cell, select column with data, etc.)
|
9e09fd103c6b3b02936c41a454931f43
|
{
"intermediate": 0.47276413440704346,
"beginner": 0.3807249665260315,
"expert": 0.14651082456111908
}
|
10,535
|
do zoom ability in here, to zoom in and out inside that cube grid with mouse wheel. also, do some rotation on all axis by mous dragging in empty space, set flag for auto-rotation to false. also, try to fit the entire 3d matrix grid on full canvas automatically, independent of gridSize or gridSpacing, with some small empty space around borders: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
92df54a932dce153aadb48356d334ab0
|
{
"intermediate": 0.42651790380477905,
"beginner": 0.36183467507362366,
"expert": 0.21164743602275848
}
|
10,536
|
Generate a survey report on college students' love values, with a total of 47 respondents. The content of the report should not be less than 2000 words, and it is best to include the chart of the survey results
|
41aca927e1630e2bfd9ffeca386b759a
|
{
"intermediate": 0.3117786943912506,
"beginner": 0.3986617922782898,
"expert": 0.289559543132782
}
|
10,537
|
do zoom ability in here, to zoom in and out inside that cube grid with mouse wheel. also, do some rotation on all axis by mous dragging in empty space, set flag for auto-rotation to false. also, try to fit the entire 3d matrix grid on full canvas automatically, independent of gridSize or gridSpacing, with some small empty space around borders: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
49494f6a109544f8ec6414314ddeda2a
|
{
"intermediate": 0.42651790380477905,
"beginner": 0.36183467507362366,
"expert": 0.21164743602275848
}
|
10,538
|
Write a code that will allow you to determine if liquidity has been added to a particular token. Use APIKey
|
c4223382156c6fd6d6710acf32b8812e
|
{
"intermediate": 0.7346372604370117,
"beginner": 0.11386577039957047,
"expert": 0.15149690210819244
}
|
10,539
|
create a VBA code in order to have a full comprehensive powerpoint presentation about the CRM vision for a private bank with a dedicated product roadmap. Ensure to create 10 different slides with the most modern powerpoint layout.
|
bdd0972e0bdd812c1383642a867ba21f
|
{
"intermediate": 0.21981003880500793,
"beginner": 0.45498690009117126,
"expert": 0.3252030313014984
}
|
10,540
|
#include <iostream>
#include <vector>
using namespace std;
class Weapon {
protected:
int damage;
int uses;
public:
Weapon(int damage, int uses) {
this->damage = damage;
this->uses = uses;
}
virtual int getDamage() = 0;
virtual void decreaseUses() = 0;
bool isUsable() {
return (uses > 0);
}
};
class Knife : public Weapon {
float length;
public:
Knife(int damage, int uses, float length) : Weapon(damage, uses) {
this->length = length;
}
int getDamage() override {
return damage * length;
}
void decreaseUses() override {
uses--;
}
};
class Bow : public Weapon {
int arrows;
public:
Bow(int damage, int uses, int arrows) : Weapon(damage, uses) {
this->arrows = arrows;
}
int getDamage() override {
return damage * arrows / 2;
}
void decreaseUses() override {
uses -= 2;
}
};
class Unarmed : public Weapon {
int maxHP;
public:
Unarmed(int maxHP) : Weapon(0, -1) {
this->maxHP = maxHP;
}
int getDamage() override {
return maxHP * 0.1;
}
void decreaseUses() override {
maxHP -= maxHP * 0.1;
}
};
class Beast {
protected:
int HP;
int damage;
public:
Beast(int HP, int damage) {
this->HP = HP;
this->damage = damage;
}
virtual void attack(Weapon* weapon) = 0;
bool isDefeated() {
return (HP <= 0);
}
int getDamage() {
return damage;
}
};
class Cow : public Beast {
int numAttacks;
public:
Cow(int HP, int damage, int numAttacks) : Beast(HP, damage) {
this->numAttacks = numAttacks;
}
void attack(Weapon* weapon) override {
if (weapon->isUsable()) {
HP -= weapon->getDamage();
weapon->decreaseUses();
}
if (numAttacks > 0)
numAttacks--;
}
bool isDefeated() {
return (HP <= 0 || numAttacks <= 0);
}
};
class Tiger : public Beast {
public:
Tiger(int HP, int damage) : Beast(HP, damage) {}
void attack(Weapon* weapon) override {
if (weapon->isUsable()) {
HP -= weapon->getDamage();
weapon->decreaseUses();
}
}
};
int main() {
int maxHP;
cin >> maxHP;
int numWeapons;
cin >> numWeapons;
vector<Weapon*> weapons;
for (int i = 0; i < numWeapons; i++) {
int type;
int damage;
int uses;
float param;
cin >> type >> damage >> uses >> param;
Weapon* weapon;
if (type == 1)
weapon = new Knife(damage, uses, param);
else if (type == 2)
weapon = new Bow(damage, uses, static_cast<int>(param));
else if (type == 3)
weapon = new Unarmed(maxHP);
weapons.push_back(weapon);
}
int numBeasts;
cin >> numBeasts;
vector<Beast*> beasts;
for (int i = 0; i < numBeasts; i++) {
int type;
int HP;
int damage;
int numAttacks;
cin >> type >> HP >> damage;
Beast* beast;
if (type == 1) {
cin >> numAttacks;
beast = new Cow(HP, damage, numAttacks);
}
else if (type == 2)
beast = new Tiger(HP, damage);
beasts.push_back(beast);
}
for (size_t i = 0; i < beasts.size(); i++) {
Beast* currentBeast = beasts[i];
for (size_t j = 0; j < weapons.size(); j++) {
Weapon* currentWeapon = weapons[j];
while (!currentBeast->isDefeated() && currentWeapon->isUsable()) {
currentBeast->attack(currentWeapon);
if (!currentBeast->isDefeated()) {
// A Phu receives counter-attack
maxHP -= currentBeast->getDamage();
}
}
}
}
int remainingWeapons = 0;
for (size_t i = 0; i < weapons.size(); i++) {
if (weapons[i]->isUsable())
remainingWeapons++;
}
if (maxHP > 0 && remainingWeapons > 0)
cout << "A Phu chien thang, hp con lai: " << maxHP << ", so vu khi con lai: " << remainingWeapons << endl;
else
cout << "A Phu that bai, so thu du con lai: " << beasts.size()-1 << endl;
return 0;
}
Your code did not pass this test case.
Input (stdin)
100
3
1 20 3 1.5
1 30 2 2
2 3 3 4
3
1 100 3 3
2 40 2
2 10 2
Your Output (stdout)
A Phu that bai, so thu du con lai: 2
Expected Output
A Phu chien thang, hp con lai: 94, so vu khi con lai: 1
Compiler Message
Wrong Answer
|
aebaba761a05c7be2c25af0b25da5d05
|
{
"intermediate": 0.2986426055431366,
"beginner": 0.4141533374786377,
"expert": 0.28720399737358093
}
|
10,541
|
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
def get_method_id(tx_hash, api_key):
URL = 'https://api.bscscan.com/api'
payload = {
"module": "proxy",
"action": "eth_getTransactionByHash",
"txhash": tx_hash,
"apikey": api_key
}
resp = requests.get(URL, params=payload)
response_data = resp.json()
if "result" in response_data:
tx_data = response_data["result"]
if "input" in tx_data:
input_data = tx_data["input"]
method_id = input_data[:10] if input_data.startswith("0x") else None
else:
method_id = None
else:
method_id = None
return method_id
@app.route("/bcscan", methods=["GET"])
def bcscan():
tx_hash = request.args.get("tx_hash", '0x33f0a57b9290493ef9eec8cf6ae6180a2bea525bf29801191f9cad91bdae1ef4')
api_key = "CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS"
if tx_hash:
try:
method_id = get_method_id(tx_hash, api_key)
if method_id:
return jsonify({"method_id": method_id})
else:
return jsonify({"error": "Method ID not found or invalid transaction hash"})
except:
return jsonify({"error": "Failed to fetch transaction data"})
else:
return jsonify({"error": "Invalid parameters"})
if __name__ == "__main__":
app.run(debug=True)
The code above allows you to get the transaction id method. Use another method that will allow you to get the id method through tx_hash. Use APIKey
|
d2f41e4591df388888980559760d024e
|
{
"intermediate": 0.6563502550125122,
"beginner": 0.1673002988100052,
"expert": 0.1763494610786438
}
|
10,542
|
do zoom ability in here, to zoom in and out inside that cube grid with mouse wheel. also, do some rotation on all axis by mous dragging in empty space, set flag for auto-rotation to false. also, try to fit the entire 3d matrix grid on full canvas automatically, independent of gridSize or gridSpacing, with some small empty space around borders. need to preserve that clicking functionality to draw lines on grid. try integrate all described above but preserve mouse clicking on points that draw lines between 3d matrix grid points. output full javascript code, without shortages, but without html code included.: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
fd36c5a251fac773d0a7b9c79a7dd94a
|
{
"intermediate": 0.43943148851394653,
"beginner": 0.348894864320755,
"expert": 0.21167370676994324
}
|
10,543
|
example to use @Mutation from type-graphql
|
033f1e04bc6b3fc57451608b0602f292
|
{
"intermediate": 0.47496405243873596,
"beginner": 0.20019090175628662,
"expert": 0.3248451054096222
}
|
10,544
|
i have a text file contain some lines like D:\car\10.jpg 1 203 192 324 215 how can i write c# software to show rectangle box with opencv and show in a picturebox line by line with button
|
c64477c7cdb3e62bf9e5b9d6a75fb701
|
{
"intermediate": 0.43687909841537476,
"beginner": 0.24768801033496857,
"expert": 0.3154328763484955
}
|
10,545
|
do zoom ability in here, to zoom in and out inside that cube grid with mouse wheel. also, do some rotation on all axis by mous dragging in empty space, set flag for auto-rotation to false. also, try to fit the entire 3d matrix grid on full canvas automatically, independent of gridSize or gridSpacing, with some small empty space around borders. need to preserve that clicking functionality to draw lines on grid. try integrate all described above but preserve mouse clicking on points that draw lines between 3d matrix grid points. output full javascript code, without shortages, but without html code included.: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
aa536ad95bcf031e59a36b5e94abbbef
|
{
"intermediate": 0.43943148851394653,
"beginner": 0.348894864320755,
"expert": 0.21167370676994324
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.