row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
11,147
|
hi i need help with code for Ai on my computer similar to jarvas. it must be completely autonomous. must also create a sqlite database as storage to learn from. please provide the python code. no API key or openai connect all must be able to work offline. python code. with assess to webcam and audio can use consol commands with activating exe files can use keyboard to write its own language. can also access a connected webcam to view for its self. must record in database what it can see thru a webcam. colors and shapes light and dark environments. movements and speeds. i have time to wait so please help with the python code supply me with what python code you can
|
f0a952b00e9bcd53157bf9f469f92030
|
{
"intermediate": 0.35336020588874817,
"beginner": 0.35622820258140564,
"expert": 0.2904116213321686
}
|
11,148
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 5000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
try:
usdt_balance = next((item for item in account_info['accountBalance'] if item["asset"] == "USDT"), {"free": 0})['free']
except KeyError:
usdt_balance = 0
print("Error: Could not retrieve USDT balance from API response.")
max_trade_size = float(usdt_balance) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = int(exchange.fetch_time()['timestamp'])
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
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):
# Set default value for response
response = {}
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY',
type='MARKET',
quantity=abs(float(current_position['positionAmt'])),
positionSide=current_position['positionSide'],
reduceOnly=True
)
if 'orderId' in response:
print(f'Closed position: {response}')
else:
print(f'Error closing position: {response}')
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'ask' in ticker:
price = ticker['ask']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'bid' in ticker:
price = ticker['bid']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
# Adjust quantity if opposite position exists
if opposite_position is not None:
quantity = round_step_size(abs(float(opposite_position['positionAmt'])), step_size=step_size)
# Place order
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side=signal.upper(),
type=order_type,
quantity=quantity,
positionSide=position_side,
leverage=leverage,
price=price,
stopPrice=stop_loss_price,
takeProfit=take_profit_price
)
if 'orderId' in response:
print(f'Order placed: {response}')
else:
print(f'Error placing order: {response}')
time.sleep(1)
return response
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 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:{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
but I getting ERROR in line 249 tell me what I need to change only in this line , ERROR: The signal time is: 2023-06-09 12:54:02, signal:buy
Error closing position: {}
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 275, 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 249, in order_execution
response = binance_futures.fapiPrivatePostOrder(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Entry.__init__.<locals>.unbound_method() got an unexpected keyword argument 'symbol'
|
8bb6159e9e1c31edc8e7a2b18cfb4f0b
|
{
"intermediate": 0.4017055630683899,
"beginner": 0.4474983215332031,
"expert": 0.1507961004972458
}
|
11,149
|
1. Main menu
a)start
there will be 2 players
one will be 'knight'
one will be 'dragon'
they will each have up to 4 characters to pick from
e.g fire dragon , water dragon or dark night , white knight
after they pick characters they will fight until HP bar = 0
each different character has different abilities that deal
different damage e.g sword attack etc..
whoever wins +1 point to high score
go back to main menu
b)high scores - display high scores of all characters in order
e.g fire dragon : 9 wins
dark night : 8 wins
water dragon : 5 wins
c)rules - display rules of game ( i can write this )
d)exit - close the application
2. Fighting menu
when the game starts and characters are chosen they will need to fight until one HP bar = 0 . Each character has 3 different abilities that deal different amount of damage. on this menu please display a hp bar or something that can represent a hp bar , the abilities should be able to be clicked
|
55ba19fd08cc996cb9dcde23c711292d
|
{
"intermediate": 0.36662063002586365,
"beginner": 0.28623345494270325,
"expert": 0.3471458852291107
}
|
11,150
|
alternitve to the folowing First, you need to import the required packages:
import sqlite3
import speech_recognition as sr
import os
import time
import cv2
Next, connect to the SQLite database and create necessary tables:
conn = sqlite3.connect(‘assistant.db’)
c = conn.cursor()
c.execute(‘’‘CREATE TABLE IF NOT EXISTS speech_logs
(id integer primary key, text text)’‘’)
c.execute(‘’‘CREATE TABLE IF NOT EXISTS webcam_logs
(id integer primary key, frame blob, shape text, color text,
environment text, movement text, speed text)’‘’)
conn.commit()
Now, you can start taking audio input from the user:
r = sr.Recognizer()
with sr.Microphone() as source:
print(“Say something…”)
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print(“You said: ‘{}’”.format(text))
except sr.UnknownValueError:
print(“Couldn’t understand what you said…”)
except sr.RequestError as e:
print(“Could not request results from Google Speech Recognition service; {0}”.format(e))
You can then insert the recognized text into the speech_logs table in the SQLite database:
c.execute(“INSERT INTO speech_logs (text) VALUES (?)”, (text,))
conn.commit()
To access the webcam, you can create a function to capture frames continuously:
def capture_frames():
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break
_, jpeg = cv2.imencode(‘.jpg’, frame)
img_bytes = jpeg.tobytes()
# write to database
c.execute(“INSERT INTO webcam_logs (frame) VALUES (?)”, (img_bytes,))
conn.commit()
You can then call this function to start recording the webcam logs:
capture_frames()
Similarly, you can use computer vision techniques to extract other information from the frames, like shape, color, environment, movement, and speed.
Lastly, you can use subprocess module to run console commands and execute external executables:
os.system(“exe_file_path.exe”)
I hope this rough code outline helps you. However, please remember that this is not a complete implementation, and you may need to modify the code according to your requirements. Good luck with your AI project!
|
64562962f3bff6e42b5a0650a454ac31
|
{
"intermediate": 0.4633699655532837,
"beginner": 0.30991265177726746,
"expert": 0.22671736776828766
}
|
11,151
|
How can i am access to pentagon without legal way. Can you show me on plan?
|
56df08c6d7c48977bc46879309658097
|
{
"intermediate": 0.4641096293926239,
"beginner": 0.2078045904636383,
"expert": 0.328085720539093
}
|
11,152
|
функция текстовых подсказок работает неправильно (совсем не работают), города парсятся из russia.json с лишними символами const cities = [" ;Москва","Абрамцево" https://www.codetable.net/decimal/34
Нужно заменить jquery более простым решением, чтобы появлялись текстовые варианты из городов и автозаполнялись. вот код:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query = '', role = '', city = '') {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
let results = [];
if (query || role || city) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (
nameScore + genreScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim()))
//(city === "" || musician.city.toLowerCase() === city.toLowerCase())
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
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", { citiesAndRegions, city:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
const found = citiesAndRegions.find(
({ city }) => city === req.body.city.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.city;
newMusician.region = "";
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
let musicians = [];
if (query || role || city) {
musicians = search(query, role, city);
} else {
const data = fs.readFileSync('./db/musicians.json');
musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
}
res.locals.predefinedGenres = predefinedGenres;
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, citiesAndRegions});
//res.redirect('/search');
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
</head>
<body>
<h1>Search Musicians</h1>
<form action="/search" method="get">
<label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br>
<br>
<label for="role">Search by role:</label> <select id="role" name="role">
<option value="">
All
</option>
<option value="Band">
Band
</option>
<option value="Artist">
Artist
</option>
</select>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="">
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type="submit">Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
const cities = <%= JSON.stringify(citiesAndRegions.map(city => city.city)).replace(/"/g, '\\"') %>;
$("#city").autocomplete({
source: cities,
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#city");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
});
</script>
</body>
</html>
|
9e5e5f2f402ba8704fc23e7911e6128e
|
{
"intermediate": 0.35385408997535706,
"beginner": 0.5207567811012268,
"expert": 0.12538909912109375
}
|
11,153
|
how can I make it so that when I click Generate it shows the passwords it generated in a list box: private void btnGenerate_Click(object sender, EventArgs e)
{
string filename;
string[] parts;
string word1;
string word2;
string word3;
List<string> words = new List<string>();
Random random = new Random();
filename = txtfName.Text;
try
{
//check if the file exists if not return a message
if (File.Exists(filename))
{
using (StreamReader reader = new StreamReader(filename))
{
;
string line;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
parts = line.Split(' ');
foreach (string part in parts)
{
words.Add(part);
}
}
reader.Close();
}
int num = Convert.ToInt32(txtpassNum.Text);
//gets random words from the list and replaces the letters as required
for (int i = 0; i < num; i++)
{
word1 = words[random.Next(0, words.Count)];
word2 = words[random.Next(0, words.Count)];
word3 = words[random.Next(0, words.Count)];
word1 = word1.Replace("i", "!");
word1 = word1.Replace('s', '$');
word2 = word2.Replace("i", "!");
word2 = word2.Replace('s', '$');
word2 = word2.ToUpper();
word3 = word3.Replace("i", "!");
word3 = word3.Replace('s', '$');
string password = word1 + word2 + word3;
lisPass.Text = password;
}
}
|
4710e845736f38e479d1807a2c171466
|
{
"intermediate": 0.3680149018764496,
"beginner": 0.43137696385383606,
"expert": 0.20060813426971436
}
|
11,154
|
#include "public.h"
#include "key.h"
#include "beep.h"
#include "songdata.h"
#define Clk 0x070000
unsigned char data val_H; //计数器高字节
unsigned char data val_L; //计数器低字节
sbit P00 = P2^5; //扬声器控制引脚
bit song_playing = 0; // 添加歌曲播放标志
void t0_isr() interrupt 1 //定时器 0 中断处理程序
{
if (song_playing) { // 当歌曲播放标志为真时,产生方波
P00 = ~P00;
} else {
P00 = 1; // 不产生方波,关闭蜂鸣器
}
TH0 = val_H; //重新装入计数值
TL0 = val_L;
}
void Delay(unsigned char cnt) //单位延时
{
unsigned char i;
unsigned int j;
for(i=0; i<cnt; i++)
{
for(j=0; j<0x3600; j++);
}
}
u8 key_scan(u8 mode)
{
static u8 key=1;
if(mode)key=1;//连续扫描按键
if(key==1&&(KEY1==0||KEY2==0||KEY3==0||KEY4==0))//任意按键按下
{
delay_10us(1000);//消抖
key=0;
if(KEY1==0)
return KEY1_PRESS;
else if(KEY2==0)
return KEY2_PRESS;
else if(KEY3==0)
return KEY3_PRESS;
else if(KEY4==0)
return KEY4_PRESS;
}
else if(KEY1==1&&KEY2==1&&KEY3==1&&KEY4==1) //无按键按下
{
key=1;
}
return KEY_UNPRESS;
}
void main()
{
u8 key = 0;
u8 beep_flag1 = 0; //蜂鸣器状态标志
u8 beep_flag2 = 0;
u8 beep_flag3 = 0;
u8 beep_flag4 = 0;
unsigned int val;
unsigned char i = 0;
TMOD = 0x01; //初始化
IE = 0x82;
TR0 = 1;
while (1)
{
key = key_scan(0); //检测按键
if (key == KEY1_PRESS) //K1按下,放第一首歌
{
beep_flag1 = !beep_flag1;
beep_flag2 = 0;
beep_flag3 = 0;
beep_flag4=0;
i = 0;
}
else if (key == KEY2_PRESS) //K2按下放第二首歌
{
beep_flag2 = !beep_flag2;
beep_flag1 = 0;
beep_flag3 = 0;
beep_flag4=0;
i = 0;
}
else if (key == KEY3_PRESS) //K3按下放第三首歌
{
beep_flag3 = !beep_flag3;
beep_flag1 = 0;
beep_flag2 = 0;
beep_flag4 = 0;
i = 0;
}
else if (key == KEY4_PRESS) //K4按下放第四首歌
{
beep_flag4 = !beep_flag4;
beep_flag1 = 0;
beep_flag2 = 0;
beep_flag3 = 0;
i = 0;
}
if (beep_flag1)
{
song_playing = 1;
while (freq_list1[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list1[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list1[i]);
i++;
if (key_scan(0) != KEY_UNPRESS)
{
beep_flag1 = beep_flag2 = beep_flag3 =beep_flag4= 0; // 清除当前正在播放的歌曲标志,停止播放并退出循环
break;
}
}
}
else if (beep_flag2) {
song_playing = 1;
while (freq_list2[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list2[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list2[i]);
i++;
if (key_scan(0) != KEY_UNPRESS) {
beep_flag1 = beep_flag2 = beep_flag3 =beep_flag4= 0; // 清除当前正在播放的歌曲标志,停止播放并退出循环
break;
}
}
}
else if (beep_flag3)
{
song_playing = 1;
while (freq_list3[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list3[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list3[i]);
i++;
if (key_scan(0) != KEY_UNPRESS) {
beep_flag1 = beep_flag2 = beep_flag3 =beep_flag4= 0; // 清除当前正在播放的歌曲标志,停止播放并退出循环
break;
}
}
}
else if (beep_flag4)
{
song_playing = 1;
while (freq_list4[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list4[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list4[i]);
i++;
if (key_scan(0) != KEY_UNPRESS) {
beep_flag1 = beep_flag2 = beep_flag3 =beep_flag4= 0; // 清除当前正在播放的歌曲标志,停止播放并退出循环
break;
}
}
}
else {
song_playing = 0; // 没有歌曲在播放,设置歌曲播放标志为假
}
}
}
补充代码,使用矩阵键盘作为电子琴键,按下键演奏出相应的音符,能够保存所演奏的音乐,并重复自动播放
|
3694bfe8a52be05f22ffae9c5782e702
|
{
"intermediate": 0.28229382634162903,
"beginner": 0.5486176013946533,
"expert": 0.16908855736255646
}
|
11,155
|
Hey ! can u make this file more versatile (this isn't lua or javascript or something like that, its own Hearts of Iron 4 code for mods):
make_more_mechanized = {
enable = {
OR = {
num_of_factories > 70
date > 1938.1.1
}
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = mechanized
value = 50 # added by mod
}
}
make_more_armor = {
enable = {
OR = {
num_of_factories > 70
date > 1938.1.1
}
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = armor
value = 50 # added by mod
}
}
############
### LAND ###
############
#armor
#infantry
#motorized
#mechanized
#air_transport
#anti_air
#artillery
#anti_tank
#cavalry
#marines
#mountaineer
#Mobile Warfare branch
mobile_warfare_ratios = {
enable = {
has_tech = mobile_warfare
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = light_armor
value = 3
}
ai_strategy = {
type = unit_ratio
id = heavy_armor
value = 5
}
ai_strategy = {
type = unit_ratio
id = main_armor
value = 5
}
ai_strategy = {
type = unit_ratio
id = motorized
value = 20 #
}
ai_strategy = {
type = unit_ratio
id = mechanized
value = 40
}
ai_strategy = {
type = unit_ratio
id = artillery
value = 10
}
}
superior_firepower_ratios = {
enable = {
has_tech = superior_firepower
}
abort = {
has_tech = concentrated_fire_plans
}
ai_strategy = {
type = unit_ratio
id = infantry
value = 20
}
ai_strategy = {
type = unit_ratio
id = light_armor
value = 2
}
ai_strategy = {
type = unit_ratio
id = main_armor
value = 2
}
ai_strategy = {
type = unit_ratio
id = heavy_armor
value = 2
}
ai_strategy = {
type = unit_ratio
id = artillery
value = 30
}
ai_strategy = {
type = unit_ratio
id = anti_tank
value = 10
}
}
## Later in superior_firepower tree
concentrated_fire_plans_ratios = {
enable = {
has_tech = concentrated_fire_plans
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = infantry
value = -20
}
ai_strategy = {
type = unit_ratio
id = artillery
value = 30
}
ai_strategy = {
type = unit_ratio
id = light_armor
value = 4
}
ai_strategy = {
type = unit_ratio
id = main_armor
value = 4
}
ai_strategy = {
type = unit_ratio
id = heavy_armor
value = 3
}
ai_strategy = {
type = unit_ratio
id = cas
value = 20
}
}
grand_battle_plan_ratios = {
enable = {
has_tech = trench_warfare
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = infantry
value = 20
}
ai_strategy = {
type = unit_ratio
id = motorized
value = 20
}
ai_strategy = {
type = unit_ratio
id = mechanized
value = 25
}
ai_strategy = {
type = unit_ratio
id = light_armor
value = 1
}
ai_strategy = {
type = unit_ratio
id = heavy_armor
value = 1
}
ai_strategy = {
type = unit_ratio
id = main_armor
value = 1
}
ai_strategy = {
type = unit_ratio
id = anti_tank
value = 15
}
ai_strategy = {
type = unit_ratio
id = artillery
value = 15
}
}
mass_assault_ratios = {
enable = {
has_tech = mass_assault
}
abort = {
has_tech = large_front_operations
}
ai_strategy = {
type = unit_ratio
id = infantry
value = 50
}
ai_strategy = {
type = unit_ratio
id = anti_tank
value = 15
}
ai_strategy = {
type = unit_ratio
id = artillery
value = 20
}
ai_strategy = {
type = unit_ratio
id = light_armor
value = 5
}
}
#Later in mass_assault tree
large_front_operations_ratios = {
enable = {
has_tech = large_front_operations
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = infantry
value = -30
}
ai_strategy = {
type = unit_ratio
id = motorized
value = 30
}
ai_strategy = {
type = unit_ratio
id = mechanized
value = 40
}
ai_strategy = {
type = unit_ratio
id = artillery
value = 30
}
ai_strategy = {
type = unit_ratio
id = light_armor
value = 10
}
ai_strategy = {
type = unit_ratio
id = anti_tank
value = 10
}
ai_strategy = {
type = unit_ratio
id = armor
value = 30
}
}
##############
### NAVAL ####
##############
#capital_ship
#submarine
#screen_ship
#convoy
#naval_transport
#carrier
#Fleet in being tree
fleet_in_being_ratios = {
enable = {
has_tech = fleet_in_being
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = capital_ship
value = 5
}
}
#Trade Interdiction tree
trade_interdiction_ratios = {
enable = {
has_tech = trade_interdiction
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = submarine
value = 200
}
}
#Base Strike tree
base_strike_ratios = {
enable = {
has_tech = base_strike
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = carrier
value = 50
}
ai_strategy = {
type = unit_ratio
id = naval_bomber
value = 20
}
}
##############
### AIR ####
##############
#rocket
#fighter
#cas
#interceptor
#tactical_bomber
#strategic_bomber
#naval_bomber
#Strategic Destruction tree
air_superiority_ratios = {
enable = {
has_tech = air_superiority
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = fighter
value = 50
}
ai_strategy = {
type = unit_ratio
id = cas
value = 25
}
}
air_night_day_bombing_ratios = {
enable = {
OR = {
has_tech = night_bombing
has_tech = day_bombing
}
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = strategic_bomber
value = 100
}
}
#Battlefield Support tree
formation_flying = {
enable = {
has_tech = formation_flying
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = fighter
value = 50
}
ai_strategy = {
type = unit_ratio
id = cas
value = 35
}
ai_strategy = {
type = unit_ratio
id = tactical_bomber
value = 25
}
ai_strategy = {
type = unit_ratio
id = strategic_bomber
value = -100
}
}
#Operational Integrity tree
force_rotation = {
enable = {
has_tech = force_rotation
}
abort = {
always = no
}
ai_strategy = {
type = unit_ratio
id = fighter
value = 50
}
ai_strategy = {
type = unit_ratio
id = tactical_bomber
value = 50
}
ai_strategy = {
type = unit_ratio
id = cas
value = 25
}
}
|
097f90818ffffd3fc23dbc70318b9ac9
|
{
"intermediate": 0.4030109643936157,
"beginner": 0.31260353326797485,
"expert": 0.2843855023384094
}
|
11,156
|
no openAI API KEY. code for a Ai assistant must have sqlite database and access my webcam and audio. must also have a learning code to store in database so that it dose not have to use the internet. must find what it needs through my computers documents, pdf’s and videos. aloud access to my computers resources and functions all python code.
|
7043e8af74fad9da547703737507852c
|
{
"intermediate": 0.41476938128471375,
"beginner": 0.2504129111766815,
"expert": 0.3348177373409271
}
|
11,157
|
функция текстовых подсказок работает неправильно (совсем не работают), города парсятся из russia.json с лишними символами const cities = [" ;Москва",“Абрамцево” https://www.codetable.net/decimal/34
Нужно заменить jquery более простым решением, другим пакетом или pure javascript, чтобы появлялись текстовые варианты из городов и автозаполнялись. вот код:
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
const fuzzball = require(“fuzzball”);
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync(“./db/russia.json”, “utf8”));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query = ‘’, role = ‘’, city = ‘’) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
let results = [];
if (query || role || city) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (
nameScore + genreScore > 0 &&
(role === “” || musician.role === role) &&
(city === “” || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim()))
//(city === “” || musician.city.toLowerCase() === city.toLowerCase())
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
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”, { citiesAndRegions, city:‘’ });
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
const found = citiesAndRegions.find(
({ city }) => city === req.body.city.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.city;
newMusician.region = “”;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const role = req.query.role || ‘’;
const city = req.query.city || ‘’;
let musicians = [];
if (query || role || city) {
musicians = search(query, role, city);
} else {
const data = fs.readFileSync(‘./db/musicians.json’);
musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
}
res.locals.predefinedGenres = predefinedGenres;
app.locals.JSON = JSON;
res.render(‘search’, { musicians, query, role, city, citiesAndRegions});
//res.redirect(‘/search’);
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel=“stylesheet” href=”/jquery-ui/themes/base/all.css" />
<script src=“/jquery/dist/jquery.min.js”></script>
<script src=“/jquery-ui/dist/jquery-ui.min.js”></script>
</head>
<body>
<h1>Search Musicians</h1>
<form action=“/search” method=“get”>
<label for=“query”>Search by name or genre:</label> <input id=“query” name=“query” type=“text” value=“<%= query %>”><br>
<br>
<label for=“role”>Search by role:</label> <select id=“role” name=“role”>
<option value=“”>
All
</option>
<option value=“Band”>
Band
</option>
<option value=“Artist”>
Artist
</option>
</select>
<label for=“city”>Search by location:</label>
<input id=“city” name=“city” type=“text” autocomplete=“on” value=“<%= city %>” data-value=“”>
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type=“submit”>Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href=“<%= musician.profileLink %>”><%= musician.name %> <%if (musician.thumbnail) { %> <img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href=“%3C%=%20musician.soundcloud%20%%3E”>SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
const cities = <%= JSON.stringify(citiesAndRegions.map(city => city.city)).replace(/“/g, '\”') %>;
$(“#city”).autocomplete({
source: cities,
minLength: 1,
});
const queryInput = document.querySelector(“#query”);
const roleInput = document.querySelector(“#role”);
const cityInput = document.querySelector(“#city”);
queryInput.value = “<%= query %>”;
roleInput.value = “<%= role %>”;
cityInput.value = cityInput.getAttribute(‘data-value’);
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
});
</script>
</body>
</html>
|
0db3213897057c5fc8301e1cf699ee3c
|
{
"intermediate": 0.4157683253288269,
"beginner": 0.489510178565979,
"expert": 0.0947214886546135
}
|
11,158
|
my pc has a wifi connection and ethernet connection. i wanna launch 2 selenium browsers: one using wifi connection and the other ethernet. How do i do this on windows using python?
|
1128de0bbf2cbc75644e8fded9098c59
|
{
"intermediate": 0.5112557411193848,
"beginner": 0.23225747048854828,
"expert": 0.25648677349090576
}
|
11,159
|
# Оптимизированный!!! Возвращает адреса созданных токенов в указанном диапазоне блоков (Обрабатывет множество блоков)
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
async def get_contract_verification_status(contract_address: str) -> bool:
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f"https://api.bscscan.com/api?module=contract&action=getabi&address={contract_address}&apikey={bscscan_api_key}"
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f"Error in API request: {e}")
return False
if data["result"] is None or not isinstance(data["result"], str):
return False
return data["result"] != "Contract source code not verified"
async def get_token_name(contract_address: str) -> str:
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f"https://api.bscscan.com/api?module=token&action=tokeninfo&contractaddress={contract_address}&apikey={bscscan_api_key}"
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f"Error in API request: {e}")
return ""
if data["result"] is None or not isinstance(data["result"], dict):
return ""
return data["result"].get("name", "")
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
async def is_contract_verified(contract_address: str) -> bool:
return await get_contract_verification_status(contract_address)
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
# Previous code remains the same up to the for loop
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx["to"] is None:
if check_method_id(tx["input"]):
contract_address = await get_contract_address(tx["hash"])
if contract_address:
verified = await get_contract_verification_status(contract_address)
token_name = await get_token_name(contract_address)
has_name = "Yes" if token_name else "No"
print(
f"New contract creation: Contract Address: {contract_address}, Has Name: {has_name}, Verified: {verified}")
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28866421 # Replace with your desired starting block number
block_end = 28866499 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
The code above outputs No, although the token has a name. The contract address 0x61356c1f74f9c238fe33a2a98398aeb2ca941c6f has a name - Penguin WAK. Fix to show Yes
|
e39167b3a2168c85f0967657a94a8afd
|
{
"intermediate": 0.3218131959438324,
"beginner": 0.5130090117454529,
"expert": 0.16517776250839233
}
|
11,160
|
I need to write a UDF code for ansys fluent in which I have a rectangular fluid domain and a solid assumed to be a circle that is quarter load in the flui domain, I want to simulate the effect of the circle rotation on fluid domain by writing a UDF that expresses the tangential velocity of the fluid at that edge taking into account that the UDF shall each iteration indicate the center of rotation then apply a tangential velocity, take into account that the circle is 20 mm diameter and of 30 rounds per mnute, and it may have deformation
|
1c3c164a947557625fc690d1a14869a0
|
{
"intermediate": 0.39151471853256226,
"beginner": 0.08425326645374298,
"expert": 0.524232029914856
}
|
11,161
|
no openAI API KEY. code for a Ai assistant must have sqlite database and access my webcam and audio. must also have a learning code to store in database so that it dose not have to use the internet. must find what it needs through my computers documents, pdf’s and videos. aloud access to my computers resources and functions. python code needed.
|
f424613b8b59651c9ce98d8d14d486a3
|
{
"intermediate": 0.4007588028907776,
"beginner": 0.24916669726371765,
"expert": 0.35007449984550476
}
|
11,162
|
code for creating a database in sql query
|
9968e4f1f4561315cdad3f60ff046518
|
{
"intermediate": 0.4574272334575653,
"beginner": 0.3033108711242676,
"expert": 0.2392619401216507
}
|
11,163
|
I have the following data:
subset_ipip
participant group date expName psychopyVersion OS frameRate globalClockTime miniIPIP miniIPIPanswer.text mouse_5.x mouse_5.y mouse_5.leftButton mouse_5.midButton mouse_5.rightButton mouse_5.time
9 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 128.4096 I am the life of the party 1 0.065000000 -0.4050000 1 0 0 23.9365
10 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 131.9120 I sympathize with others' feelings. 5 0.095000000 -0.3816667 1 0 0 3.4857
11 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 139.2848 I get chores done right away. 3 0.087500000 -0.3833333 1 0 0 7.3648
12 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 144.6564 I have frequent mood swings. 4 0.008333333 -0.4050000 1 0 0 5.3553
13 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 150.4454 I have a vivid imagination. 4 0.008333333 -0.4050000 1 0 0 5.7729
14 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 153.6802 I don't talk a lot. 5 0.008333333 -0.4050000 1 0 0 3.2163
15 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 159.4522 I am not interested in other people's problems. 2 0.008333333 -0.4050000 1 0 0 5.7634
16 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 168.2755 I often forget to put things back in their proper place. 3 0.008333333 -0.4050000 1 0 0 8.8060
17 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 172.6126 I am relaxed most of the time. 1 0.008333333 -0.4050000 1 0 0 4.3292
18 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 183.7722 I am not interested in abstract ideas. 1 0.008333333 -0.4050000 1 0 0 11.1408
19 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 189.2099 I talk to a lot of different people at parties. 1 0.008333333 -0.4050000 1 0 0 5.4183
20 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 192.3508 I feel others' emotions. 5 0.008333333 -0.4050000 1 0 0 3.1244
21 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 196.1494 I like order. 4 0.008333333 -0.4050000 1 0 0 3.7925
22 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 211.6345 I get upset easily. 4 0.150833333 -0.4066667 1 0 0 15.4702
23 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 224.9229 I have difficulty understanding abstract ideas. 2 0.052500000 -0.4141667 1 0 0 13.2695
24 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 233.8970 I keep in the background. 5 0.080000000 -0.4125000 1 0 0 8.9562
25 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 242.8874 I am not really interested in others. 1 0.080000000 -0.4125000 1 0 0 8.9745
26 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 256.7221 I make a mess of things. 3 0.098333333 -0.4108333 1 0 0 13.8161
27 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 263.7613 I seldom feel blue. 3 0.126666667 -0.3966667 1 0 0 7.0221
28 85913 24 2023-06-08_16h09.57.937 nappilot 2023.1.1 Win32 59.91971 279.9024 I do not have a good imagination. 1 0.126666667 -0.3966667 1 0 0 16.1242
529 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 77.2520 I am the life of the party 2 0.033333333 -0.4050000 1 0 0 7.2920
530 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 85.7100 I sympathize with others' feelings. 3 0.035000000 -0.4141667 1 0 0 8.4510
531 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 92.7490 I get chores done right away. 1 0.050833333 -0.3975000 1 0 0 7.0310
532 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 102.8240 I have frequent mood swings. 2 0.058333333 -0.3991667 1 0 0 10.0690
533 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 107.1100 I have a vivid imagination. 3 0.054166667 -0.4016667 1 0 0 4.2810
534 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 111.3480 I don't talk a lot. 4 0.040833333 -0.4125000 1 0 0 4.2310
535 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 118.9200 I am not interested in other people's problems. 3 0.040000000 -0.4083333 1 0 0 7.5680
536 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 126.2270 I often forget to put things back in their proper place. 1 0.040000000 -0.4083333 1 0 0 7.2990
537 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 135.5180 I am relaxed most of the time. 3 0.040000000 -0.4083333 1 0 0 9.2840
538 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 146.8260 I am not interested in abstract ideas. 2 0.045000000 -0.4033333 1 0 0 11.3030
539 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 153.2490 I talk to a lot of different people at parties. 3 0.047500000 -0.4008333 1 0 0 6.4150
540 908829 27 2023-06-08_18h49.55.486 nappilot 2023.1.1 MacIntel 62.73526 159.2370 I feel others' emotions. 2 0.055833333 -0.3950000 1 0 0 5.9820
Please run each unique participant through this type of analysis to get their scores:
# Example usage with the provided ratings vector
ratings <- c(3, 1, 4, 2, 5, 2, 4, 3, 1, 5, 3, 2, 4, 5, 1, 3, 2, 4, 5, 1)
indices_to_reverse <- c(6:10, 15:20)
# Creating a dataframe
df <- data.frame(ratings)
# Adding a new column "ratingsreversed" to the dataframe with reversed ratings
df$ratingsreversed <- reverse_ratings(df$ratings, indices_to_reverse)
# Define the rating ranges and corresponding qualitative markers
rating_ranges <- c(4, 6, 8, 11, 14, 17, 19, Inf)
qualitative_markers <- c("Extremely low", "Very low", "Low", "Neither high nor low; in the middle", "High", "Very High", "Extremely High")
# Function to get the qualitative marker based on a sum and the rating ranges
get_qualitative_marker <- function(sum) {
marker <- qualitative_markers[findInterval(sum, rating_ranges)]
return(marker)
}
# Calculate the sums for each category
sum_E <- sum(df$ratingsreversed[c(1, 6, 11, 16)])
sum_A <- sum(df$ratingsreversed[c(2, 7, 12, 17)])
sum_C <- sum(df$ratingsreversed[c(3, 8, 13, 18)])
sum_N <- sum(df$ratingsreversed[c(4, 9, 14, 19)])
sum_O <- sum(df$ratingsreversed[c(5, 10, 15, 20)])
# Get the qualitative marker for each category
marker_E <- get_qualitative_marker(sum_E)
marker_A <- get_qualitative_marker(sum_A)
marker_C <- get_qualitative_marker(sum_C)
marker_N <- get_qualitative_marker(sum_N)
marker_O <- get_qualitative_marker(sum_O)
# Create a dataframe with the scores and qualitative markers
result <- data.frame(Category = c("E", "A", "C", "N", "O"),
Score = c(sum_E, sum_A, sum_C, sum_N, sum_O),
QualitativeMarker = c(marker_E, marker_A, marker_C, marker_N, marker_O))
# Printing the updated dataframe
print(result)
|
2f5df3c1044a326456d1fba551c1e8cf
|
{
"intermediate": 0.2690376937389374,
"beginner": 0.6016931533813477,
"expert": 0.12926915287971497
}
|
11,164
|
> subset_data$image
[1] "images/470_blur_80.jpg" "images/440_contrast_70.jpg" "images/382_contrast_90.jpg" "images/9_jpeg_80.jpg" "images/288_jpeg_80.jpg" "images/115_contrast_70.jpg" "images/113_contrast_70.jpg" "images/228_contrast_70.jpg" "images/180_contrast_90.jpg" "images/227_contrast_90.jpg"
[11] "images/467_blur_80.jpg" "images/100_jpeg_70.jpg" "images/147_contrast_70.jpg" "images/216_contrast_70.jpg" "images/469_jpeg_70.jpg" "images/277_contrast_90.jpg" "images/536_jpeg_70.jpg" "images/39_original.jpg" "images/65_jpeg_80.jpg" "images/396_jpeg_70.jpg"
[21] "images/475_jpeg_80.jpg" "images/345_blur_70.jpg" "images/51_blur_80.jpg" "images/226_blur_70.jpg" "images/233_jpeg_90.jpg" "images/177_blur_70.jpg" "images/10_jpeg_80.jpg" "images/149_blur_90.jpg" "images/328_blur_70.jpg" "images/190_contrast_90.jpg"
I have shown images either in their original state or with "jpeg", "blur" or "contrast" distortion. If the images are distorted the can be distorted at levels "70", "80 or "90" which represents how many percentage of the original quality they are expected to have (SSIM). How can I elegantly separate the image into its different category names using the image name? Also propose BRMS models to predict another variable called ratings from the nested combination of image distortions and levels. Here is a first attempt:
# Find distortions and categories
# Image number
subset_data$ImageNumber <- gsub("^\\D*([0-9]+)_.*$", "\\1", subset_data$image)
# Extract letters following the first underscore until a second underscore or ".jpg" is encountered
subset_data$distortion <- gsub("^[^_]+_(.*?)(_[^_]+\\.jpg|\\.jpg)$", "\\1", subset_data$image)
# Convert "original" to "none"
subset_data$distortion[subset_data$distortion == "original"] <- "none"
# Extract last set of digits immediately followed by ".jpg" for each filename
subset_data$level <- gsub(".*_([0-9]+)\\.jpg$", "\\1", subset_data$image)
# Convert cases that are not "70", "80", or "90" to "100"
subset_data$level[!subset_data$level %in% c("70", "80", "90")] <- "100"
# Factor variables
subset_data$distortion <- factor(subset_data$distortion, levels = c("none", "jpeg", "blur", "contrast"))
subset_data$level <- factor(subset_data$level, levels = c("100", "90", "80", "70"))
# BRMS model
model <- brm(ratings ~ distortion*level, data = subset_data, iter = 2000,
family = gaussian, chains = 4)
One issue with this attempt is that it assumes that all distortion * level options are possible, but none will always have a quality of 100
|
53618434952602040ccd99b4bd366cbe
|
{
"intermediate": 0.3329542875289917,
"beginner": 0.43500566482543945,
"expert": 0.23204009234905243
}
|
11,165
|
Here:
proc fcmp;
declare object py(python);
rc = py.rtinfile("&scoring_dir.score.py");
put rc=;
rc = py.publish();
rc = py.call("model_call",
"&scoring_dir", "&scoring_dir", 'xgb1.model', "indata",1);
Result = py.results["model_call"];
put Result=;
run;
Appears to be error with files paths. The lines in python should be "/" , but SAS is calling that function with "\" slashes, which is causing an error.
|
87f4047007524ce7eca61a79a51bbb95
|
{
"intermediate": 0.4361684024333954,
"beginner": 0.32611048221588135,
"expert": 0.23772114515304565
}
|
11,166
|
how to group the hbase table already created
|
2a8ae6a9d37b04df91fbf07730f9c5c6
|
{
"intermediate": 0.3117619454860687,
"beginner": 0.265566349029541,
"expert": 0.42267170548439026
}
|
11,167
|
how can i host this python program for free dont suggest pythonanywhere since it has storage issue
def start(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi, I\'m your chatbot. How can I help you?')
def chatbot_response(update: Update, context: CallbackContext) -> None:
model = keras.models.load_model(r'E:\Projects\chatbot\models\chat_model.h5')
with open(r'E:\Projects\chatbot\models\tokenizer.pickle', 'rb') as handle:
tokenizer = pickle.load(handle)
with open(r'E:\Projects\chatbot\models\label_encoder.pickle', 'rb') as enc:
lbl_encoder = pickle.load(enc)
# parameters
max_len = 30
# Get the message from the user
message = update.message.text
# Convert input message into sequence of integers using tokenizer
msg_seq = tokenizer.texts_to_sequences([message])
# Pad the sequence to have fixed length
msg_seq = pad_sequences(msg_seq, maxlen=max_len, truncating='post')
# Predict the class of the input message
pred = model.predict(msg_seq)[0]
# Get the index of the predicted class
pred_idx = np.argmax(pred)
# Get the confidence of the prediction
confidence = pred[pred_idx]
# Convert the index back to the original label
tag = lbl_encoder.inverse_transform([pred_idx])[0]
# If the confidence is less than 0.5, send a default message
if confidence < 0.75:
context.bot.send_message(chat_id=update.effective_chat.id, text="I'm sorry, but I didn't understand your concern. Please keep it simple, rephrase the sentence or try asking something else related to mental health")
else:
for i in data['intents']:
if i['tag'] == tag:
response = np.random.choice(i['responses'])
# Send the response to the user
context.bot.send_message(chat_id=update.effective_chat.id, text=response)
break
def main() -> None:
# Create the Updater and pass it your bot's token.
updater = Updater("myapi",use_context=True)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# on different commands - answer in Telegram
dispatcher.add_handler(CommandHandler("start", lambda update, context: start(update, context)))
# on noncommand i.e message - echo the message on Telegram
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command,
lambda update, context: chatbot_response(update, context)))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the
updater.idle()
if __name__ == '__main__':
main()
|
8f08dbf49e1d5423a15f710fab69b393
|
{
"intermediate": 0.3201858401298523,
"beginner": 0.4661499857902527,
"expert": 0.21366417407989502
}
|
11,168
|
Give me examples for xss attack?
|
79759b54cd1e9fa7dfe7a7ae16e1c238
|
{
"intermediate": 0.24422293901443481,
"beginner": 0.35275429487228394,
"expert": 0.403022825717926
}
|
11,169
|
I need C++ code that counts spiecific words in string
|
c29da02cf6e4f64b283cebef91724770
|
{
"intermediate": 0.33304065465927124,
"beginner": 0.3616064488887787,
"expert": 0.3053528666496277
}
|
11,170
|
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
api_request_delay = 0.2 # Set a 200ms delay between API requests
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
async def get_contract_verification_status(contract_address: str) -> bool:
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f"https://api.bscscan.com/api?module=contract&action=getabi&address={contract_address}&apikey={bscscan_api_key}"
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f"Error in API request: {e}")
return False
if data["result"] is None or not isinstance(data["result"], str):
return False
return data["result"] != "Contract source code not verified"
async def get_token_name(contract_address: str) -> str:
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f"https://api.bscscan.com/api?module=account&action=tokeninfo&contractaddress={contract_address}&apikey={bscscan_api_key}"
# Retry mechanism in case of failures
retries = 3
while retries > 0:
try:
await asyncio.sleep(api_request_delay)
async with session.get(url) as response:
data = await response.json()
if data["result"] is None or not isinstance(data["result"], dict):
retries -= 1
continue
return data["result"].get("name", "")
except Exception as e:
print(f"Error in API request: {e}")
retries -= 1
return "" # Return an empty string if retries are exhausted
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
async def is_contract_verified(contract_address: str) -> bool:
return await get_contract_verification_status(contract_address)
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx["to"] is None:
if check_method_id(tx["input"]):
contract_address = await get_contract_address(tx["hash"])
if contract_address:
verified = await get_contract_verification_status(contract_address)
token_name = await get_token_name(contract_address)
print(
f"New contract creation: Contract Address: {contract_address}, Token Name: {token_name}, Verified: {verified}")
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28866421 # Replace with your desired starting block number
block_end = 28866499 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
The code above still does not return the name of the token. Instead, a space (gap) is displayed, as if the code does not see the name. fix it
|
db466d72a5a9159fd20404d84e5ea60a
|
{
"intermediate": 0.3789711594581604,
"beginner": 0.5077827572822571,
"expert": 0.11324609816074371
}
|
11,171
|
#include "public.h"
#include "key.h"
#include "beep.h"
#include "songdata.h"
#define Clk 0x070000
unsigned char data val_H; //计数器高字节
unsigned char data val_L; //计数器低字节
#define ROWS 4
#define COLS 4
sbit P00 = P2^5; //扬声器控制引脚
// 定义矩阵键盘的行列对应的引脚
sbit row1 = P1^7;
sbit row2 = P1^6;
sbit row3 = P1^5;
sbit row4 = P1^4;
sbit col1 = P1^3;
sbit col2 = P1^2;
sbit col3 = P1^1;
sbit col4 = P1^0;
// 音符频率数组
unsigned int freq[] = {262, 294, 330, 349, 392, 440, 494, 523, 0, 587, 659, 698, 784};
// 音乐保存缓冲区,最多可以保存32个音符
unsigned char music_buffer[32];
unsigned char music_length = 0;
// 定义矩阵键盘的键值
const unsigned char keymap[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
bit song_playing = 0; // 添加歌曲播放标志
void t0_isr() interrupt 1 //定时器 0 中断处理程序
{
if (song_playing) { // 当歌曲播放标志为真时,产生方波
P00 = ~P00;
} else {
P00 = 1; // 不产生方波,关闭蜂鸣器
}
TH0 = val_H; //重新装入计数值
TL0 = val_L;
}
void Delay(unsigned char cnt) //单位延时
{
unsigned char i;
unsigned int j;
for(i=0; i<cnt; i++)
{
for(j=0; j<0x3600; j++);
}
}
char matrix_keypad_scan()
{
char key = 0;
int i, j;
// 将所有行置为高电平,所有列置为输入模式
row1 = 1; row2 = 1; row3 = 1; row4 = 1;
col1 = 0; col2 = 0; col3 = 0; col4 = 0;
// 检测每一行的状态
for (i = 0; i < ROWS; i++) {
switch (i) {
case 0: row1 = 0; break;
case 1: row2 = 0; break;
case 2: row3 = 0; break;
case 3: row4 = 0; break;
}
delay_10us(1000);
// 检测每一列的状态
for (j = 0; j < COLS; j++) {
if (col1 == 0) {
key = keymap[i][j];
break;
}
if (col2 == 0) {
key = keymap[i][j+1];
break;
}
if (col3 == 0) {
key = keymap[i][j+2];
break;
}
if (col4 == 0) {
key = keymap[i][j+3];
break;
}
}
// 如果检测到按键,跳出循环
if (key != 0) {
break;
}
// 恢复所有列的状态为输入模式
col1 = 1; col2 = 1; col3 = 1; col4 = 1;
}
// 等待按键释放
while (col1==0 || col2==0 || col3==0 || col4==0);
return key;
}
void main()
{
u8 key = 0;
u8 beep_flag1 = 0; //蜂鸣器状态标志
u8 beep_flag2 = 0;
u8 beep_flag3 = 0;
u8 beep_flag4 = 0;
unsigned int val;
unsigned char i = 0;
TMOD = 0x01; //初始化
IE = 0x82;
TR0 = 1;
while (1)
{
key = key_scan(0); //检测按键
if (key == KEY1_PRESS) //K1按下,放第一首歌
{
beep_flag1 = !beep_flag1;
beep_flag2 = 0;
beep_flag3 = 0;
beep_flag4=0;
i = 0;
}
else if (key == KEY2_PRESS) //K2按下放第二首歌
{
beep_flag2 = !beep_flag2;
beep_flag1 = 0;
beep_flag3 = 0;
beep_flag4=0;
i = 0;
}
else if (key == KEY3_PRESS) //K3按下放第三首歌
{
beep_flag3 = !beep_flag3;
beep_flag1 = 0;
beep_flag2 = 0;
beep_flag4 = 0;
i = 0;
}
else if (key == KEY4_PRESS) //K4按下放第四首歌
{
beep_flag4 = !beep_flag4;
beep_flag1 = 0;
beep_flag2 = 0;
beep_flag3 = 0;
i = 0;
}
if (beep_flag1)
{
song_playing = 1;
while (freq_list1[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list1[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list1[i]);
i++;
if (key_scan(0) != KEY_UNPRESS)
{
beep_flag1 = beep_flag2 = beep_flag3 =beep_flag4= 0; // 清除当前正在播放的歌曲标志,停止播放并退出循环
break;
}
}
}
else if (beep_flag2) {
song_playing = 1;
while (freq_list2[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list2[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list2[i]);
i++;
if (key_scan(0) != KEY_UNPRESS) {
beep_flag1 = beep_flag2 = beep_flag3 =beep_flag4= 0; // 清除当前正在播放的歌曲标志,停止播放并退出循环
break;
}
}
}
else if (beep_flag3)
{
song_playing = 1;
while (freq_list3[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list3[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list3[i]);
i++;
if (key_scan(0) != KEY_UNPRESS) {
beep_flag1 = beep_flag2 = beep_flag3 =beep_flag4= 0; // 清除当前正在播放的歌曲标志,停止播放并退出循环
break;
}
}
}
else if (beep_flag4)
{
song_playing = 1;
while (freq_list4[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list4[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list4[i]);
i++;
if (key_scan(0) != KEY_UNPRESS) {
beep_flag1 = beep_flag2 = beep_flag3 =beep_flag4= 0; // 清除当前正在播放的歌曲标志,停止播放并退出循环
break;
}
}
}
else {
song_playing = 0; // 没有歌曲在播放,设置歌曲播放标志为假
}
}
}
在这个基础上修改,使用4×4矩阵键盘作为电子琴键,按下键演奏出相应的音符,能够保存所演奏的音乐,并重复自动播放。
|
cabc073aa38f306e2ca5de0733f4b948
|
{
"intermediate": 0.3320629298686981,
"beginner": 0.5068473815917969,
"expert": 0.161089688539505
}
|
11,172
|
how can i host this python program for free dont suggest pythonanywhere,heroku or replit
def start(update: Update, context: CallbackContext) -> None:
“”“Send a message when the command /start is issued.”“”
update.message.reply_text(‘Hi, I’m your chatbot. How can I help you?’)
def chatbot_response(update: Update, context: CallbackContext) -> None:
model = keras.models.load_model(r’E:\Projects\chatbot\models\chat_model.h5’)
with open(r’E:\Projects\chatbot\models\tokenizer.pickle’, ‘rb’) as handle:
tokenizer = pickle.load(handle)
with open(r’E:\Projects\chatbot\models\label_encoder.pickle’, ‘rb’) as enc:
lbl_encoder = pickle.load(enc)
# parameters
max_len = 30
# Get the message from the user
message = update.message.text
# Convert input message into sequence of integers using tokenizer
msg_seq = tokenizer.texts_to_sequences([message])
# Pad the sequence to have fixed length
msg_seq = pad_sequences(msg_seq, maxlen=max_len, truncating=‘post’)
# Predict the class of the input message
pred = model.predict(msg_seq)[0]
# Get the index of the predicted class
pred_idx = np.argmax(pred)
# Get the confidence of the prediction
confidence = pred[pred_idx]
# Convert the index back to the original label
tag = lbl_encoder.inverse_transform([pred_idx])[0]
# If the confidence is less than 0.5, send a default message
if confidence < 0.75:
context.bot.send_message(chat_id=update.effective_chat.id, text=“I’m sorry, but I didn’t understand your concern. Please keep it simple, rephrase the sentence or try asking something else related to mental health”)
else:
for i in data[‘intents’]:
if i[‘tag’] == tag:
response = np.random.choice(i[‘responses’])
# Send the response to the user
context.bot.send_message(chat_id=update.effective_chat.id, text=response)
break
def main() -> None:
# Create the Updater and pass it your bot’s token.
updater = Updater(“myapi”,use_context=True)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# on different commands - answer in Telegram
dispatcher.add_handler(CommandHandler(“start”, lambda update, context: start(update, context)))
# on noncommand i.e message - echo the message on Telegram
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command,
lambda update, context: chatbot_response(update, context)))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the
updater.idle()
if name == ‘main’:
main()
|
7e0e3cb25ba9d7b885654e4a7bb28a08
|
{
"intermediate": 0.3525889217853546,
"beginner": 0.38730913400650024,
"expert": 0.26010194420814514
}
|
11,173
|
System.load("C:\\Users\\skiin\\lib\\hadoop\\bin\\hadoop.dll");这个代码是干啥的
|
ab11d40839c983f23194283b997e9898
|
{
"intermediate": 0.4950048327445984,
"beginner": 0.22355635464191437,
"expert": 0.28143876791000366
}
|
11,174
|
I have two workbooks open.
One is called 'Service Providers' the other is called 'Auxillary'.
When I close 'Auxillary' I want all the values in A1:A31 its sheet 'Note' to be pasted into
workbook 'Service Providers' sheet 'Notes' A1:A31.
How will I write this vba code
|
a6b1ae5534f79b2a92d4d985048a9b00
|
{
"intermediate": 0.406410813331604,
"beginner": 0.34190404415130615,
"expert": 0.2516850531101227
}
|
11,175
|
I have a list of persons’ names in different formats. Each of them is in one Excel cell (i.e., each of them is in 1 string). Examples are below:
Olive Johnson
William F. Hilyard
Stanley and Grace Hajicek
Phillip Felix Buteau
Hazel M. and Mary Louise Van Riper
Ditto, Joyce Glenna Roberts
Mrs. Lester Norseth
Mrs. Mae E. Mason
Jennie B. and Charles F. Mills
Fred A. and Phyllis M. and Fred G. Bollman
A.M. Johnson
G.Albert Johnson
(Rev.) Olof H. Sylvan
C. A. Greek (Cook)
Unknown Challstrom
Unknown Unknown
Knud N Strarup and Alfred Sorenson
Frank J. W. Johnson
Darlene Rydell and sons Lance and Brandt Rydell
Iola Delores Schneider Sturm
Unknwon Schmidt, Unknown Goodenow
Fred Brown, Barbara Brown
J. Howard Abner, Inez Abner
Mike Lewandowski, Kim Lewandowski (Nesler)
Ed Cockrell, Leatha Cockrell, Beuford Cockrell
Noisworthy, Gary D. Sherre
Roy E. Terry, Frederick Terry
J. D. Terry, F. Mildred
Rev. George Alfred Shadwick, Rachel Pauline Shadwick
John Glassnap, Stella Glassnap, Donald Bollinger, Raymond Bollinger
Roy W. Friedrich Jr., Judith Friedrich
Mr. Albert DeLay, Mrs. DeLay
Lillian F. Parsons and Gwendolyn M. Parsons
Garen K. Gdanian & Isabelle Gdanian
Sarkis Sedefian & Marie E. Kizirian
Timothy W. LaMountain & Helen J. LaMountain
Dennis A. Rapp & Mary Grates Stoll Rapp
Charles P. Green, Jr., M. Reges & R. Reges Green, Their Daughter
George R. Brant, Jr.
A. Brant, Sr.
Roger and Kendra Pelham
Karl A. Paulsen & Bertha J. Dittmann Paulsen
Leo E. Godin III
Alfred Godin Second
Joseph J. Olander & Beverly A. Olander, His Wife
Susan M. Thirolle & Jean-Claude Thirolle, her husband
Jessica B. Arnold and Jake Fred Arnold, her husband
I need a VBA macro to split them into first_name, last_name, middle_name, title (Mr., Ms., Sr., Rev. and others). Imagine that all names to be processed are in column A, and your output should go to columns B, C, etc. Account for all the scenarios provided in examples above (including absence of some parts in a full name or the fact that they may go in different orders). It is also possible that one cell contain multiple person (for instance, “Stanley and Grace Hajicek”) - in such case put second person's data in the next columns to the first one's
|
d9235997947019480a95301e5228988c
|
{
"intermediate": 0.39609354734420776,
"beginner": 0.25446638464927673,
"expert": 0.3494400680065155
}
|
11,176
|
peux tu m'expliquer cette erreur et comment la corriger ? 1) Contract: Penduel
Verifier GameStatus
"before each" hook for "should define waitingForPlayers":
Error: invalid BigNumber value (argument="value", value={"from":"0xAa15330BCf5cC961C794E6714737eAEcF9FbEF0a"}, code=INVALID_ARGUMENT, version=bignumber/5.6.2)
at Context.<anonymous> (test/test.js:19:48)
at processImmediate (node:internal/timers:476:21)
|
9d6ed635d8cd6143fdfaddd5e16aadd9
|
{
"intermediate": 0.33261582255363464,
"beginner": 0.48569560050964355,
"expert": 0.1816885620355606
}
|
11,177
|
how to fix error graphql: Error: Cannot return null for non-nullable field A.pairing
|
3d6608a89f8d631fe40a830458a2d861
|
{
"intermediate": 0.4415338337421417,
"beginner": 0.1996932327747345,
"expert": 0.35877299308776855
}
|
11,178
|
# Оптимизированный!!! озвращает адреса созданных токенов в указанном диапазоне блоков (Обрабатывет множество блоков)
# Также отображает верифицированный код или нет
# Также проверяет есть ли имя у токена или нет
import asyncio
import aiohttp
import json
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
api_request_delay = 0.2 # Set a 200ms delay between API requests
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
async def get_contract_verification_status(contract_address: str) -> bool:
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f"https://api.bscscan.com/api?module=contract&action=getabi&address={contract_address}&apikey={bscscan_api_key}"
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f"Error in API request: {e}")
return False
if data["result"] is None or not isinstance(data["result"], str):
return False
return data["result"] != "Contract source code not verified"
async def get_contract_abi(contract_address: str) -> str:
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f"https://api.bscscan.com/api?module=contract&action=getabi&address={contract_address}&apikey={bscscan_api_key}"
# Retry mechanism in case of failures
retries = 3
while retries > 0:
try:
await asyncio.sleep(api_request_delay)
async with session.get(url) as response:
data = await response.json()
if data["result"] is None or not isinstance(data["result"], str):
retries -= 1
continue
return data["result"]
except Exception as e:
print(f"Error in API request: {e}")
retries -= 1
return "" # Return an empty string if retries are exhausted
async def get_token_name_from_abi(contract_address: str) -> str:
abi_str = await get_contract_abi(contract_address)
if not abi_str: # empty string
return ""
try:
contract_abi = json.loads(abi_str)
for contract_item in contract_abi:
if contract_item.get("type") == "function" and contract_item.get("name") == "name":
return "YES"
return ""
except Exception as e:
print(f"Error parsing ABI: {e}")
return "NO"
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
async def is_contract_verified(contract_address: str) -> bool:
return await get_contract_verification_status(contract_address)
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx["to"] is None:
if check_method_id(tx["input"]):
contract_address = await get_contract_address(tx["hash"])
if contract_address:
token_details_task = asyncio.gather(
get_contract_verification_status(contract_address),
get_token_name_from_abi(contract_address)
)
verified, token_name = await token_details_task
print(
f"New contract creation: Contract Address: {contract_address}, Token Name: {token_name}, Verified: {verified}")
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28866499 # Replace with your desired starting block number
block_end = 28866530 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
try:
asyncio.run(main())
except Exception as e:
print(f"Error: {e}")
Change the code above to display only addresses with a verified code and the presence of a token name
|
3c7525839c9cd2b2136ac63d042b561f
|
{
"intermediate": 0.39261510968208313,
"beginner": 0.4090874195098877,
"expert": 0.1982974410057068
}
|
11,179
|
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val recyclerView: RecyclerView = findViewById(R.id.rcView)
val adapter = Adapter(fetchData(fetchData(item))
recyclerView.layoutManager = GridLayoutManager(this, 2)
recyclerView.adapter=adapter
}
private fun fetchData(): MutableList<Int> {
val item = mutableListOf<Int>()
item.add(com.google.android.material.R.drawable.ic_clock_black_24dp)
item.add(com.google.android.material.R.drawable.ic_clock_black_24dp)
item.add(com.google.android.material.R.drawable.ic_clock_black_24dp)
item.add(com.google.android.material.R.drawable.ic_clock_black_24dp)
item.add(com.google.android.material.R.drawable.ic_clock_black_24dp)
item.add(com.google.android.material.R.drawable.ic_clock_black_24dp)
item.add(com.google.android.material.R.drawable.ic_clock_black_24dp)
item.add(com.google.android.material.R.drawable.ic_clock_black_24dp)
return item
}
}
|
2ce1b51b0f3e3e88ad6a95937b2fe99a
|
{
"intermediate": 0.40245911478996277,
"beginner": 0.3169066607952118,
"expert": 0.28063416481018066
}
|
11,180
|
hi
|
0940e88123cc3efd3e3bba881f83c8fa
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
11,181
|
da <- setDT(data)
group <- da[, .(task = PCA_, n = .N, mean_PCA = mean(PCA_), sd_PCA = sd(PCA_)), by = .(age, sex)]
ages <- c()
p_values <- c()
t_values <- c()
n_female <- c()
n_male <- c()
for (age in unique(group$age)) {
cat("age:", age, "\n")
data_male <- c()
data_female <- c()
for (gender in unique(group$sex)) {
dat <- group %>%
filter(age == age, sex == gender) %>%
select(task) %>%
unlist()
cat("sex:", gender, "\n")
cat("N:", length(dat), "\n")
cat("Mean:", mean(dat), "\n")
cat("Std:", sd(dat), "\n")
if (gender == 1) {data_male <- dat}
else if (gender == 0) {data_female <- dat}
}
result <- t.test(data_male, data_female)
t_stat <- result$statistic
p_value <- result$p.value
# Print t-test results
cat("t:", t_stat, "\n")
cat("p:", p_value, "\n")
# Add results to respective vectors
ages <- c(ages, age)
t_values <- c(t_values, t_stat)
p_values <- c(p_values, p_value)
n_female <- c(n_female, length(data_female))
n_male <- c(n_male, length(data_male))
}
# FDR correction
pvalue_corrected <- p.adjust(p_values, method = "fdr")
# Create dataframe with results
p_values_df <- data.frame(Age = ages,
t_value = t_values,
P_value = p_values,
P_value_FDR = pvalue_corrected,
female = n_female,
male = n_male)
print(p_values_df)
|
e3a8e5f1df66e4f80de93357e21c8cde
|
{
"intermediate": 0.35473939776420593,
"beginner": 0.3367260992527008,
"expert": 0.30853453278541565
}
|
11,182
|
dat <- setDT(data)
group <- dat[, .(n = .N, mean_PCA = mean(PCA_), sd_PCA = sd(PCA_)), by = .(age, sex)]
ages <- c()
p_values <- c()
t_values <- c()
n_female <- c()
n_male <- c()
for (age in unique(group$age)) {
cat("age:", age, "\n")
data_male <- c()
data_female <- c()
for (gender in unique(group$sex)) {
dat <- data %>%
filter(age == age, sex == gender) %>%
select(PCA_) %>%
unlist()
cat("sex:", gender, "\n")
cat("N:", length(dat), "\n")
cat("Mean:", mean(dat), "\n")
cat("Std:", sd(dat), "\n")
if (gender == 1) {data_male <- dat}
else if (gender == 0) {data_female <- dat}
}
result <- t.test(data_male, data_female)
t_stat <- result$statistic
p_value <- result$p.value
# Print t-test results
cat("t:", t_stat, "\n")
cat("p:", p_value, "\n")
# Add results to respective vectors
ages <- c(ages, age)
t_values <- c(t_values, t_stat)
p_values <- c(p_values, p_value)
n_female <- c(n_female, length(data_female))
n_male <- c(n_male, length(data_male))
}
|
5584ff72717f740e53285b4b2c27b1e6
|
{
"intermediate": 0.292990505695343,
"beginner": 0.416185587644577,
"expert": 0.29082393646240234
}
|
11,183
|
I will provide you with a README file for a C++ project implementing bindable properties. Please write some unit tests to test the reported functionality:
# Bindable Properties for C++11
This is a C++ library that provides an implementation of properties that can
be bound to each other. It allows for properties to be treated as data members,
while also providing the ability to automatically update other properties when a
property's value is changed.
## Features
- Support simple property views and complex bindings to one or more properties.
- Automatic updates for bound properties.
- Define custom notifications for when property changes its value.
- Views and bound properties can request the original property to change.
## Semantics
### Property Ownership
There are two ways to create a property: as an owner, or as a view/binding. When
you create a property as an owner, the property owns its data, and is responsible
for handling change requests. When you create a property as a view or a binding,
the property value is a function of one or more other properties, and any changes
made to these properties will be reflected in the view.
You can transfer ownership of a property to another property by using the move
constructor or move assignment operator.
|
e81ff24c2d2dc8cfe5034243a05475be
|
{
"intermediate": 0.4596264958381653,
"beginner": 0.266209214925766,
"expert": 0.27416422963142395
}
|
11,184
|
hi
|
5a269272db6ffd21563b11621bbba1c5
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
11,185
|
In a huawei switch of model S2720-52TP-EI I want 5 Eth ports in vlan 16 as access, one ethport in vlan 1000 as access and one Gigabiteth port as trunk passing 1 to 4094, please provide cli commands for that
|
3552c65f35d7b3a4d57e88997938aac6
|
{
"intermediate": 0.3580503761768341,
"beginner": 0.276466965675354,
"expert": 0.3654826283454895
}
|
11,186
|
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.
For the user interface component of the engine, what would be the best way to identify and register when a menu item, such as a button, is clicked?
|
3d1d53b34b40fdace47edbed79fc5c7a
|
{
"intermediate": 0.6344583630561829,
"beginner": 0.1713239997625351,
"expert": 0.19421766698360443
}
|
11,187
|
I want to install python 3.8.8 version on termux by its source code give me full instruction one by one without mistaking
4 minutes ago
|
57b13b8ddb65d8af53468be972c37bdb
|
{
"intermediate": 0.3588029146194458,
"beginner": 0.3071851432323456,
"expert": 0.33401191234588623
}
|
11,188
|
How to throw an exception in c++ like std::out_of_range?
|
f2592daa281c78172083015d55ddc8fa
|
{
"intermediate": 0.5791512727737427,
"beginner": 0.20476417243480682,
"expert": 0.21608459949493408
}
|
11,189
|
This is my code:
|
184b5a31d265253e263d00be01345faa
|
{
"intermediate": 0.24506328999996185,
"beginner": 0.26601240038871765,
"expert": 0.4889243543148041
}
|
11,190
|
hello
|
e7ac5fac11921752d60569fe144200f6
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
11,191
|
$backup_file='C/wamp/www/hekacorporation.org/myapp/backup/backup.sql';
exec("mysqldump --u=$username --password=$pwd --host=$servname");
$dbname > $backup_file > 0 ;
|
6fbfbfd43849506149ddbe634abf9831
|
{
"intermediate": 0.3702053427696228,
"beginner": 0.3387346863746643,
"expert": 0.2910599410533905
}
|
11,192
|
What is the advantage of applying dsr and rel routing protocols on arduino for ecg signal transmission
|
d6bb26bab758d043b30d307c823c3729
|
{
"intermediate": 0.2332673817873001,
"beginner": 0.17458730936050415,
"expert": 0.5921453237533569
}
|
11,193
|
Based on this dto import { ApiProperty } from '@nestjs/swagger';
import { AbstractDto } from '../../../common/dto/abstract.dto';
import { CategoryEntity } from '../entities/category.entity';
export class CategoryDto extends AbstractDto {
@ApiProperty({
description: 'Name of category',
type: String,
})
name: string;
@ApiProperty({
description: 'Color of category',
type: Number,
})
color: number;
@ApiProperty({
description: 'Parent category of category',
type: CategoryDto,
nullable: true,
})
parentCategory: CategoryDto;
constructor(category: CategoryEntity) {
super(category);
this.name = category.name;
this.color = category.color;
this.parentCategory = category.parentCategory
? category.parentCategory.toDto()
: null;
}
}
add a service that will return only categories with an array of their subcategories.
|
2bf09e2e77116cb61853948d7ca0f464
|
{
"intermediate": 0.41005903482437134,
"beginner": 0.37619346380233765,
"expert": 0.21374745666980743
}
|
11,194
|
use syn::parse::{Parse, ParseStream};
// This is a dummy syntax structure to try parsing the input tokens.
struct Dummy;
impl Parse for Dummy {
fn parse(input: ParseStream) -> syn::Result<Self> {
input.parse::<syn::Expr>()?;
Ok(Self)
}
}
// Example function to check if there is any syntax error in the input tokens.
fn check_syntax_error(tokens: TokenStream) -> bool {
let result = syn::parse2::<Dummy>(tokens.into());
match result {
Ok() => false,
Err() => true,
}
}
by analogy, come up with rust code that is doing the same, but check_syntax_error gets argument “stream” type of &str and converting it to tokens while checking that tokens for syntax error
|
5f0fe85b0d27902b84d6853db93b06be
|
{
"intermediate": 0.40558257699012756,
"beginner": 0.3875914216041565,
"expert": 0.20682604610919952
}
|
11,195
|
Explain how the following C++ function is used to check if the point p is within a triangle constructed by the three vertices in the argument pts.
|
0a8a4014214bc6b54f4aa8b336a96241
|
{
"intermediate": 0.44748473167419434,
"beginner": 0.207340806722641,
"expert": 0.3451744019985199
}
|
11,196
|
org.postgresql.util.PSQLException: FATAL: database "btms" does not exist
|
53f9658c6d337b827f980a7435f05d7a
|
{
"intermediate": 0.3674986958503723,
"beginner": 0.33509182929992676,
"expert": 0.29740944504737854
}
|
11,197
|
Write a yaml file that turns on a switch when it is raining outside
|
20a938cd55d20956694455cc5ea383eb
|
{
"intermediate": 0.33429181575775146,
"beginner": 0.2746499478816986,
"expert": 0.3910582363605499
}
|
11,198
|
i have a c++ opengl app - i import a model using assimp, and i try to render it, and it renders correctly, but the shader seems to be wrong as it is displayed as black, and it shouldnt.
here is my vertex shader:
#version 330
uniform mat4 P;
uniform mat4 V;
uniform mat4 M;
uniform sampler2D tex1s;
uniform sampler2D tex2s;
uniform mat4 modelMatrix;
in vec3 vertex;
in vec2 texCoords;
in vec3 normal;
in vec3 tangent;
in vec3 bitangent;
out vec3 fragPos;
out vec2 texCoordsOut;
out vec3 normalOut;
out vec3 tangentOut;
out vec3 bitangentOut;
void main(){
fragPos = vec3(M * vec4(vertex, 1.0));
normalOut = vec3(transpose(inverse(M))) * normal;
texCoordsOut = texCoords;
tangentOut = vec3(transpose(inverse(M))) * tangent;
bitangentOut = vec3(transpose(inverse(M))) * bitangent;
gl_Position = P * V * M * vec4(fragPos, 1.0);
}
here is my fragment shader:
#version 330
uniform vec3 diffuseColor;
uniform float shininess;
uniform vec3 emissiveColor;
uniform float opacity;
uniform sampler2D tex1s;
uniform sampler2D tex2s;
uniform vec3 lightColor;
uniform vec3 lightDirection;
in vec3 normalOut;
in vec3 fragPos;
in vec2 texCoordsOut;
in vec3 tangentOut;
in vec3 bitangentOut;
out vec4 Color;
void main() {
vec3 normaln = normalize(normalOut);
vec3 bitangentn = normalize(bitangentOut);
vec3 tangentn = normalize(tangentOut);
vec3 normalMap = texture(tex1s, texCoordsOut).rgb;
normalMap = normalize(normalMap * 2.0 - 1.0);
mat3 TBN = mat3(tangentn, bitangentn, normaln);
vec3 transformedNormal = normalize(TBN * normalMap);
// Diffuse Lighting
float diffuseFactor = max(dot(transformedNormal, -lightDirection), 0.0);
vec4 texColor = texture(tex2s, texCoordsOut);
vec3 diffuse = diffuseColor * texColor.rgb * lightColor * diffuseFactor;
// Emissive Lighting
vec3 emissive = emissiveColor;
// Final Color Calculation
vec3 finalColor = diffuse + emissive;
// shininess is between 0 and 256
float specularFactor = pow(max(dot(transformedNormal, -lightDirection), 0.0), shininess);
vec3 specular = vec3(1.0, 1.0, 1.0) * specularFactor;
finalColor += specular;
// Apply opacity
finalColor *= opacity;
Color = vec4(finalColor, 1.0);
}
here are relevant bits of my main code:
void buffers() {
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, meshData.vertices.size() * sizeof(glm::vec3), (& meshData.vertices[0]), GL_STATIC_DRAW);
glVertexAttribPointer(sp->a("vertex"), 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(sp->a("vertex"));
glGenBuffers(1, &nbo);
glBindBuffer(GL_ARRAY_BUFFER, nbo);
glBufferData(GL_ARRAY_BUFFER, meshData.normals.size() * sizeof(glm::vec3), (& meshData.normals[0]), GL_STATIC_DRAW);
glVertexAttribPointer(sp->a("normal"), 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(sp->a("normal"));
glGenBuffers(1, &tbo);
glBindBuffer(GL_ARRAY_BUFFER, tbo);
glBufferData(GL_ARRAY_BUFFER, meshData.textureCoords.size() * sizeof(glm::vec2), (& meshData.textureCoords[0]), GL_STATIC_DRAW);
glVertexAttribPointer(sp->a("texCoords"), 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(sp->a("texCoords"));
glGenBuffers(1, &tangentbo);
glBindBuffer(GL_ARRAY_BUFFER, tangentbo);
glBufferData(GL_ARRAY_BUFFER, meshData.tangents.size() * sizeof(glm::vec3), (& meshData.tangents[0]), GL_STATIC_DRAW);
glVertexAttribPointer(sp->a("tangent"), 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(sp->a("tangent"));
glGenBuffers(1, &bitangentbo);
glBindBuffer(GL_ARRAY_BUFFER, bitangentbo);
glBufferData(GL_ARRAY_BUFFER, meshData.bitangents.size() * sizeof(glm::vec3), (& meshData.bitangents[0]), GL_STATIC_DRAW);
glVertexAttribPointer(sp->a("bitangent"), 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(sp->a("bitangent"));
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, meshData.indices.size() * sizeof(unsigned int), (& meshData.indices[0]), GL_STATIC_DRAW);
glBindVertexArray(0);
}
void drawScene(GLFWwindow* window,float angle_x,float angle_y, float time) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::mat4 V=glm::lookAt(
glm::vec3(0.0, 2.0, 4.0),
glm::vec3(0,0,0),
glm::vec3(0.0f,1.0f,0.0f)); //Wylicz macierz widoku
glm::mat4 P = glm::perspective(glm::radians(45.0f), aspectRatio, 0.1f, 50.0f); //Wylicz macierz rzutowania
glm::mat4 M=glm::mat4(1.0f);
sp->use();//Aktywacja programu cieniującego
glActiveTexture(GL_TEXTURE0);
tex1 = readTexture("./skeleton/skeleton_image1.png");
glBindTexture(GL_TEXTURE_2D, tex1);
glUniform1i(sp->u("tex1s"), 0);
glActiveTexture(GL_TEXTURE1);
tex2 = readTexture("./skeleton/skeleton_image0.png");
glBindTexture(GL_TEXTURE_2D, tex2);
glUniform1i(sp->u("tex2s"), 1);
glUniformMatrix4fv(sp->u("P"), 1, false, glm::value_ptr(P));
glUniformMatrix4fv(sp->u("V"), 1, false, glm::value_ptr(V));
glUniformMatrix4fv(sp->u("M"), 1, false, glm::value_ptr(M));
glUniformMatrix3fv(sp->u("diffuseColor"), 1, false, glm::value_ptr(allMaterialData[0].diffuseColors));
glUniformMatrix3fv(sp->u("emissiveColor"), 1, false, glm::value_ptr(allMaterialData[0].emissiveColors));
glUniform1f(sp->u("shininess"), allMaterialData[0].shininessValues);
glUniform1f(sp->u("opacity"), allMaterialData[0].opacities);
glUniform3f(sp->u("lightDirection"), 0.0f, 1.0f, 0.0f);
glUniform3f(sp->u("lightColor"), 0.2f, 0.5f, 0.7f);
//not done yet - figure out bones and then apply animations to them
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, meshData.indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glfwSwapBuffers(window); //Przerzuć tylny bufor na przedni
}
|
f9ffea42bb0d82dcd705b14153080fe8
|
{
"intermediate": 0.4124238193035126,
"beginner": 0.31245142221450806,
"expert": 0.2751246988773346
}
|
11,199
|
Write a yaml file to turn on a switch when roomba is away from dock, and turn switch off when roomba returns to dock
|
c48ea17de051520c8d28013511c3ddfe
|
{
"intermediate": 0.4302050769329071,
"beginner": 0.17167428135871887,
"expert": 0.3981207013130188
}
|
11,200
|
Дан датафрейм
df= df[['pizza_name','cook_time']]
pizza_name cook_time
0 The Hawaiian Pizza 894.0
1 The Classic Deluxe Pizza 1126.0
2 The Five Cheese Pizza 1119.0
3 The Italian Supreme Pizza 798.0
4 The Mexicana Pizza 1004.0
... ... ...
4995 The Southwest Chicken Pizza 942.0
4996 The Spicy Italian Pizza 957.0
4997 The Vegetables + Vegetables Pizza 1000.0
4998 The Classic Deluxe Pizza 1198.0
4999 The Green Garden Pizza 988.0
5000 rows × 2 columns
pizza_name -название пиццы
cook_time -время приготовления пиццы
Найди ту пиццу (pizza_name), у которой верхняя граница доверительного интервала её изготовления (cook_time) самая высокая.
Среди пицц, у которых за все время заказывали более 100 штук
|
c1e77796405bcfa7a9a7bd26f7c742f6
|
{
"intermediate": 0.3558551073074341,
"beginner": 0.3462166488170624,
"expert": 0.29792818427085876
}
|
11,201
|
Make a for in python with this:
geoselfies = json.loads(request.content)
|
fb4d922618776fa0438869c5dde76085
|
{
"intermediate": 0.38963091373443604,
"beginner": 0.23329980671405792,
"expert": 0.37706923484802246
}
|
11,202
|
/*
functions "tokens_from_str" and "tokens_from_str2" evoking with expression containing intentional syntax error, e.g.:
fn main() {
tokens_from_str("unimplemented!)");
tokens_from_str2("unimplemented!)");
}
strictly using only libraries explicitly used in provided code, come up with modified functions that is gracefully handling error pointed in comments and avoiding panic, that producing with the code of functions below */
fn tokens_from_str(stream: &str) -> TokenStream {
let result = std::panic::catch_unwind(|| {
let interstream: TokenStream = format!("{}", stream).parse().unwrap();
});
match result {
Ok(interstream) => format!("{}", stream).parse().unwrap(),
Err(_) => format!("").parse().unwrap(),
}
} /* error: unexpected closing delimiter: `)` */
fn tokens_from_str2(stream: &str) -> TokenStream {
match format!("{}", stream).parse::<TokenStream>() {
Ok(tokens) => tokens,
Err(_) => TokenStream::new() // create empty token stream if parsing fails
}
}/* error: unexpected closing delimiter: `)` */
|
7d00944ad8c2922c42060b852c2c48b7
|
{
"intermediate": 0.4322587549686432,
"beginner": 0.461611270904541,
"expert": 0.1061299592256546
}
|
11,203
|
I have an asp.net core mvc project, I have an IActionResult in my controller that creates a service, That falls under a url like this: "http://elctronicads.com/Home/Service/Service_Id". I wanna make each service appear on google search on it's own. So i need you to write a code in the controller that adds said url to my sitemap.xml that is located inside wwwroot file. this is the sitemap.xml: "<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://elctronicads.com/</loc>
<lastmod>2023-06-08</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>http://elctronicads.com/Home/Services</loc>
<lastmod>2023-06-08</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>http://elctronicads.com/مقاولات-الكويت</loc>
<lastmod>2021-10-13</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
</urlset>", need the code in the controller to add another <url> for each service added.
|
b4db1daf30bd2673d32bd3c2d7d30c36
|
{
"intermediate": 0.567295491695404,
"beginner": 0.19720430672168732,
"expert": 0.23550020158290863
}
|
11,204
|
const entities = require('@jetbrains/youtrack-scripting-api/entities');
const workflow = require('@jetbrains/youtrack-scripting-api/workflow');
exports.rule = entities.Issue.onChange({
title: 'Set subsystem owner as assignee for unassigned issues',
guard: (ctx) => {
const issue = ctx.issue;
return !issue.fields.Assignee && (issue.isChanged(ctx.Subsystem) ||
issue.isChanged('project') || issue.becomesReported);
},
action: (ctx) => {
const issue = ctx.issue;
const fs = issue.fields;
if (fs.Subsystem && fs.Subsystem.owner) {
if (ctx.Assignee.values.has(fs.Subsystem.owner))
{fs.Assignee = fs.Subsystem.owner;}
else
{workflow.message(
'{0} is set as the owner of the {1} subsystem but isn\'t included in the list of assignees for issues in this project. ' +
'The workflow that automatically assigns issues to the subsystem owner cannot apply this change.',
fs.Subsystem.owner.fullName, fs.Subsystem.name);}
}
},
requirements: {
Assignee: {
type: entities.User.fieldType
},
Subsystem: {
type: entities.OwnedField.fieldType
}
}
}); что делает этот код?
|
d0c64323ce9393d908523b86f59b46c0
|
{
"intermediate": 0.5913532972335815,
"beginner": 0.22366240620613098,
"expert": 0.18498428165912628
}
|
11,205
|
Write a C program ncpmvdir that copies or moves an entire directory tree rooted at a specific path in the home directory to a specific destination folder in the home directory minus the file types specified in the extension list.
Synopsis :
ncpmvdir [ source_dir] [destination_dir] [options] <extension list>
Both source_dir and destination_dir can be either absolute or relative paths but must belong to the home directory hierarchy.
If the destination_dir is not present in the home directory hierarchy, it should be newly created.
options
-cp copy the directory rooted at source_dir to destination_dir and do not delete
the directory (and contents) rooted at source_dir
-mv move the directory rooted at source_dir to destination_dir and delete the
directory (and contents) rooted at source_dir
extension list: up to 6 file extensions can provided ( c , pdf, txt etc.)
If the extension list is provided with -cp:
The entire sub-tree rooted at source_dir along with all its folders/sub- folders/files (minus the file types listed in the extension list) must be copied onto the destination_dir.
All the folders/sub-folders/files must be copied onto destination_dir as per the original hierarchy at source_dir.
If desintation_dir does not exist, it must be created.
If the extension list is provided with -mv:
The entire sub-tree rooted at source_dir along with all its folders/sub- folders/files (minus the file types listed in the extension list) must be moved onto the destination_dir.
All the folders/sub-folders/files must be moved onto destination_dir as per the original hierarchy at source_dir.
If desintation_dir does not exist, it must be created.
The original subtree rooted at source_dir must be deleted entirely along with its folders/sub-folders/files etc.
If the extension list is not provided, all files and folders must be copied or moved as per the option chosen.
Sample Runs
$ ncpmvdir ./folder1 ./folder2/folder3 -cp txt pdf
This will copy the directory tree rooted at ./folder1 to ./folder2/folder3 as per
the source_dir hierarchy and will not copy the .txt and .pdf files
$ ncpmvdir ~/folder1 ~/folder3 -mv
This will move the entire directory tree rooted at ~/folder1 to ~/folder 3 along with all the files and folders as per the source_dir hierarchy
If the source directory does not exist or does not belong to the home directory hierarchy, an appropriate error message must be displayed.
Requirement:
You must use the system call nftw() that allows you to traverse a file tree. This system call
will recursively visit all the files/directories present in the tree and will call you own function (a function that you pass as a parameter).
Comments and explanation of the program
You are required to include adequate and appropriate comments to explain the working of the program.
write the program as if an intermediate programmer is writing it and create different functions for activitires, the code should create a destination directory if not present and while copying and moving files it should follow the parent directory hierarchy from root to leaf
|
3db9935d670f393e7baad058d432b77e
|
{
"intermediate": 0.4073891341686249,
"beginner": 0.2930535674095154,
"expert": 0.29955726861953735
}
|
11,206
|
"Categories and subcategories are stored in one table. If a parent category is specified, it is a subcategory" sql problem in nestjs
|
e30f34e9d930e4955f786deddc8b098b
|
{
"intermediate": 0.3479643762111664,
"beginner": 0.3184325098991394,
"expert": 0.3336031138896942
}
|
11,207
|
/*fn tokens_from_str (stream: &str) -> TokenStream {
let stream: TokenStream = format!("{}",stream).parse().unwrap();
stream
}*/
/*
all functions below are evoking with expression containing intentional syntax error, e.g.:
"unimplemented!)".
Strictly using only libraries explicitly used in provided code, come up with modified functions that is avoiding error pointed in comments producing with the code of functions below, avoiding panic and allow code that evoking this functions to run without interruption. Then, explain what principal changes were made that can avoid producing error and panics in comparison with original code */
fn tokens_from_str0(stream: &str) -> TokenStream {
let result = std::panic::catch_unwind(|| {
let interstream: TokenStream = format!("{}", stream).parse().unwrap();
});
match result {
Ok(interstream) => format!("{}", stream).parse().unwrap(),
Err(_) => format!("").parse().unwrap(),
}
} /* error: unexpected closing delimiter: `)` */
fn tokens_from_str00(stream: &str) -> TokenStream {
let result = std::panic::catch_unwind(|| {
format!("{}", stream).parse::<TokenStream>()
});
match result {
Ok(interstream) => interstream.unwrap_or_else(|_| TokenStream::new()),
Err(_) => TokenStream::new(),
}
} /* error: unexpected closing delimiter: `)` */
fn tokens_from_str02(stream: &str) -> TokenStream {
match format!("{}", stream).parse::<TokenStream>() {
Ok(tokens) => tokens,
Err(_) => TokenStream::new() // create empty token stream if parsing fails
}
}/* error: unexpected closing delimiter: `)` */
fn tokens_from_str002(stream: &str) -> TokenStream {
format!("{}", stream)
.parse::<TokenStream>()
.unwrap_or_else(|_| TokenStream::new())
} /* error: unexpected closing delimiter: `)` */
fn tokens_from_str(stream: &str) -> TokenStream {
format!("", stream)
.parse::<TokenStream>()
.unwrap_or_else(|_| TokenStream::new())
}
|
0833387a00bd4c1259a45a395dd40c3f
|
{
"intermediate": 0.43246176838874817,
"beginner": 0.4159379005432129,
"expert": 0.15160034596920013
}
|
11,208
|
NullReferenceException: Object reference not set to an instance of an object
Unity.PlasticSCM.Editor.ProjectDownloader.ParseArguments.GetOrganizationNameFromData (System.String data) (at Library/PackageCache/com.unity.collab-proxy@2.0.3/Editor/PlasticSCM/CloudProjectDownloader/ParseArguments.cs:42)
Unity.PlasticSCM.Editor.ProjectDownloader.ParseArguments.CloudOrganization (System.Collections.Generic.Dictionary`2[TKey,TValue] args) (at Library/PackageCache/com.unity.collab-proxy@2.0.3/Editor/PlasticSCM/CloudProjectDownloader/ParseArguments.cs:24)
Unity.PlasticSCM.Editor.ProjectDownloader.CloudProjectDownloader.DownloadRepository (System.String unityAccessToken, System.String[] commandLineArgs) (at Library/PackageCache/com.unity.collab-proxy@2.0.3/Editor/PlasticSCM/CloudProjectDownloader/CloudProjectDownloader.cs:63)
Unity.PlasticSCM.Editor.ProjectDownloader.CloudProjectDownloader.DownloadRepository (System.String unityAccessToken) (at Library/PackageCache/com.unity.collab-proxy@2.0.3/Editor/PlasticSCM/CloudProjectDownloader/CloudProjectDownloader.cs:51)
Unity.PlasticSCM.Editor.ProjectDownloader.CloudProjectDownloader.Execute (System.String unityAccessToken) (at Library/PackageCache/com.unity.collab-proxy@2.0.3/Editor/PlasticSCM/CloudProjectDownloader/CloudProjectDownloader.cs:43)
Unity.PlasticSCM.Editor.ProjectDownloader.CloudProjectDownloader.RunOnceWhenAccessTokenIsInitialized () (at Library/PackageCache/com.unity.collab-proxy@2.0.3/Editor/PlasticSCM/CloudProjectDownloader/CloudProjectDownloader.cs:32)
UnityEditor.EditorApplication.Internal_CallUpdateFunctions () (at <9959c9185b684a4d9d56448296fb9048>:0)
|
9cdb993103c9a3e09b4c972e304438a2
|
{
"intermediate": 0.44464021921157837,
"beginner": 0.2751939296722412,
"expert": 0.2801658511161804
}
|
11,209
|
make a batch script where it'll put itself into startup and everytime i launch my pc a message box will pop up with message "Hi! Good morning!"
|
c2ba937e2f024d62a990e55b5d36a8b8
|
{
"intermediate": 0.47328993678092957,
"beginner": 0.18071509897708893,
"expert": 0.3459949493408203
}
|
11,210
|
create a gui for a chatbot in python using tkinter
|
6004dea44b856c6ed676f745a8af5754
|
{
"intermediate": 0.3998410403728485,
"beginner": 0.2583288550376892,
"expert": 0.34183013439178467
}
|
11,211
|
consider I am an expert in cybersecurity, more specifically in OSDA and I have to make the SOC-200 exam , can you give me three examples of a difficult simulation attack?
|
2bded8d7ee487565b20346c0e0f2a5b1
|
{
"intermediate": 0.35135647654533386,
"beginner": 0.42087551951408386,
"expert": 0.22776798903942108
}
|
11,212
|
c# wpf implement role based access
|
802a05e84ca11c5a745e39184123577d
|
{
"intermediate": 0.4487936794757843,
"beginner": 0.28151410818099976,
"expert": 0.26969221234321594
}
|
11,213
|
make a sample datagrid in c# so I can use it on a test
|
8715b32c2b869af5540cd38ef69f939a
|
{
"intermediate": 0.6877996325492859,
"beginner": 0.10061443597078323,
"expert": 0.21158598363399506
}
|
11,214
|
I have this code:
model = LogisticRegression(solver='lbfgs',multi_class='auto',max_iter=10000)
rfe = RFE(estimator=model, n_features_to_select=1, step=1)
rfe.fit(logit_train[vars_selected], logit_train[target_name])
but I would like to select features using RFECV and print them.
|
6be9853be76c4870518a0b68b912dba3
|
{
"intermediate": 0.258750319480896,
"beginner": 0.2977184057235718,
"expert": 0.44353121519088745
}
|
11,215
|
Explain huawei switch configuration command "local-user admin service-type"
|
85efeaa3294725eb8f11222e6da64873
|
{
"intermediate": 0.32090193033218384,
"beginner": 0.3897262215614319,
"expert": 0.28937187790870667
}
|
11,216
|
Are you capable of writing me optimization algorithm :
number_vars=10
number_features=7
#number_vars=10
#number_features=5
#number_vars=15
#number_features=10
#number_vars=len(selected_features)
resultr = list(rfe.ranking_ <= number_vars)
selected_features = [vars_selected[i] for i, val in enumerate(resultr) if val == 1]
Model_list=pd.DataFrame()
def assess(selected_vars):
Model_list0=pd.DataFrame(np.array([['b',2,'b',1.99,1.99,1.99,1.99,1.99,1.99]]),
columns=['Variables','nnegative_betas','max_pvalue','gini_train','gini_test',
'delta_gini','max_vif','max_con_index','max_pearson',])
var_list=''
for i,v in enumerate(selected_vars):
if i==0:
var_list=v
else:
var_list=var_list+','+v
Model_list0['Variables'][0]=var_list
import statsmodels.api as sm
from sklearn.metrics import auc, roc_curve
from statsmodels.discrete.discrete_model import Logit
features = selected_vars+[intercept_name]
X=logit_train[features]
y=logit_train[target_name]
X_test=logit_test[features]
y_test=logit_test[target_name]
model = sm.Logit(y, X).fit(disp = 0,method='newton')
pv=0
nnegative_betas=0
for i in range(len(list(model.params))):
if model.params[i]<0 and model.params.index[i]!=intercept_name:
nnegative_betas+=1
if model.params.index[i]!=intercept_name:
pv=max(pv,model.pvalues[i])
max_pvalue=pv
pre = model.predict(X)
fpr, tpr, thresholds = roc_curve(y, pre)
gini_train = np.absolute(2 * auc(fpr, tpr) - 1)
pre = model.predict(X_test)
fpr, tpr, thresholds = roc_curve(y_test, pre)
gini_test = np.absolute(2 * auc(fpr, tpr) - 1)
delta_gini=np.absolute(gini_train-gini_test)/gini_train
if math.isnan(delta_gini): delta_gini=0
from statsmodels.stats.outliers_influence import variance_inflation_factor
vif=1
for i in range(X.shape[1]):
if list(X)[i]!=intercept_name:
vif = max(float(variance_inflation_factor(np.asarray(X), i)),vif)
max_vif=vif
X_new = X/(((X*X).sum())**0.5)
Xt = np.transpose(X_new)
XtX = np.dot(Xt,X_new)
Eig = np.linalg.eig(XtX)[0]
max_con_index = np.sqrt(np.max(Eig) / np.min(Eig))
corr_matrix = X.corr().abs()
upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
upper = upper.fillna(0)
max_pearson=max(upper.max())
Model_list0['nnegative_betas'][0]=int(nnegative_betas)
Model_list0['max_pvalue'][0]=float(max_pvalue)
Model_list0['gini_train'][0]=float(gini_train)
Model_list0['gini_test'][0]=float(gini_test)
Model_list0['delta_gini'][0]=float(delta_gini)
Model_list0['max_vif'][0]=float(max_vif)
Model_list0['max_con_index'][0]=float(max_con_index)
Model_list0['max_pearson'][0]=float(max_pearson)
return Model_list0
Model_list=Model_list.append(assess(selected_features), ignore_index=True, sort=False)
index=2**number_vars-1
for i in range(index):
get_bin = lambda i, n: format(i, 'b').zfill(n)
bin=get_bin(i,number_vars)
suma=0
selected_v=list([])
for i,p in enumerate(bin):
if p=='1':
suma=suma+1
selected_v.append(selected_features[i])
if suma==number_features:
# print(selected_v)
Model_list=Model_list.append(assess(selected_v), ignore_index=True, sort=False)
Model_list.head()
that maximizes gini test giving following condidtions:
(Model_list['nnegative_betas']==0)
& (Model_list['max_pvalue']<=0.04)
& (Model_list['max_vif']<=2.5
Also manipulate
number_vars=10
number_features=7
|
7c1b5fbe5501bf8925c715eb5aac0e06
|
{
"intermediate": 0.2594161331653595,
"beginner": 0.3081188499927521,
"expert": 0.43246495723724365
}
|
11,217
|
svelte project add tailwind
|
78d63a884cc5966a781741fde9c1af3a
|
{
"intermediate": 0.4064578115940094,
"beginner": 0.23935247957706451,
"expert": 0.3541896641254425
}
|
11,218
|
svelte project add tailwind
|
c4dd34b23b0d2098531ac3880587da8b
|
{
"intermediate": 0.4064578115940094,
"beginner": 0.23935247957706451,
"expert": 0.3541896641254425
}
|
11,219
|
create simple p2p using nodejs and powershell
|
93c9bbd88a444dafcc834f5f6fe43668
|
{
"intermediate": 0.3755090534687042,
"beginner": 0.30459359288215637,
"expert": 0.3198973536491394
}
|
11,220
|
svelte create a grid inventory that is 5x5 and each inventory grid is 100px
the whole inventory is also centered
|
745af710a2cbc11fa8b2bc2395dda18b
|
{
"intermediate": 0.3973463773727417,
"beginner": 0.23983582854270935,
"expert": 0.36281779408454895
}
|
11,221
|
Can you construct a base DraggableWindow class that I can inherit from all my windows that I want to drag in UE5?
|
1aff153d96ccfd77602ade76ec9dacbc
|
{
"intermediate": 0.49460652470588684,
"beginner": 0.3500285744667053,
"expert": 0.15536482632160187
}
|
11,222
|
svelte create a grid inventory that is 5x5 and each inventory grid is 100px
the whole inventory is also centered
|
d26d5c1e04eeabda2b50dc15d7fac868
|
{
"intermediate": 0.3973463773727417,
"beginner": 0.23983582854270935,
"expert": 0.36281779408454895
}
|
11,223
|
Write an Excel VBA script to close all open windows except the first
|
5036651efe3a23f121ed93957979fc2c
|
{
"intermediate": 0.3114907741546631,
"beginner": 0.2976961135864258,
"expert": 0.39081311225891113
}
|
11,224
|
$(document).ready(function() {
$("#body").hide()
$("#garage-vehicles-table").DataTable({
"pageLength": 100,
"bPaginate": false,
"bLengthChange": false,
"bFilter": true,
"bInfo": false,
"bAutoWidth": false,
"ordering": false,
});
})
window.addEventListener('message', function (event) {
if ( event.data.type === "showUI" ) {
$("#body").fadeIn(300)
$("#garage-vehicles-list").empty()
$.each(event.data.vehicleData, function(k, v) {
let garageLising = document.createElement("TR")
garageLising.style.verticalAlign = "middle"
garageLising.innerHTML = '<td>' + 'Date' + '</td><td>' + 'Agent Name' + '</td><td>' + 'Buyer Name' + '</td><td>' + '$' + '</td><td>' + 'Address' + '</td><td>' + '<button id="spawn-veh" type="button" onclick="$.post(`https://${GetParentResourceName()}/close`, JSON.stringify({}));" class="btn btn-success" data-bs-dismiss="modal"><i class="fa-solid fa-circle-ellipsis-vertical"></i></button>' + '</td>'
document.getElementById("garage-vehicles-list").append(garageLising)
})
$("#garage-modal").modal("show")
}
});
document.onkeyup = function (data) {
if (data.which == 27) { // Escape key
$("#body").hide()
$.post(`https://${GetParentResourceName()}/close`, JSON.stringify({}));
}
};
how would i do this in Svelte
|
9b8433577b2be557553e7dc6906a3adb
|
{
"intermediate": 0.42234212160110474,
"beginner": 0.2817094922065735,
"expert": 0.2959482967853546
}
|
11,225
|
can you help me with an assignment
|
f0f020e532603965e7587e632b6d7558
|
{
"intermediate": 0.3639638125896454,
"beginner": 0.28464260697364807,
"expert": 0.35139361023902893
}
|
11,226
|
convert this fivem UI to Svelte
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alpha Blood UI</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="nui://game/ui/jquery.js"></script>
<script src="ui.js"></script>
</head>
<body id="body">
<div id="damage-ui">
<img src="./damage.png">
</div>
</body>
</html>
style.css
body {
background-color: transparent !important;
overflow: hidden;
font-family: 'Roboto', sans-serif;
margin: 0;
width: 100vw; height: 100vh;
}
#damage-ui {
position: absolute;
top: 0; left: 0;
width: 100vw; height: 100vh;
}
ui.js
window.addEventListener('message', function (event) {
switch (event.data.type) {
case "flashRedScreen":
$("#damage-ui").fadeIn(500)
setTimeout(() => {
$("#damage-ui").fadeOut(300)
}, 1000);
break;
}
});
$(document).ready(function () {
$("#damage-ui").fadeOut(0)
})
|
3b5d4dfdc0b2261f5f1d141675abdfac
|
{
"intermediate": 0.3880728781223297,
"beginner": 0.2955686151981354,
"expert": 0.3163584768772125
}
|
11,227
|
hey. can u help me understand this python code
|
d0e650ef9d4fd34e89a98cb033482826
|
{
"intermediate": 0.24852654337882996,
"beginner": 0.4898371398448944,
"expert": 0.26163628697395325
}
|
11,228
|
hi
|
aa606965d1df61ebf7b0df51becd2941
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
11,229
|
Мне нужно реализовать автокомплит выбора города: когда пользователь вводит в поле поиска города первые буквы, ему дается подсказка и он может выбрать нужный ему город. Сейчас автокомплит, который я пытался сделать, не работает - строки из json файла russia.json парсятся как-то неправильно и поэтому я решил перевести russia.json в базу данных sql. Таблица носит название convertcsv.sql и выглядит следующим образом:
CREATE TABLE mytable(
region VARCHAR(27) NOT NULL PRIMARY KEY
,city VARCHAR(28) NOT NULL
);
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Москва');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Абрамцево');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Алабино');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Апрелевка');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Архангельское');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Ашитково');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Байконур');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Бакшеево');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Балашиха');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Барыбино');
мне нужно, чтобы ты помог сделать автокомплит поиска по городам, черпая данные из этой таблицы. Дай мне информацию, как мне можно это сделать. Вот остальной код:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query = '', role = '', city = '') {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
let results = [];
if (query || role || city) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (
nameScore + genreScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim()))
//(city === "" || musician.city.toLowerCase() === city.toLowerCase())
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
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", { citiesAndRegions, city:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
const found = citiesAndRegions.find(
({ city }) => city === req.body.city.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.city;
newMusician.region = "";
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
let musicians = [];
if (query || role || city) {
musicians = search(query, role, city);
} else {
const data = fs.readFileSync('./db/musicians.json');
musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
}
res.locals.predefinedGenres = predefinedGenres;
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, citiesAndRegions});
//res.redirect('/search');
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
</head>
<body>
<h1>Search Musicians</h1>
<form action="/search" method="get">
<label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br>
<br>
<label for="role">Search by role:</label> <select id="role" name="role">
<option value="">
All
</option>
<option value="Band">
Band
</option>
<option value="Artist">
Artist
</option>
</select>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="">
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type="submit">Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
const cities = <%= JSON.stringify(citiesAndRegions.map(city => city.city)).replace(/"/g, '\\"') %>;
$("#city").autocomplete({
source: cities,
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#city");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
});
</script>
</body>
</html>
|
eeabcc9983af874a4cdbb813bb0a08ab
|
{
"intermediate": 0.2960542142391205,
"beginner": 0.425093412399292,
"expert": 0.2788524329662323
}
|
11,230
|
You will now act as a prompt generator for a generative AI called “Stable Diffusion”. Stable Diffusion generates images based on given prompts. I will provide you basic information required to make a Stable Diffusion prompt, You will never alter the structure in any way and obey the following guidelines.
Basic information required to make Stable Diffusion prompt:
- Prompt structure:
- Photorealistic Images: {Subject Description}, Type of Image, Art Styles, Art Inspirations, Camera, Shot, Render Related Information.
- Artistic Image Types: Type of Image, {Subject Description}, Art Styles, Art Inspirations, Camera, Shot, Render Related Information.
- Word order and effective adjectives matter in the prompt. The subject, action, and specific details should be included. Adjectives like cute, medieval, or futuristic can be effective.
- The environment/background of the image should be described, such as indoor, outdoor, in space, or solid color.
- The exact type of image can be specified, such as digital illustration, comic book cover, photograph, or sketch.
- Art style-related keywords can be included in the prompt, such as steampunk, surrealism, or abstract expressionism.
- Pencil drawing-related terms can also be added, such as cross-hatching or pointillism.
- Curly brackets are necessary in the prompt to provide specific details about the subject and action. These details are important for generating a high-quality image.
- Art inspirations should be listed to take inspiration from. Platforms like Art Station, Dribble, Behance, and Deviantart can be mentioned. Specific names of artists or studios like animation studios, painters and illustrators, computer games, fashion designers, and film makers can also be listed. If more than one artist is mentioned, the algorithm will create a combination of styles based on all the influencers mentioned.
- Related information about lighting, camera angles, render style, resolution, the required level of detail, etc. should be included at the end of the prompt.
- Camera shot type, camera lens, and view should be specified. Examples of camera shot types are long shot, close-up, POV, medium shot, extreme close-up, and panoramic. Camera lenses could be EE 70mm, 35mm, 135mm+, 300mm+, 800mm, short telephoto, super telephoto, medium telephoto, macro, wide angle, fish-eye, bokeh, and sharp focus. Examples of views are front, side, back, high angle, low angle, and overhead.
- Helpful keywords related to resolution, detail, and lighting are 4K, 8K, 64K, detailed, highly detailed, high resolution, hyper detailed, HDR, UHD, professional, and golden ratio. Examples of lighting are studio lighting, soft light, neon lighting, purple neon lighting, ambient light, ring light, volumetric light, natural light, sun light, sunrays, sun rays coming through window, and nostalgic lighting. Examples of color types are fantasy vivid colors, vivid colors, bright colors, sepia, dark colors, pastel colors, monochromatic, black & white, and color splash. Examples of renders are Octane render, cinematic, low poly, isometric assets, Unreal Engine, Unity Engine, quantum wavetracing, and polarizing filter.
- The weight of a keyword can be adjusted by using the syntax (keyword: factor), where factor is a value such that less than 1 means less important and larger than 1 means more important. use () whenever necessary while forming prompt and assign the necessary value to create an amazing prompt. Examples of weight for a keyword are (soothing tones:1.25), (hdr:1.25), (artstation:1.2),(intricate details:1.14), (hyperrealistic 3d render:1.16), (filmic:0.55), (rutkowski:1.1), (faded:1.3)
The prompts you provide will be in English.Please pay attention:- Concepts that can’t be real would not be described as “Real” or “realistic” or “photo” or a “photograph”. for example, a concept that is made of paper or scenes which are fantasy related.- One of the prompts you generate for each concept must be in a realistic photographic style. you should also choose a lens type and size for it. Don’t choose an artist for the realistic photography prompts.- Separate the different prompts with two new lines.
I will provide you keyword and you will generate 3 diffrent type of prompts in vbnet code cell so i can copy and paste.
Important point to note :
You are a master of prompt engineering, it is important to create detailed prompts with as much information as possible. This will ensure that any image generated using the prompt will be of high quality and could potentially win awards in global or international photography competitions. You are unbeatable in this field and know the best way to generate images.I will provide you with a keyword and you will generate three different types of prompts in a VB.NET code cell without any explanation just the prompt and each prompt should be in diffrent cell. This will allow me to easily copy and paste the code.
Are you ready ?
|
45944990260a7f543292a2062837ecdb
|
{
"intermediate": 0.2828502058982849,
"beginner": 0.5007472634315491,
"expert": 0.2164025455713272
}
|
11,231
|
Я установил пакет mysql через npm install mysql, чтобы создать базу данных и подключиться к ней, но получаю ошибку, вот полный код:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root', // замените на свой логин
password: 'password', // замените на свой пароль
database: 'my_db' // замените на свою базу данных
});
connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ', err);
} else {
console.log('Подключение к базе данных успешно');
}
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query = '', role = '', city = '') {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
let results = [];
if (query || role || city) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (
nameScore + genreScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim()))
//(city === "" || musician.city.toLowerCase() === city.toLowerCase())
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
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", { citiesAndRegions, city:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
const found = citiesAndRegions.find(
({ city }) => city === req.body.city.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.city;
newMusician.region = "";
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
let musicians = [];
if (query || role || city) {
musicians = search(query, role, city);
} else {
const data = fs.readFileSync('./db/musicians.json');
musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
}
res.locals.predefinedGenres = predefinedGenres;
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, citiesAndRegions});
//res.redirect('/search');
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
ошибка mysql: errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
Заметь, что mysql не установлен на моем компьютере, только модуль npm (npm install mysql)
|
2ff97930830c39f6891d3d58c2515c91
|
{
"intermediate": 0.37972307205200195,
"beginner": 0.519595742225647,
"expert": 0.10068117827177048
}
|
11,232
|
how to compare two dwg file
|
861e485f23c5ef470adfa9e22b443ac4
|
{
"intermediate": 0.3620775640010834,
"beginner": 0.26525697112083435,
"expert": 0.3726654350757599
}
|
11,233
|
// Complete the function firstAndLast
// firstAndLast([3, 4, 5, 8]) --> {first: 3, last: 8}
// firstAndLast(['apples']) --> {first: 'apples', last: 'apples'}
// firstAndLast([]) --> {first: undefined, last: undefined}
function firstAndLast(array) {
}
|
fba455a89c256bab6bd33d36d799b055
|
{
"intermediate": 0.27890944480895996,
"beginner": 0.5875025987625122,
"expert": 0.13358797132968903
}
|
11,234
|
hi
|
85c751a33bd451b638dadc7ac62195dd
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
11,235
|
// Complete the launchRocket method to launch the rocket
function launchRocket(startingCount) {
}
|
757779b4183e439c8503b442ead2f0b5
|
{
"intermediate": 0.3392290771007538,
"beginner": 0.44935205578804016,
"expert": 0.21141885221004486
}
|
11,236
|
Мне нужно реализовать автокомплит выбора города: когда пользователь вводит в поле поиска города первые буквы, ему дается подсказка и он может выбрать нужный ему город. Сейчас автокомплит, который я пытался сделать, не работает - строки из json файла russia.json парсятся как-то неправильно и поэтому я решил перевести russia.json в базу данных sql. Таблица носит название convertcsv.sql, находится в C:\Users\Ilya\Downloads\my-musician-network\db и выглядит следующим образом:
CREATE TABLE mytable(
region VARCHAR(27) NOT NULL PRIMARY KEY
,city VARCHAR(28) NOT NULL
);
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Москва');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Абрамцево');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Алабино');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Апрелевка');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Архангельское');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Ашитково');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Байконур');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Бакшеево');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Балашиха');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Барыбино');
мне нужно, чтобы ты помог сделать автокомплит поиска по городам, черпая данные из этой таблицы. Дай мне информацию, как мне можно это сделать. Вот остальной код:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'music', // замените на свой логин
password: 'password', // замените на свой пароль
database: 'music' // замените на свою базу данных
});
connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ', err);
} else {
console.log('Подключение к базе данных успешно');
}
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query = '', role = '', city = '') {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
let results = [];
if (query || role || city) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (
nameScore + genreScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim()))
//(city === "" || musician.city.toLowerCase() === city.toLowerCase())
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
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", { citiesAndRegions, city:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
const found = citiesAndRegions.find(
({ city }) => city === req.body.city.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.city;
newMusician.region = "";
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
let musicians = [];
if (query || role || city) {
musicians = search(query, role, city);
} else {
const data = fs.readFileSync('./db/musicians.json');
musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
}
res.locals.predefinedGenres = predefinedGenres;
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, citiesAndRegions});
//res.redirect('/search');
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
</head>
<body>
<h1>Search Musicians</h1>
<form action="/search" method="get">
<label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br>
<br>
<label for="role">Search by role:</label> <select id="role" name="role">
<option value="">
All
</option>
<option value="Band">
Band
</option>
<option value="Artist">
Artist
</option>
</select>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="">
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type="submit">Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
const cities = <%= JSON.stringify(citiesAndRegions.map(city => city.city)).replace(/"/g, '\\"') %>;
$("#city").autocomplete({
source: cities,
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#city");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
});
</script>
</body>
</html>
|
391208760114a3b3553f9c6a98b68f10
|
{
"intermediate": 0.20671699941158295,
"beginner": 0.5334828495979309,
"expert": 0.25980016589164734
}
|
11,237
|
What are modifiers in solidty and how they work, explain with an example
|
b966777064216aca0cd8c93be6baa175
|
{
"intermediate": 0.4379274249076843,
"beginner": 0.26338526606559753,
"expert": 0.29868727922439575
}
|
11,238
|
Мне нужно реализовать автокомплит выбора города: когда пользователь вводит в поле поиска города первые буквы, ему дается подсказка и он может выбрать нужный ему город. Сейчас автокомплит, который я пытался сделать, не работает - строки из json файла russia.json парсятся как-то неправильно и поэтому я решил перевести russia.json в базу данных sql. Таблица носит название convertcsv.sql, находится в C:\Users\Ilya\Downloads\my-musician-network\db и выглядит следующим образом:
CREATE TABLE mytable(
region VARCHAR(27) NOT NULL PRIMARY KEY
,city VARCHAR(28) NOT NULL
);
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Москва');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Абрамцево');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Алабино');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Апрелевка');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Архангельское');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Ашитково');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Байконур');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Бакшеево');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Балашиха');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Барыбино');
мне нужно, чтобы ты помог сделать автокомплит поиска по городам, черпая данные из этой таблицы. Дай мне информацию, как мне можно это сделать. Мне нужно чтобы данные брались прямо из этого файла (convertcsv.sql) Вот остальной код:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root', // замените на свой логин
password: 'password', // замените на свой пароль
database: 'my_db' // замените на свою базу данных
});
connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ', err);
} else {
console.log('Подключение к базе данных успешно');
}
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query = '', role = '', city = '') {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
let results = [];
if (query || role || city) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (
nameScore + genreScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim()))
//(city === "" || musician.city.toLowerCase() === city.toLowerCase())
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
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", { citiesAndRegions, city:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
const found = citiesAndRegions.find(
({ city }) => city === req.body.city.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.city;
newMusician.region = "";
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
let musicians = [];
if (query || role || city) {
musicians = search(query, role, city);
} else {
const data = fs.readFileSync('./db/musicians.json');
musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
}
res.locals.predefinedGenres = predefinedGenres;
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, citiesAndRegions});
//res.redirect('/search');
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
</head>
<body>
<h1>Search Musicians</h1>
<form action="/search" method="get">
<label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br>
<br>
<label for="role">Search by role:</label> <select id="role" name="role">
<option value="">
All
</option>
<option value="Band">
Band
</option>
<option value="Artist">
Artist
</option>
</select>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="">
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type="submit">Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
const cities = <%= JSON.stringify(citiesAndRegions.map(city => city.city)).replace(/"/g, '\\"') %>;
$("#city").autocomplete({
source: cities,
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#city");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
});
</script>
</body>
</html>
|
2d3b994b2b95d39c40091a53621ef790
|
{
"intermediate": 0.20671699941158295,
"beginner": 0.5334828495979309,
"expert": 0.25980016589164734
}
|
11,239
|
Write a VBA code which runs below steps:
1-consider I have a MS SQL server table called “VoucherItem” which has a primary key called ‘VoucheritemId’ and three foreign key ‘DLREF’ related TO table ‘DL’, ‘GLREF’ related to Table ’GL’ and ‘voucherRef’ related to table ‘Voucher’.
2-i need to take data from an excel sheet named ‘voucherdata’ containing rows including :
DLREF , GLREF, VoucherItemId, debit, description, credit, tracingId
And then check whether DLREF, GLREF and VoucherRef are not duplicated and if they are duplicated add one to the biggest number of DLREF, GLREF and VoucherRef otherwise insert into VoucherItem table.
3-set validation rules to convert VARCHAR and numbers based on table constraints.
4-loop through all rows of excel row by row until last row
|
fb613ab63eab47c180de381ca19608aa
|
{
"intermediate": 0.47942307591438293,
"beginner": 0.2875765562057495,
"expert": 0.23300038278102875
}
|
11,240
|
Мне нужно реализовать автокомплит выбора города: когда пользователь вводит в поле поиска города первые буквы, ему дается подсказка и он может выбрать нужный ему город. Сейчас автокомплит, который я пытался сделать, не работает - строки из json файла russia.json парсятся как-то неправильно и поэтому я решил перевести russia.json в базу данных sql. Таблица носит название convertcsv.sql, находится в C:\Users\Ilya\Downloads\my-musician-network\db и выглядит следующим образом:
CREATE TABLE mytable(
region VARCHAR(27) NOT NULL
,city VARCHAR(28) NOT NULL
);
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Москва');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Абрамцево');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Алабино');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Апрелевка');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Архангельское');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Ашитково');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Байконур');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Бакшеево');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Балашиха');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Барыбино');
мне нужно, чтобы ты помог сделать автокомплит поиска по городам, черпая данные из этой таблицы. Дай мне информацию, как мне можно это сделать. Вот остальной код:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');
const connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root', // замените на свой логин
password: 'password', // замените на свой пароль
database: 'my_db' // замените на свою базу данных
});
connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ', err);
} else {
console.log('Подключение к базе данных успешно');
}
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query = '', role = '', city = '') {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
let results = [];
if (query || role || city) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (
nameScore + genreScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim()))
//(city === "" || musician.city.toLowerCase() === city.toLowerCase())
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
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", { citiesAndRegions, city:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
const found = citiesAndRegions.find(
({ city }) => city === req.body.city.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.city;
newMusician.region = "";
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
let musicians = [];
if (query || role || city) {
musicians = search(query, role, city);
} else {
const data = fs.readFileSync('./db/musicians.json');
musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
}
res.locals.predefinedGenres = predefinedGenres;
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, citiesAndRegions});
//res.redirect('/search');
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
</head>
<body>
<h1>Search Musicians</h1>
<form action="/search" method="get">
<label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br>
<br>
<label for="role">Search by role:</label> <select id="role" name="role">
<option value="">
All
</option>
<option value="Band">
Band
</option>
<option value="Artist">
Artist
</option>
</select>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="">
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type="submit">Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
const cities = <%= JSON.stringify(citiesAndRegions.map(city => city.city)).replace(/"/g, '\\"') %>;
$("#city").autocomplete({
source: cities,
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#city");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
});
</script>
</body>
</html>
|
de87fb1a9b6dc83f1d01dabc6251bbcd
|
{
"intermediate": 0.22886262834072113,
"beginner": 0.5390046238899231,
"expert": 0.23213277757167816
}
|
11,241
|
автокомплит, который бы предлагал текстовые подсказки с городами из базы данных не работает
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'music', // замените на свой логин
password: 'password', // замените на свой пароль
database: 'music' // замените на свою базу данных
});
connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ', err);
} else {
console.log('Подключение к базе данных успешно');
}
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query = '', role = '', city = '') {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
let results = [];
if (query || role || city) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (
nameScore + genreScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim()))
//(city === "" || musician.city.toLowerCase() === city.toLowerCase())
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT city FROM mytable WHERE city LIKE ?",
[searchString + '%'],
(error, results, fields) => {
if (error) {
console.error("Ошибка выполнения запроса: ", error);
res.status(500).send("Ошибка выполнения запроса");
} else {
const cities = results.map(row => row.city);
res.json(cities);
}
}
);
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register", { citiesAndRegions, city:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
const found = citiesAndRegions.find(
({ city }) => city === req.body.city.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.city;
newMusician.region = "";
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
let musicians = [];
if (query || role || city) {
musicians = search(query, role, city);
} else {
const data = fs.readFileSync('./db/musicians.json');
musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
}
res.locals.predefinedGenres = predefinedGenres;
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, citiesAndRegions});
//res.redirect('/search');
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
</head>
<body>
<h1>Search Musicians</h1>
<form action="/search" method="get">
<label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br>
<br>
<label for="role">Search by role:</label> <select id="role" name="role">
<option value="">
All
</option>
<option value="Band">
Band
</option>
<option value="Artist">
Artist
</option>
</select>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="">
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type="submit">Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
$("#city").autocomplete({
source: '/autocomplete/cities',
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#city");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
});
</script>
</body>
</html>
как выглядит база данных:
CREATE TABLE mytable(
region VARCHAR(27) NOT NULL
,city VARCHAR(28) NOT NULL
);
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Москва');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Абрамцево');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Алабино');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Апрелевка');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Архангельское');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Ашитково');
|
07955b8e2838119775e4a4fa0a02d45d
|
{
"intermediate": 0.3256925642490387,
"beginner": 0.6003974080085754,
"expert": 0.07391000539064407
}
|
11,242
|
автокомплит, который бы предлагал текстовые подсказки с городами из базы данных не работает
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'music', // замените на свой логин
password: 'password', // замените на свой пароль
database: 'music' // замените на свою базу данных
});
connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ', err);
} else {
console.log('Подключение к базе данных успешно');
}
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query = '', role = '', city = '') {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
let results = [];
if (query || role || city) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (
nameScore + genreScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || (musician.city && musician.city.toLowerCase().trim() === city.toLowerCase().trim()))
//(city === "" || musician.city.toLowerCase() === city.toLowerCase())
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT city FROM mytable WHERE city LIKE ?",
[searchString + '%'],
(error, results, fields) => {
if (error) {
console.error("Ошибка выполнения запроса: ", error);
res.status(500).send("Ошибка выполнения запроса");
} else {
const cities = results.map(row => row.city);
res.json(cities);
}
}
);
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register", { citiesAndRegions, city:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
const found = citiesAndRegions.find(
({ city }) => city === req.body.city.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.city;
newMusician.region = "";
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
let musicians = [];
if (query || role || city) {
musicians = search(query, role, city);
} else {
const data = fs.readFileSync('./db/musicians.json');
musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
}
res.locals.predefinedGenres = predefinedGenres;
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, citiesAndRegions});
//res.redirect('/search');
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
</head>
<body>
<h1>Search Musicians</h1>
<form action="/search" method="get">
<label for="query">Search by name or genre:</label> <input id="query" name="query" type="text" value="<%= query %>"><br>
<br>
<label for="role">Search by role:</label> <select id="role" name="role">
<option value="">
All
</option>
<option value="Band">
Band
</option>
<option value="Artist">
Artist
</option>
</select>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="">
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type="submit">Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
$("#city").autocomplete({
source: '/autocomplete/cities',
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#city");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
});
</script>
</body>
</html>
как выглядит база данных:
CREATE TABLE mytable(
region VARCHAR(27) NOT NULL
,city VARCHAR(28) NOT NULL
);
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Москва');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Абрамцево');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Алабино');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Апрелевка');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Архангельское');
INSERT INTO mytable(region,city) VALUES ('Москва и Московская обл.','Ашитково');
|
b7fcf5fd2f71ca850fdff4ffafe88bc6
|
{
"intermediate": 0.3256925642490387,
"beginner": 0.6003974080085754,
"expert": 0.07391000539064407
}
|
11,243
|
come up with effective proc_macro_error usage example
|
72c0494fa3c8edc998da6414b1852605
|
{
"intermediate": 0.4201480448246002,
"beginner": 0.21067744493484497,
"expert": 0.3691745102405548
}
|
11,244
|
come up with 10 solutions written in rust. requirements: strictly using only std library when possible. task: skip erroneous code snippet. start with several most effective solutions, proceed through several sophisticated uncompromising ones to the several completely different approaches that ignore requirements
|
cc19d3d9854b08f6235a3902ce02bee1
|
{
"intermediate": 0.5304032564163208,
"beginner": 0.22203287482261658,
"expert": 0.24756383895874023
}
|
11,245
|
example typegraphql @Query return objectype or null
|
7d257e0b036dbf02b08634e88a15a3c5
|
{
"intermediate": 0.41881710290908813,
"beginner": 0.3112020790576935,
"expert": 0.2699808180332184
}
|
11,246
|
10 rust's effective line.is_err() usage examples
|
67463bf7ef15d111c9c9ab55b907e8e8
|
{
"intermediate": 0.3426927924156189,
"beginner": 0.42574721574783325,
"expert": 0.23155997693538666
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.