row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
10,947
|
write this code in C
|
3188dd05832a3de047c075cede9c3f59
|
{
"intermediate": 0.18730394542217255,
"beginner": 0.5402274131774902,
"expert": 0.27246859669685364
}
|
10,948
|
how to fix: Error: Cannot determine GraphQL output type for of class. Is the value, that is used as its TS type or explicit type, decorated with a proper decorator or is it a proper output value
|
d37af9967a025a60c53a5e357a534c4b
|
{
"intermediate": 0.359896183013916,
"beginner": 0.5077770352363586,
"expert": 0.13232679665088654
}
|
10,949
|
Can you see any flows in this system:
%%file anomaly.py
import json
import os
import time
import numpy as np
import pandas as pd
import socket
import logging
from datetime import datetime
from joblib import load
from confluent_kafka import Producer, Consumer
from multiprocessing import Process
KAFKA_BROKER = 'broker:9092'
TRANSACTION_TOPIC = 'transactions'
TRANSACTOPM_CG = 'transactions'
ANOMALY_TOPIC = 'anomaly'
NUM_PARTITIONS = 3
client_ids = np.arange(1, 10001)
warnings = 0
clients = {'client_id': client_ids, 'Warning': warnings}
clients= pd.DataFrame(clients)
#MODEL_PATH = os.path.abspath('isolation_forest.joblib')
def create_producer():
try:
producer = Producer({
"bootstrap.servers":KAFKA_BROKER,
"client.id": socket.gethostname(),
"enable.idempotence": True,
"batch.size": 64000,
"linger.ms":10,
"acks": "all",
"retries": 5,
"delivery.timeout.ms":1000
})
except Exception as e:
logging.exception("nie mogę utworzyć producenta")
producer = None
return producer
def create_consumer(topic, group_id):
try:
consumer = Consumer({
"bootstrap.servers": KAFKA_BROKER,
"group.id": group_id,
"client.id": socket.gethostname(),
"isolation.level":"read_committed",
"default.topic.config":{
"auto.offset.reset":"latest",
"enable.auto.commit": False
}
})
consumer.subscribe([topic])
except Exception as e:
logging.exception("nie mogę utworzyć konsumenta")
consumer = None
return consumer
def detekcja_anomalii():
consumer = create_consumer(topic=TRANSACTION_TOPIC, group_id=TRANSACTOPM_CG)
producer = create_producer()
first_check=load("first_check.pkl")
second_check=laad("second_check.pkl")
isolation_first=("first_isolation.pkl")
isolation_second=("second_isolation.pkl")
#clf = load(MODEL_PATH)
while True:
message = consumer.poll()
if message is None:
continue
if message.error():
logging.error(f"CONSUMER error: {message.error()}")
continue
record = json.loads(message.value().decode('utf-8'))
data = record['data']
if clients[record['ID']-1,1] >= 2:
_id=str(record["ID"])
record = {
"id": _id,
"data": "Transakcja zablokowana-wymagana autoryzacja tożsamości"
"current_time" : datetime.utcnow().isoformat()
}
record = json.dumps(record).encode("utf-8")
producer.produce(topic=ANOMALY_TOPIC, value=record)
producer.flush()
elif clients[record['ID']-1,1]==1:
prediciton1=second_check.predict(data)
prediction2=isolation_second.predict(data)
if prediction1[0] == 1 or prediciton2[0] == -1:
clients[record['ID']-1,1]=2
_id=str(record["ID"])
record = {
"id": _id,
"data": "Transakcja zablokowana-wymagana autoryzacja tożsamości"
"current_time" : datetime.utcnow().isoformat()
}
record = json.dumps(record).encode("utf-8")
producer.produce(topic=ANOMALY_TOPIC, value=record)
producer.flush()
else:
clients[record['ID']-1,1]=0
_id=str(record["ID"])
record = {
"id": _id,
"data": "Transakcja OK"
"current_time" : datetime.utcnow().isoformat()
}
record = json.dumps(record).encode("utf-8")
producer.produce(topic=ANOMALY_TOPIC, value=record)
producer.flush()
else:
prediciton1=first_check.predict(data)
prediction2=isolation_first.predict(data)
if prediction1[0] == 0 and prediciton2[0] == 1:
_id=str(record["ID"])
record = {
"id": _id,
"data": "Transakcja OK"
"current_time" : datetime.utcnow().isoformat()
}
record = json.dumps(record).encode("utf-8")
producer.produce(topic=ANOMALY_TOPIC, value=record)
producer.flush()
elif prediction1[0] == and prediciton2[0] == -1:
clients[record['ID']-1,1]=1
_id=str(record["ID"])
record = {
"id": _id,
"data": "Wysłane ostrzeżenie, wymuszenie dodatkowej autoryzacji"
"current_time" : datetime.utcnow().isoformat()
}
record = json.dumps(record).encode("utf-8")
producer.produce(topic=ANOMALY_TOPIC, value=record)
producer.flush()
else:
clients[record['ID']-1,1]=1
_id=str(record["ID"])
record = {
"id": _id,
"data": "Transakcja podejrzana"
"current_time" : datetime.utcnow().isoformat()
}
record = json.dumps(record).encode("utf-8")
producer.produce(topic=ANOMALY_TOPIC, value=record)
producer.flush()
consumer.close()
for _ in range(NUM_PARTITIONS):
p = Process(target=detekcja_anomalii)
p.start()
?
Write corrected WHOLE code with comments inside.
|
43ef0dac4d55471e2f2a4cd76541ed8b
|
{
"intermediate": 0.4190492331981659,
"beginner": 0.4983446002006531,
"expert": 0.08260616660118103
}
|
10,950
|
identify records of dataframe whose two columns are not equal
|
475deb2f4eec71a23c11f07e1eb9f7f0
|
{
"intermediate": 0.3721356689929962,
"beginner": 0.30695945024490356,
"expert": 0.32090482115745544
}
|
10,951
|
Hi, which version of chatGPT am using now ?
|
3a22796f2398b3b2cd6bacd6afae27c9
|
{
"intermediate": 0.4611817002296448,
"beginner": 0.2523064911365509,
"expert": 0.28651177883148193
}
|
10,952
|
<AAA>
<Q></Q>
<SSSS></SSSS>
<BB></BB>
<CCC></CCC>
<DDDDDDDD></DDDDDDDD>
<EEEE></EEEE>
</AAA>
//*[string-length(name()) > 3]
//*[string-length(name(.))>3]
|
46537073fe778f7e0b3727f80ddbafc6
|
{
"intermediate": 0.32351604104042053,
"beginner": 0.4337039589881897,
"expert": 0.2427799552679062
}
|
10,953
|
CREATE TABLE sg_businesstype (
businesstypeid int not null auto_increment,
businesstype varchar(80),
primary key (businesstypeid)
);
insert into sg_businesstype ( businesstype ) values
('Buying Agent'), ('Dealer / Reseller'), ('Distributor'), ('Manufacturer / OEM'), ('Not Known'), ('Retailer'), ('Service Provider');
CREATE TABLE sg_users (
sgid int not null auto_increment,
email varchar(80) not null,
name varchar(60) not null,
usertype int not null default 1,
company varchar(80) null,
tel varchar(25) null,
mobile varchar(25) null,
businesstypeid int null,
newsletter boolean default false,
status boolean default true,
rating int default 0,
registerdate timestamp not null default CURRENT_TIMESTAMP,
logo varchar(255) null,
primary key (sgid),
foreign key (businesstypeid) references sg_businesstype (businesstypeid)
);
I used above sql to create two tables. I have written some php script to connect the database with $db by PDO. An email will be passed by variable $email. Give me a rich ux/ui bootstrap form to maintain the table sg_users. the first step is retrieving the record by $email and fill the form. If any modification, update the table sg_user.
|
b6a90da59e13376643ed14fe6033ee73
|
{
"intermediate": 0.4791737496852875,
"beginner": 0.28491300344467163,
"expert": 0.2359132021665573
}
|
10,954
|
I will give you a large Python script. I need you to remove everything that is not related to getting extracted text by streamed audio. Basically I need to simplify this script only to be used for streaming audio using microphone and getting the extracted text.
import pyaudio
import argparse
import asyncio
import aiohttp
import json
import os
import sys
import wave
import websockets
from datetime import datetime
startTime = datetime.now()
all_mic_data = []
all_transcripts = []
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 48000 # 48000
CHUNK = 8000
audio_queue = asyncio.Queue()
# Mimic sending a real-time stream by sending this many seconds of audio at a time.
# Used for file "streaming" only.
REALTIME_RESOLUTION = 0.250
subtitle_line_counter = 0
def subtitle_time_formatter(seconds, separator):
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds - int(seconds)) * 1000)
return f"{hours:02}:{minutes:02}:{secs:02}{separator}{millis:03}"
def subtitle_formatter(response, format):
global subtitle_line_counter
subtitle_line_counter += 1
start = response["start"]
end = start + response["duration"]
transcript = (
response.get("channel", {}).get("alternatives", [{}])[0].get("transcript", "")
)
if format == "srt":
separator = ","
else:
separator = "."
subtitle_string = f"{subtitle_line_counter}\n"
subtitle_string += f"{subtitle_time_formatter(start, separator)} --> "
subtitle_string += f"{subtitle_time_formatter(end, separator)}\n"
if format == "vtt":
subtitle_string += "- "
subtitle_string += f"{transcript}\n\n"
return subtitle_string
# Used for microphone streaming only.
def mic_callback(input_data, frame_count, time_info, status_flag):
audio_queue.put_nowait(input_data)
return (input_data, pyaudio.paContinue)
async def run(key, method, format, **kwargs):
deepgram_url = f'{kwargs["host"]}/v1/listen?punctuate=true&tier=nova&language=en'
if method == "mic":
deepgram_url += f"&encoding=linear16&sample_rate=48000"
elif method == "wav":
data = kwargs["data"]
deepgram_url += f'&channels={kwargs["channels"]}&sample_rate={kwargs["sample_rate"]}&encoding=linear16'
# Connect to the real-time streaming endpoint, attaching our credentials.
async with websockets.connect(
deepgram_url, extra_headers={"Authorization": "Token {}".format(key)}
) as ws:
print(f'ℹ️ Request ID: {ws.response_headers.get("dg-request-id")}')
print("🟢 (1/5) Successfully opened Deepgram streaming connection")
async def sender(ws):
print(
f'🟢 (2/5) Ready to stream {method if (method == "mic" or method == "url") else kwargs["filepath"]} audio to Deepgram{". Speak into your microphone to transcribe." if method == "mic" else ""}'
)
if method == "mic":
try:
while True:
mic_data = await audio_queue.get()
all_mic_data.append(mic_data)
await ws.send(mic_data)
except websockets.exceptions.ConnectionClosedOK:
await ws.send(json.dumps({"type": "CloseStream"}))
print(
"🟢 (5/5) Successfully closed Deepgram connection, waiting for final transcripts if necessary"
)
except Exception as e:
print(f"Error while sending: {str(e)}")
raise
elif method == "url":
# Listen for the connection to open and send streaming audio from the URL to Deepgram
async with aiohttp.ClientSession() as session:
async with session.get(kwargs["url"]) as audio:
while True:
remote_url_data = await audio.content.readany()
await ws.send(remote_url_data)
# If no data is being sent from the live stream, then break out of the loop.
if not remote_url_data:
break
elif method == "wav":
nonlocal data
# How many bytes are contained in one second of audio?
byte_rate = (
kwargs["sample_width"] * kwargs["sample_rate"] * kwargs["channels"]
)
# How many bytes are in `REALTIME_RESOLUTION` seconds of audio?
chunk_size = int(byte_rate * REALTIME_RESOLUTION)
try:
while len(data):
chunk, data = data[:chunk_size], data[chunk_size:]
# Mimic real-time by waiting `REALTIME_RESOLUTION` seconds
# before the next packet.
await asyncio.sleep(REALTIME_RESOLUTION)
# Send the data
await ws.send(chunk)
await ws.send(json.dumps({"type": "CloseStream"}))
print(
"🟢 (5/5) Successfully closed Deepgram connection, waiting for final transcripts if necessary"
)
except Exception as e:
print(f"🔴 ERROR: Something happened while sending, {e}")
raise e
return
async def receiver(ws):
"""Print out the messages received from the server."""
first_message = True
first_transcript = True
transcript = ""
async for msg in ws:
res = json.loads(msg)
if first_message:
print(
"🟢 (3/5) Successfully receiving Deepgram messages, waiting for finalized transcription..."
)
first_message = False
try:
# handle local server messages
# print(res.get("msg"))
if res.get("msg"):
print(res["msg"])
if res.get("is_final"):
transcript = (
res.get("channel", {})
.get("alternatives", [{}])[0]
.get("transcript", "")
)
if transcript != "":
if first_transcript:
print("🟢 (4/5) Began receiving transcription")
# if using webvtt, print out header
if format == "vtt":
print("WEBVTT\n")
first_transcript = False
if format == "vtt" or format == "srt":
transcript = subtitle_formatter(res, format)
print(transcript)
all_transcripts.append(transcript)
# if using the microphone, close stream if user says "goodbye"
if method == "mic" and "goodbye" in transcript.lower():
await ws.send(json.dumps({"type": "CloseStream"}))
print(
"🟢 (5/5) Successfully closed Deepgram connection, waiting for final transcripts if necessary"
)
# handle end of stream
if res.get("created"):
# save subtitle data if specified
if format == "vtt" or format == "srt":
data_dir = os.path.abspath(
os.path.join(os.path.curdir, "data")
)
if not os.path.exists(data_dir):
os.makedirs(data_dir)
transcript_file_path = os.path.abspath(
os.path.join(
data_dir,
f"{startTime.strftime('%Y%m%d%H%M')}.{format}",
)
)
with open(transcript_file_path, "w") as f:
f.write("".join(all_transcripts))
print(f"🟢 Subtitles saved to {transcript_file_path}")
# also save mic data if we were live streaming audio
# otherwise the wav file will already be saved to disk
if method == "mic":
wave_file_path = os.path.abspath(
os.path.join(
data_dir,
f"{startTime.strftime('%Y%m%d%H%M')}.wav",
)
)
wave_file = wave.open(wave_file_path, "wb")
wave_file.setnchannels(CHANNELS)
wave_file.setsampwidth(SAMPLE_SIZE)
wave_file.setframerate(RATE)
wave_file.writeframes(b"".join(all_mic_data))
wave_file.close()
print(f"🟢 Mic audio saved to {wave_file_path}")
print(
f'🟢 Request finished with a duration of {res["duration"]} seconds. Exiting!'
)
except KeyError:
print(f"🔴 ERROR: Received unexpected API response! {msg}")
# Set up microphone if streaming from mic
async def microphone():
audio = pyaudio.PyAudio()
stream = audio.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
input_device_index=5, # Custom mic
stream_callback=mic_callback,
)
stream.start_stream()
global SAMPLE_SIZE
SAMPLE_SIZE = audio.get_sample_size(FORMAT)
while stream.is_active():
await asyncio.sleep(0.1)
stream.stop_stream()
stream.close()
functions = [
asyncio.ensure_future(sender(ws)),
asyncio.ensure_future(receiver(ws)),
]
if method == "mic":
functions.append(asyncio.ensure_future(microphone()))
await asyncio.gather(*functions)
def validate_input(input):
if input.lower().startswith("mic"):
return input
elif input.lower().endswith("wav"):
if os.path.exists(input):
return input
elif input.lower().startswith("http"):
return input
raise argparse.ArgumentTypeError(
f'{input} is an invalid input. Please enter the path to a WAV file, a valid stream URL, or "mic" to stream from your microphone.'
)
def validate_format(format):
if (
format.lower() == ("text")
or format.lower() == ("vtt")
or format.lower() == ("srt")
):
return format
raise argparse.ArgumentTypeError(
f'{format} is invalid. Please enter "text", "vtt", or "srt".'
)
def validate_dg_host(dg_host):
if (
# Check that the host is a websocket URL
dg_host.startswith("wss://")
or dg_host.startswith("ws://")
):
# Trim trailing slash if necessary
if dg_host[-1] == '/':
return dg_host[:-1]
return dg_host
raise argparse.ArgumentTypeError(
f'{dg_host} is invalid. Please provide a WebSocket URL in the format "{{wss|ws}}://hostname[:port]".'
)
def parse_args():
"""Parses the command-line arguments."""
parser = argparse.ArgumentParser(
description="Submits data to the real-time streaming endpoint."
)
parser.add_argument(
"-k", "--key", required=True, help="YOUR_DEEPGRAM_API_KEY (authorization)"
)
parser.add_argument(
"-i",
"--input",
help='Input to stream to Deepgram. Can be "mic" to stream from your microphone (requires pyaudio), the path to a WAV file, or the URL to a direct audio stream. Defaults to the included file preamble.wav',
nargs="?",
const=1,
default="preamble.wav",
type=validate_input,
)
parser.add_argument(
"-f",
"--format",
help='Format for output. Can be "text" to return plain text, "VTT", or "SRT". If set to VTT or SRT, the audio file and subtitle file will be saved to the data/ directory. Defaults to "text".',
nargs="?",
const=1,
default="text",
type=validate_format,
)
#Parse the host
parser.add_argument(
"--host",
help='Point the test suite at a specific Deepgram URL (useful for on-prem deployments). Takes "{{wss|ws}}://hostname[:port]" as its value. Defaults to "wss://api.deepgram.com".',
nargs="?",
const=1,
default="wss://api.deepgram.com",
type=validate_dg_host,
)
return parser.parse_args()
def main():
"""Entrypoint for the example."""
# Parse the command-line arguments.
args = parse_args()
input = args.input
format = args.format.lower()
host = args.host
try:
if input.lower().startswith("mic"):
asyncio.run(run(args.key, "mic", format, host=host))
elif input.lower().endswith("wav"):
if os.path.exists(input):
# Open the audio file.
with wave.open(input, "rb") as fh:
(
channels,
sample_width,
sample_rate,
num_samples,
_,
_,
) = fh.getparams()
assert sample_width == 2, "WAV data must be 16-bit."
data = fh.readframes(num_samples)
asyncio.run(
run(
args.key,
"wav",
format,
data=data,
channels=channels,
sample_width=sample_width,
sample_rate=sample_rate,
filepath=args.input,
host=host,
)
)
else:
raise argparse.ArgumentTypeError(
f"🔴 {args.input} is not a valid WAV file."
)
elif input.lower().startswith("http"):
asyncio.run(run(args.key, "url", format, url=input, host=host))
else:
raise argparse.ArgumentTypeError(
f'🔴 {input} is an invalid input. Please enter the path to a WAV file, a valid stream URL, or "mic" to stream from your microphone.'
)
except websockets.exceptions.InvalidStatusCode as e:
print(f'🔴 ERROR: Could not connect to Deepgram! {e.headers.get("dg-error")}')
print(
f'🔴 Please contact Deepgram Support (<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>) with request ID {e.headers.get("dg-request-id")}'
)
return
except websockets.exceptions.ConnectionClosedError as e:
error_description = f"Unknown websocket error."
print(
f"🔴 ERROR: Deepgram connection unexpectedly closed with code {e.code} and payload {e.reason}"
)
if e.reason == "DATA-0000":
error_description = "The payload cannot be decoded as audio. It is either not audio data or is a codec unsupported by Deepgram."
elif e.reason == "NET-0000":
error_description = "The service has not transmitted a Text frame to the client within the timeout window. This may indicate an issue internally in Deepgram's systems or could be due to Deepgram not receiving enough audio data to transcribe a frame."
elif e.reason == "NET-0001":
error_description = "The service has not received a Binary frame from the client within the timeout window. This may indicate an internal issue in Deepgram's systems, the client's systems, or the network connecting them."
print(f"🔴 {error_description}")
# TODO: update with link to streaming troubleshooting page once available
# print(f'🔴 Refer to our troubleshooting suggestions: ')
print(
f"🔴 Please contact Deepgram Support (<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>) with the request ID listed above."
)
return
except websockets.exceptions.ConnectionClosedOK:
return
except Exception as e:
print(f"🔴 ERROR: Something went wrong! {e}")
return
if __name__ == "__main__":
sys.exit(main() or 0)
|
0e3fffc6294c6d4eadda8bd19b0ee21b
|
{
"intermediate": 0.32436761260032654,
"beginner": 0.4993061125278473,
"expert": 0.17632627487182617
}
|
10,955
|
A borderRadius can only be given on borders with uniform colors and styles.
|
9e386b1e2f47ce8d15dfc9742ced5482
|
{
"intermediate": 0.41167524456977844,
"beginner": 0.273154616355896,
"expert": 0.3151701092720032
}
|
10,956
|
If i used migrations before in asp.net core mvc and want to add another table, what should i write in package console?
|
0947079edb362f107c9b774d6be34d73
|
{
"intermediate": 0.6424986124038696,
"beginner": 0.17349733412265778,
"expert": 0.1840040385723114
}
|
10,957
|
[Thu Jun 08 19:03:10.250517 2023] [:error] [pid 24802:tid 140352006645504] PHP Fatal error: Uncaught exception 'Exception' with message 'couldn't connect to host' in /opt/p
service/scc/apache2/conf/_classes/scc_http_s_request.phl:326\nStack trace:\n#0 /opt/pservice/scc/apache2/conf/_classes/scc_http_s_request.phl(361): raise_curl_error(Resource
id #13)\n#1 /opt/pservice/scc/apache2/conf/_classes/scc_login.phl(98): http_curl_request('127.0.0.1:58010...', false)\n#2 /opt/pservice/scc/apache2/conf/_classes/scc_login.
phl(386): AUTHLOGICROUTER->do_curl_request('/SCCLOGIN/LOGIN...', Array)\n#3 /opt/pservice/scc/apache2/conf/_classes/scc_login.phl(738): AUTHLOGICROUTER->go_to_login_form(NUL
L, NULL, 'LOGIN')\n#4 /opt/pservice/scc/apache2/conf/_classes/scc_login.phl(730): AUTHLOGICROUTER->do_login(NULL)\n#5 /opt/pservice/scc/apache2/conf/_classes/scc_login.phl(7
69): AUTHLOGICROUTER->try_to_autologin()\n#6 /opt/pservice/scc/apache2/conf/_classes/scc_login.phl(788): AUTHLOGICROUTER->do_default()\n#7 /opt/pservice/scc/apache2/htdocs/p
s/scc/login.php(88): AUTHLOGICROUTER->route(NULL)\n#8 {main}\n thrown in /opt/pservice/scc/apache2/conf/_classes/scc_http_s_request.phl on line 326
what&
|
41835cd51e18a75b19e725f60c398c6e
|
{
"intermediate": 0.28829991817474365,
"beginner": 0.4324652850627899,
"expert": 0.2792348265647888
}
|
10,958
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 5000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
usdt_balance = next((item for item in account_info['assets'] if item["asset"] == "USDT"), {"balance": 0})
max_trade_size = float(usdt_balance.get("balance", 0)) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 44640)
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', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place stop market order
if order_type == 'STOP_MARKET':
try:
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='BUY' if signal == 'buy' else 'SELL',
type='STOP_MARKET',
quantity=quantity,
stopPrice=stop_loss_price,
reduceOnly=True
)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
# Place market or take profit order
elif order_type == 'market':
try:
response = binance_futures.create_order(
symbol=symbol,
type=order_type,
side='BUY' if signal == 'buy' else 'SELL',
amount=quantity,
price=price
)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: The signal time is: 2023-06-08 12:43:01 :sell
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 285, 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 248, in order_execution
response = binance_futures.fapiPrivatePostOrder(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Entry.__init__.<locals>.unbound_method() got an unexpected keyword argument 'symbol'
|
cafb2ecefa9d633d51f4011ec10a7935
|
{
"intermediate": 0.38698631525039673,
"beginner": 0.42868635058403015,
"expert": 0.1843273788690567
}
|
10,959
|
Write a README.md for the code below:
|
6921dda0c76e1d77fe9e246a9ac535e1
|
{
"intermediate": 0.312786728143692,
"beginner": 0.26490840315818787,
"expert": 0.4223048686981201
}
|
10,960
|
how can I make it so that when I click on the button calculate it shows the bmi and status: public partial class FBMI : Form
{
public FBMI()
{
InitializeComponent();
btnClose.Click += btnClose_Click;
btnCalculate.Click += btnCalculate_Click;
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void richTextBox2_TextChanged(object sender, EventArgs e)
{
if (btnCalculate.DialogResult == DialogResult.OK)
{
double height = Convert.ToDouble(txtHeight.Text);
height = height + 0.0254;
double mass = Convert.ToDouble(txtWeight.Text);
mass = mass / 2.205;
double bmi = mass / (height * height);
rtBmi.Text = bmi.ToString();
}
}
private void rtStatus_TextChanged_1(object sender, EventArgs e)
{
double bmi = Convert.ToDouble(rtBmi.Text);
if (bmi < 18.5)
{
rtStatus.Text = "You are underweight";
}
else if (bmi >= 18.5 && bmi <= 24.9)
{
rtStatus.Text = "You are normal weight";
}
else if (bmi >= 25.0 && bmi <= 29.9)
{
rtStatus.Text = "You are overweight";
}
else
{
rtStatus.Text = "You are obese";
}
}
private void txtWeight_TextChanged(object sender, EventArgs e)
{
int userInput;
if (!int.TryParse(txtWeight.Text, out userInput))
{
MessageBox.Show("The mass and height must be numbers.");
}
}
private void txtHeight_TextChanged(object sender, EventArgs e)
{
int userInput;
if (!int.TryParse(txtHeight.Text, out userInput))
{
MessageBox.Show("The mass and height must be numbers.");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
|
71b0d65ac933c6d3428f99a830893f09
|
{
"intermediate": 0.34603220224380493,
"beginner": 0.4380820393562317,
"expert": 0.215885728597641
}
|
10,961
|
How can I write a VBA code for the following; Print Columns A to K that are not hidden from Row 1 to last Row of column A that has a value
|
aec4cb31582dbba31257ac4a8f97f201
|
{
"intermediate": 0.361187607049942,
"beginner": 0.23834076523780823,
"expert": 0.40047159790992737
}
|
10,962
|
how can I make it so that the error is shown only when the user types the whole word in the text box not after every charachter: private void txtWeight_TextChanged(object sender, EventArgs e)
{
try
{
int weight = int.Parse(txtWeight.Text);
}catch (Exception ex)
{
MessageBox.Show("The mass and height must be numbers.");
}
}
private void txtHeight_TextChanged(object sender, EventArgs e)
{
try
{
int height = int.Parse(txtHeight.Text);
} catch (Exception ex)
{
MessageBox.Show("The mass and height must be numbers.");
}
}
|
91b367360b5c6c290a8a2cbbe0a43f60
|
{
"intermediate": 0.5151912569999695,
"beginner": 0.29653435945510864,
"expert": 0.18827445805072784
}
|
10,963
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 5000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
usdt_balance = next((item for item in account_info['assets'] if item["asset"] == "USDT"), {"balance": 0})
max_trade_size = float(usdt_balance.get("balance", 0)) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 44640)
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', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place stop market order
if order_type == 'STOP_MARKET':
try:
response = binance_futures.fapiPrivatePostOrder(
side='BUY' if signal == 'buy' else 'SELL',
type='STOP_MARKET',
quantity=quantity,
stopPrice=stop_loss_price,
reduceOnly=True
)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
# Place market or take profit order
elif order_type == 'market':
try:
response = binance_futures.create_order(
symbol=symbol,
type=order_type,
side='BUY' if signal == 'buy' else 'SELL',
amount=quantity,
price=price
)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR in order excution, I want to place an binance futures order , but it doesn't work . ERROR: The signal time is: 2023-06-08 19:21:59 :
The signal time is: 2023-06-08 19:22:01 :
The signal time is: 2023-06-08 19:22:02 :buy
The signal time is: 2023-06-08 19:22:06 :buy
The signal time is: 2023-06-08 19:22:09 :buy
The signal time is: 2023-06-08 19:22:12 :buy
The signal time is: 2023-06-08 19:22:15 :buy
The signal time is: 2023-06-08 19:22:18 :buy
The signal time is: 2023-06-08 19:22:21 :buy
The signal time is: 2023-06-08 19:22:24 :buy
The signal time is: 2023-06-08 19:22:26 :buy
The signal time is: 2023-06-08 19:22:29 :buy
The signal time is: 2023-06-08 19:22:32 :buy
The signal time is: 2023-06-08 19:22:35 :buy
The signal time is: 2023-06-08 19:22:38 :buy
The signal time is: 2023-06-08 19:22:41 :buy
The signal time is: 2023-06-08 19:22:44 :buy
The signal time is: 2023-06-08 19:22:47 :buy
The signal time is: 2023-06-08 19:22:50 :buy
The signal time is: 2023-06-08 19:22:53 :buy
The signal time is: 2023-06-08 19:22:56 :buy
The signal time is: 2023-06-08 19:22:59 :buy
The signal time is: 2023-06-08 19:23:02 :sell
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 284, 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 248, in order_execution
response = binance_futures.fapiPrivatePostOrder(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Entry.__init__.<locals>.unbound_method() got an unexpected keyword argument 'side'
|
83bdc46c376a84a62c279d4d1d68561e
|
{
"intermediate": 0.38698631525039673,
"beginner": 0.42868635058403015,
"expert": 0.1843273788690567
}
|
10,964
|
Write a code for java on spring boot for collecting metric fro, server
|
d93241edc8f005969424b01cd56a79f2
|
{
"intermediate": 0.6676130294799805,
"beginner": 0.14985691010951996,
"expert": 0.18253009021282196
}
|
10,965
|
# Оптимизированный!!! Возвращает адреса созданных токенов в указанном диапазоне блоков (Обрабатывет множество блоков)
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')
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
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:
print(f'New contract creation: Contract Address: {contract_address}')
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 = 28866529 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
Complete the code above so that in addition to the address of the token contract, the address of the creator of the token contract is also displayed
|
620ad7ebf05c0640084baa7170f96223
|
{
"intermediate": 0.39617377519607544,
"beginner": 0.4186747372150421,
"expert": 0.18515151739120483
}
|
10,966
|
Certainly! I can help you code a Tic-Tac-Toe game in Visual Basic Script.
|
9d6bf5d83c5edb69883c0256f8ac2d99
|
{
"intermediate": 0.39425602555274963,
"beginner": 0.2987678647041321,
"expert": 0.3069761097431183
}
|
10,967
|
Golang backend code http methods
|
73374658680a6dec1f130a391b4ee3a6
|
{
"intermediate": 0.23712219297885895,
"beginner": 0.18638186156749725,
"expert": 0.5764959454536438
}
|
10,968
|
Write a tic-tac-toe game using HTML
|
5c34b514ca840223be8fbec5d72365b3
|
{
"intermediate": 0.362384557723999,
"beginner": 0.40080416202545166,
"expert": 0.2368113249540329
}
|
10,969
|
Write a tic-tac-toe game using HTML
|
4107a53607f1ce3356830b774cb10066
|
{
"intermediate": 0.362384557723999,
"beginner": 0.40080416202545166,
"expert": 0.2368113249540329
}
|
10,970
|
create a html code for a afk leaderboard where you try to be afk all the time going up the seconds leaderboard.
|
bf4af63df04b309a22df5f96f63a8ae5
|
{
"intermediate": 0.3410874903202057,
"beginner": 0.26096251606941223,
"expert": 0.3979499936103821
}
|
10,971
|
Email body to update the joining date earlier and requesting for bonus
|
38c4ce137627851ed680d4fb7e4ec035
|
{
"intermediate": 0.3524342179298401,
"beginner": 0.24698445200920105,
"expert": 0.40058138966560364
}
|
10,972
|
How to sort an arraylist so they one is always infront of the other
|
ec90e1162c6a39a4d79fadecca7ff40d
|
{
"intermediate": 0.20007537305355072,
"beginner": 0.12131612747907639,
"expert": 0.6786084771156311
}
|
10,973
|
Write a tic tac toe game using c#
|
b69eb5228c0361d4d388671cc622b4c2
|
{
"intermediate": 0.3314952552318573,
"beginner": 0.46606817841529846,
"expert": 0.20243655145168304
}
|
10,974
|
Write a tic tac toe game code using c#
|
1f95a583af150aae14e11d82b7b74b3d
|
{
"intermediate": 0.3116629421710968,
"beginner": 0.4622957706451416,
"expert": 0.2260412722826004
}
|
10,975
|
write a program that finds an approximate of the root in [-1,0], with an absolute error less than 10^-4, checking the error after each iteration with the following equation: cos(2x) – ln(x2+1)=0
|
bd5421ac8d546d7a06c3e9b355c30073
|
{
"intermediate": 0.22322441637516022,
"beginner": 0.08084458857774734,
"expert": 0.6959309577941895
}
|
10,976
|
write me a code in a c program, using this information, "Background
The use of computers in the finance industry has been marked with controversy lately as
programmed trading -- designed to take advantage of extremely small fluctuations in
Page 5 of 70
prices -- has been outlawed at many Wall Street firms. The ethics of computer
programming is a fledgling field with many thorny issues.
The Problem
Arbitrage is the trading of one currency for another with the hopes of taking advantage of
small differences in conversion rates among several currencies in order to achieve a
profit. For example, if $1.00 in U.S. currency buys 0.7 British pounds currency, £1 in
British currency buys 9.5 French francs, and 1 French franc buys 0.16 in U.S. dollars,
then an arbitrage trader can start with $1.00 and earn 1*0.7*9.5*0.16=1.064 dollars thus
earning a profit of 6.4 percent.
You will write a program that determines whether a sequence of currency exchanges can
yield a profit as described above.
To result in successful arbitrage, a sequence of exchanges must begin and end with the
same currency, but any starting currency may be considered.
The Input
The input file consists of one or more conversion tables. You must solve the arbitrage
problem for each of the tables in the input file.
Each table is preceded by an integer n on a line by itself giving the dimensions of the
table. The maximum dimension is 20; the minimum dimension is 2.
The table then follows in row major order but with the diagonal elements of the table
missing (these are assumed to have value 1.0). Thus the first row of the table represents
the conversion rates between country 1 and n-1 other countries, i.e., the amount of
currency of country i (2≤i≤n) that can be purchased with one unit of the currency of
country 1.
Thus each table consists of n+1 lines in the input file: 1 line containing n and n lines
representing the conversion table.
The Output
For each table in the input file you must determine whether a sequence of exchanges
exists that results in a profit of more than 1 percent (0.01). If a sequence exists you must
print the sequence of exchanges that results in a profit. If there is more than one sequence
that results in a profit of more than 1 percent you must print a sequence of minimal
length, i.e., one of the sequences that uses the fewest exchanges of currencies to yield a
profit.
Because the IRS (United States Internal Revenue Service) notices lengthy transaction
sequences, all profiting sequences must consist of n or fewer transactions where n is the
dimension of the table giving conversion rates. The sequence 1 2 1 represents two
conversions.
If a profiting sequence exists you must print the sequence of exchanges that results in a
profit. The sequence is printed as a sequence of integers with the integer i representing
the ith line of the conversion table (country i). The first integer in the sequence is the
country from which the profiting sequence starts. This integer also ends the sequence.
If no profiting sequence of n or fewer transactions exists, then the line
no arbitrage sequence exists
should be printed.
Sample Input
3
1.2 .89
Page 6 of 70
.88 5.1
1.1 0.15
4
3.1 0.0023 0.35
0.21 0.00353 8.13
200 180.559 10.339
2.11 0.089 0.06111
2
2.0
0.45
Sample Output
1 2 1
1 2 4 1
no arbitrage sequence exists"
|
7a748bb4878c0b59852a16ea4e9ee328
|
{
"intermediate": 0.33095329999923706,
"beginner": 0.5527623295783997,
"expert": 0.11628440767526627
}
|
10,977
|
fix this error: “Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidCastException: Unable to cast object of type ‘ListPartition1[elctronicads.Models.Ads]' to type 'System.Collections.Generic.List1[elctronicads.Models.Ads]’.
at elctronicads.Controllers.HomeController.Service(Nullable`1 id) in C:\Users\kingk\Desktop\elctronicads\elctronicads\Controllers\HomeController.cs:line 49” coming from this code " public IActionResult Service(int? id)
{
var articles = _context.Ad.ToList();
if (!id.HasValue)
return NotFound();
var mainArticle = _context.Ad.FirstOrDefault(x => x.id == id.Value);
if (mainArticle == null)
return NotFound();
string[] keyk = mainArticle.Keywords.Split(“,”);
var key = _context.Ad.Where(x => Convert.ToInt32(x.OwnerName) == id).ToList().Take(5);
var viewModel = new ServiceViewModel
{
MainArticle = mainArticle,
ClosestArticles = (List<Ads>)key,
owner = _context.Clients.Where(x => x.Id == Convert.ToInt32(mainArticle.OwnerName)).FirstOrDefault()
};
return View(viewModel);
}"
|
a2b2774174f9b537eb5725d39c69a600
|
{
"intermediate": 0.47839614748954773,
"beginner": 0.2887874245643616,
"expert": 0.2328164279460907
}
|
10,978
|
cos(2x) – ln(x2+1)=0
write a program that finds an approximate of the root in [-1,0], with an absolute error less than 10^-4, checking the error after each iteration
|
9fac79231f58b417d7a7f30247a315ba
|
{
"intermediate": 0.23411348462104797,
"beginner": 0.09959437698125839,
"expert": 0.6662921905517578
}
|
10,979
|
please provide batch or powershell code that launches several JAR files (via java.exe for windows) in parallel and wait till every jar finishes
|
2f56b6f5a2abe7db30551401e95c61f0
|
{
"intermediate": 0.6112651824951172,
"beginner": 0.1380441039800644,
"expert": 0.25069066882133484
}
|
10,980
|
$navBarHeight: 50px;
@mixin calcHeight($arg) {
height: (100vh-$arg);
}
correct mixing in scss
|
7688821495e959edd8f27a9275b97ae4
|
{
"intermediate": 0.4051457941532135,
"beginner": 0.27344486117362976,
"expert": 0.32140931487083435
}
|
10,981
|
Are you capable of helping to walk me through updating my yt-dlp program?
|
794315f66285d5eba318de33f8e8c132
|
{
"intermediate": 0.4131310284137726,
"beginner": 0.110634945333004,
"expert": 0.47623395919799805
}
|
10,982
|
Hi can you help me with storybook?
|
2cbc98bcdf8166eedd0a6b3a0be185f5
|
{
"intermediate": 0.3342359960079193,
"beginner": 0.3931674063205719,
"expert": 0.2725965976715088
}
|
10,983
|
Write me a program in C, with this info, "Problems that process input and generate a simple ``yes'' or ``no'' answer are called
decision problems. One class of decision problems, the NP-complete problems, are not
amenable to general efficient solutions. Other problems may be simple as decision
problems, but enumerating all possible ``yes'' answers may be very difficult (or at least
time-consuming).
This problem involves determining the number of routes available to an emergency
vehicle operating in a city of one-way streets.
The Problem
Given the intersections connected by one-way streets in a city, you are to write a program
that determines the number of different routes between each intersection. A route is a
sequence of one-way streets connecting two intersections.
Intersections are identified by non-negative integers. A one-way street is specified by a
pair of intersections. For example, j k indicates that there is a one-way street from
intersection j to intersection k. Note that two-way streets can be modelled by specifying
two one-way streets: j k and k j.
Consider a city of four intersections connected by the following one-way streets:
0 1
0 2
1 2
2 3
There is one route from intersection 0 to 1, two routes from 0 to 2 (the routes are 0 > 1 > 2
and 0 > 2), two routes from 0 to 3, one route from 1 to 2, one route from 1
to 3, one route from 2 to 3, and no other routes.
It is possible for an infinite number of different routes to exist. For example if the
intersections above are augmented by the street 3 2, there is still only one route from 0 to
1, but there are infinitely many different routes from 0 to 2. This is because the street
from 2 to 3 and back to 2 can be repeated yielding a different sequence of streets and
hence a different route. Thus the route 0 > 2 > 3 > 2 > 3 > 2 is a different route
than 0 > 2 > 3 > 2.
The Input
The input is a sequence of city specifications. Each specification begins with the number
of one-way streets in the city followed by that many one-way streets given as pairs of
intersections. Each pair j k represents a one-way street from intersection j to intersection
k. In all cities, intersections are numbered sequentially from 0 to the ``largest''
intersection. All integers in the input are separated by whitespace. The input is terminated
by end-of-file.
There will never be a one-way street from an intersection to itself. No city will have more
than 30 intersections.
The Output
For each city specification, a square matrix of the number of different routes from
intersection j to intersection k is printed. If the matrix is denoted M, then M[j][k] is the
number of different routes from intersection j to intersection k. The matrix M should be
printed in row-major order, one row per line. Each matrix should be preceded by the
string ``matrix for city k'' (with k appropriately instantiated, beginning with 0).
If there are an infinite number of different paths between two intersections a -1 should be
printed. DO NOT worry about justifying and aligning the output of each matrix. All
entries in a row should be separated by whitespace.
Sample Input
7 0 1 0 2 0 4 2 4 2 3 3 1 4 3
5
0 2
0 1 1 5 2 5 2 1
9
0 1 0 2 0 3
0 4 1 4 2 1
2 0
3 0
3 1
Sample Output
matrix for city 0
0 4 1 3 2
0 0 0 0 0
0 2 0 2 1
0 1 0 0 0
0 1 0 1 0
matrix for city 1
0 2 1 0 0 3
0 0 0 0 0 1
0 1 0 0 0 2
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
matrix for city 2
-1 -1 -1 -1 -1
0 0 0 0 1
-1 -1 -1 -1 -1
-1 -1 -1 -1 -1
0 0 0 0 0"
|
dd026350d0a358002d3f8ee3dbfe8304
|
{
"intermediate": 0.33482202887535095,
"beginner": 0.3596157133579254,
"expert": 0.30556225776672363
}
|
10,984
|
Act as a VBA programmer. Write me VBA code which works on Mac to create PowerPoint slides about the topic being a pilot: For this activity, you will be creating a slide show presentation that explores the pilot career in depth. One slide introducing your career and giving a brief overview of the career/career field One slide explaining what is required (education, training) in order to work in your chosen career One slide describing personal interests or abilities that may be helpful in this career One slide outlining the
|
536508fc46c208549b0cd38c92f86494
|
{
"intermediate": 0.22992253303527832,
"beginner": 0.6140002012252808,
"expert": 0.15607722103595734
}
|
10,985
|
You froze on my end. Do you recall our last conversation from my IP?
|
d2a0079849f076301c3582092c1f6c8c
|
{
"intermediate": 0.3287864625453949,
"beginner": 0.40488436818122864,
"expert": 0.26632916927337646
}
|
10,986
|
Реши ошибку в Google colab
error Traceback (most recent call last)
<ipython-input-8-8bef02c87633> in <cell line: 1>()
4
5 # b. Детектируем лицо на изображении
----> 6 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
7 faces = detector(gray)
8
error: OpenCV(4.7.0) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'
|
d43161657a550abefa84a7b160aca718
|
{
"intermediate": 0.38980719447135925,
"beginner": 0.3359341025352478,
"expert": 0.27425870299339294
}
|
10,987
|
Write a typical simple data validation process example that reduced data errors by sql
|
d61f774c0227550eacf9428bb35dccd2
|
{
"intermediate": 0.5161415338516235,
"beginner": 0.20339395105838776,
"expert": 0.2804645001888275
}
|
10,988
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 5000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
usdt_balance = next((item for item in account_info['assets'] if item["asset"] == "USDT"), {"balance": 0})
max_trade_size = float(usdt_balance.get("balance", 0)) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 44640)
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', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place stop market order
if order_type == 'STOP_MARKET':
try:
data = json.dumps({"symbol": symbol})
response = binance_futures.fapiPrivatePostOrder(
data=data,
sideEffectType='MARGIN_BUY',
type='MARKET' if signal == 'buy' else 'STOP_MARKET',
quantity=quantity,
positionSide=POSITION_SIDE_LONG if signal == 'buy' else POSITION_SIDE_SHORT,
reduceOnly=True,
newOrderRespType='FULL',
stopPrice=stop_loss_price,
price=price,
workingType='MARK_PRICE',
priceProtect=False,
timeInForce='GTC',
newClientOrderId=''
)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
# Place market or take profit order
elif order_type == 'market':
try:
response = binance_futures.create_order(
symbol=symbol,
type=order_type,
side='BUY' if signal == 'buy' else 'SELL',
amount=quantity,
price=price
)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, signal:{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: The signal time is: 2023-06-08 21:34:58, signal:buy
The signal time is: 2023-06-08 21:35:01, signal:sell
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 293, 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 'data'
|
96dc750a653afb1dd55e41ffc786bcf5
|
{
"intermediate": 0.38698631525039673,
"beginner": 0.42868635058403015,
"expert": 0.1843273788690567
}
|
10,989
|
Реши ошибку в Google Colab:
ValueError Traceback (most recent call last)
<ipython-input-12-35d3ed07c3b4> in <cell line: 3>()
1 # 2. Индексируем векторы признаков
2 face_descriptors = np.array(face_descriptors)
----> 3 kdtree = KDTree(face_descriptors)
sklearn/neighbors/_binary_tree.pxi in sklearn.neighbors._kd_tree.BinaryTree.init()
/usr/local/lib/python3.10/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name)
900 # If input is 1D raise error
901 if array.ndim == 1:
–> 902 raise ValueError(
903 “Expected 2D array, got 1D array instead:\narray={}.\n”
904 "Reshape your data either using array.reshape(-1, 1) if "
ValueError: Expected 2D array, got 1D array instead:
array=[].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
|
8a1d6fa162ea830e042f75404b5e6616
|
{
"intermediate": 0.5009061694145203,
"beginner": 0.24802063405513763,
"expert": 0.2510731816291809
}
|
10,990
|
write two coding programmes (any language code is OK – please make sure you cite your sources)
|
1b15fca013001d8f2594c823d504b57c
|
{
"intermediate": 0.34775397181510925,
"beginner": 0.26330623030662537,
"expert": 0.3889397382736206
}
|
10,991
|
Посмотрите внимательно на список с записями и обратите внимание, что мы запрашивали 100 альбомов, то есть на одну запись меньше, чем нам показал счётчик. Ответьте, в чём причина: ваш ответ на python
|
1c81129421c27ea51a0c1a72158051dd
|
{
"intermediate": 0.3506610691547394,
"beginner": 0.27611207962036133,
"expert": 0.3732268214225769
}
|
10,992
|
Есть код:
or image_path in image_paths:
# a. Считываем изображение из файла
image = cv2.imread(image_path)
# b. Детектируем лицо на изображении
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
# c. Вырезаем лицо из изображения (будет выбрано первое найденное лицо)
if len(faces) == 1:
face = faces[0]
landmarks = sp(gray, face)
aligned_face = dlib.get_face_chip(image, landmarks)
# d. Вычисляем вектор признаков из изображения лица
face_descriptor = np.array(face_descriptor_extractor.compute_face_descriptor(aligned_face))
if face_descriptor.shape[0] == 128: # Проверяем размерность вектора признаков
face_descriptors.append(face_descriptor)
# 2. Индексируем векторы признаков
face_descriptors = np.array(face_descriptors)
face_descriptors = face_descriptors.reshape(-1, 128)
kdtree = KDTree(face_descriptors)
# 3. Загружаем свое изображение
your_image_path = “/content/gdrive/MyDrive/photo_2022-08-22_20-53-55.jpg”
your_image = cv2.imread(your_image_path)
gray = cv2.cvtColor(your_image, cv2.COLOR_BGR2GRAY)
your_faces = detector(gray)
Исправь эту часть:
if len(your_faces) == 1:
your_face = your_faces[0]
landmarks = sp(gray, your_face)
aligned_face = dlib.get_face_chip(your_image, landmarks)
# d. Вычисляем вектор признаков вашего лица
your_face_descriptor = np.array(face_descriptor_extractor.compute_face_descriptor(aligned_face))
# 4. Находим 3 наиболее похожих фотографии
_, indices = kdtree.query([your_face_descriptor], k=4)
# 5. Выводим найденные 3 наиболее похожих фотографии
for i, idx in enumerate(indices[0][1:]):
similar_image = cv2.imread(image_paths[idx])
cv2.imshow(f"Similar Face {i+1}", similar_image)
|
6cf79bf386ca72655d5e668c9f2a04a6
|
{
"intermediate": 0.28010836243629456,
"beginner": 0.49400612711906433,
"expert": 0.2258855402469635
}
|
10,993
|
Есть код:
or image_path in image_paths:
# a. Считываем изображение из файла
image = cv2.imread(image_path)
# b. Детектируем лицо на изображении
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
# c. Вырезаем лицо из изображения (будет выбрано первое найденное лицо)
if len(faces) == 1:
face = faces[0]
landmarks = sp(gray, face)
aligned_face = dlib.get_face_chip(image, landmarks)
# d. Вычисляем вектор признаков из изображения лица
face_descriptor = np.array(face_descriptor_extractor.compute_face_descriptor(aligned_face))
if face_descriptor.shape[0] == 128: # Проверяем размерность вектора признаков
face_descriptors.append(face_descriptor)
# 2. Индексируем векторы признаков
face_descriptors = np.array(face_descriptors)
face_descriptors = face_descriptors.reshape(-1, 128)
kdtree = KDTree(face_descriptors)
# 3. Загружаем свое изображение
your_image_path = “/content/gdrive/MyDrive/photo_2022-08-22_20-53-55.jpg”
your_image = cv2.imread(your_image_path)
gray = cv2.cvtColor(your_image, cv2.COLOR_BGR2GRAY)
your_faces = detector(gray)
Исправь ошибки в этой части, чтобы код работал:
if len(your_faces) == 1:
your_face = your_faces[0]
landmarks = sp(gray, your_face)
aligned_face = dlib.get_face_chip(your_image, landmarks)
# d. Вычисляем вектор признаков вашего лица
your_face_descriptor = np.array(face_descriptor_extractor.compute_face_descriptor(aligned_face))
# 4. Находим 3 наиболее похожих фотографии
_, indices = kdtree.query([your_face_descriptor], k=4)
# 5. Выводим найденные 3 наиболее похожих фотографии
for i, idx in enumerate(indices[0][1:]):
similar_image = cv2.imread(image_paths[idx])
cv2.imshow(f"Similar Face {i+1}", similar_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
f1d39a470d4a6553a48bfa11567c4e55
|
{
"intermediate": 0.34829607605934143,
"beginner": 0.4217466711997986,
"expert": 0.22995725274085999
}
|
10,994
|
Is it possible to open an excel sheet as a popup window, edit it and auto save when closing the window
|
f88d383d60cb10d6e528962a6c5e93fc
|
{
"intermediate": 0.45028769969940186,
"beginner": 0.19984671473503113,
"expert": 0.34986555576324463
}
|
10,995
|
You didn;t continue your cdoe, Code: Here’s an example updated binance_futures.fapiPrivatePostOrder() method call:
response = binance_futures.fapiPrivatePostOrder(
data={
‘symbol’: ‘BTCUSDT’,
‘side’: ‘SELL’ if current_position[‘positionSide’] == ‘LONG’ else ‘BUY’,
‘type’: ‘MARKET’,
‘quantity’: abs(float(current_position[‘positionAmt’])),
‘positionSide’: current_position[‘positionSide’],
‘reduceOnly’: True
}
)
Replace ‘BTCUSDT’ with your desired symbol.
Regarding the long position not executing when you receive a buy signal, it’s possible that there is an issue with your signal generation logic or order execution logic. You can try adding print statements or logs to see what steps are being executed and whether there are any errors that are occurring.
Give me just right code of order_execution
Here’s an updated order_execution function with the changes:
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position[“symbol”] == symbol:
current_position = position
if current_position is not None and current_position[“positionAmt”] != 0:
response = binance_futures.fapiPrivatePostOrder(
data={
‘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:
try:
price = round_step_size(price, step_size=step_size)
if signal == ‘buy’:
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == ‘sell’:
# Calculate take profit and stop loss prices for a sell signal
|
22a2ed1c182480b875f2731d234747c9
|
{
"intermediate": 0.35100257396698,
"beginner": 0.49934253096580505,
"expert": 0.14965490996837616
}
|
10,996
|
Write me a working program in C, with this info, The saying ``You can't see the wood for the trees'' is not only a cliche, but is also
incorrect. The real problem is that you can't see the trees for the wood. If you stand in the
middle of a ``wood'' (in NZ terms, a patch of bush), the trees tend to obscure each other
and the number of distinct trees you can actually see is quite small. This is especially true
if the trees are planted in rows and columns (as in a pine plantation), because they tend to
line up. The purpose of this problem is to find how many distinct trees you can see from
an arbitrary point in a pine plantation (assumed to stretch ``for ever'').
You can only see a distinct tree if no part of its trunk is obscured by a nearer tree--that is
if both sides of the trunk can be seen, with a discernible gap between them and the trunks
of all trees closer to you. Also, you can't see a tree if it is apparently ``too small''. For
definiteness, ``not too small'' and ``discernible gap'' will mean that the angle subtended at
your eye is greater than 0.01 degrees (you are assumed to use one eye for observing).
Thus the two trees marked obscure at least the trees marked from the given view
point.
Write a program that will determine the number of trees visible under these assumptions,
given the diameter of the trees, and the coordinates of a viewing position. Because the
grid is infinite, the origin is unimportant, and the coordinates will be numbers between 0
and 1.
Input
Input will consist of a series of lines, each line containing three real numbers of the form
0.nn. The first number will be the trunk diameter--all trees will be assumed to be
cylinders of exactly this diameter, with their centres placed exactly on the points of a
rectangular grid with a spacing of one unit. The next two numbers will be the x and y
coordinates of the observer. To avoid potential problems, say by being too close to a tree,
we will guarantee that diameter≤x,y≤(1-diameter). To avoid problems with trees being
too small you may assume that diameter
0.1. The file will be terminated by a line
consisting of three zeroes.
Output
Output will consist of a series of lines, one for each line of the input. Each line will
consist of the number of trees of the given size, visible from the given position.
Sample input
0.10 0.46 0.38
0 0 0
Sample output
128, please make sure it's working, this is how the idea works, this could help you, "Since the limited opening angle is above 0.01, the trees that are too far away are not considered, so a part of the trees can be exhausted.
For the trees at the exhaustive position, the numbers from the current position are arranged from small to large, and start to consider whether there are trees in the front, so first calculate the opening angle [l, r] of each tree, and then for a tree, find out whether Shaded by trees that are closer.
For the part of calculating the opening angle (a point outside the circle), there are two ways
Calculate the intersection of the two tangents to obtain the angle formed by the two intersections, and ensure that it does not exceed 180 degrees.
Pull from the starting point to the center of the circle, after calculating the angle, according to the triangle formed by the tangent, calculate asin and superimpose the angle."
|
a8c85549dae0536b6eff9f5e2dd9674b
|
{
"intermediate": 0.4897450804710388,
"beginner": 0.2148865908384323,
"expert": 0.2953682839870453
}
|
10,997
|
Поменяй этот код для игры scp sl def get_server_online():
try:
game_info = gamedig.query(“garrysmod”, host=f”{server_address}:{server_port}”)
online_players = game_info[“players”]
return online_players
except gamedig.GamedigError as e:
print("Error getting server info: ", e)
|
769b8a3cc4d100147df6a5032eb44099
|
{
"intermediate": 0.2761530876159668,
"beginner": 0.4858250617980957,
"expert": 0.2380218356847763
}
|
10,998
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 5000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
usdt_balance = next((item for item in account_info['assets'] if item["asset"] == "USDT"), {"balance": 0})
max_trade_size = float(usdt_balance.get("balance", 0)) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 44640)
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', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
response = binance_futures.fapiPrivatePostOrder(
data={
'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(
data={
'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', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, signal:{signal}")
if signal:
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR in order exceution, ERROR:The signal time is: 2023-06-09 00:13:02, signal:buy
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 270, 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 181, in order_execution
if 'orderId' in response:
^^^^^^^^^
UnboundLocalError: cannot access local variable 'response' where it is not associated with a value
|
9727b989926d2156fdb223a6db24c0db
|
{
"intermediate": 0.38698631525039673,
"beginner": 0.42868635058403015,
"expert": 0.1843273788690567
}
|
10,999
|
I have a python code source.py that I want to generate a build.py file via a bashscript. I want to find and replace the "#build_token" in the python and replace it with actual token and save it as new file in /build/file.py
|
9a82602d78a24672217e3b1226dd2f3e
|
{
"intermediate": 0.369597464799881,
"beginner": 0.24844196438789368,
"expert": 0.38196060061454773
}
|
11,000
|
this is my code: Cell In[74], line 1
| Artist Name | Album Name | Release Date |
^
SyntaxError: invalid syntax
and it has this error: Cell In[74], line 1
| Artist Name | Album Name | Release Date |
^
SyntaxError: invalid syntax
fix it
|
41466d9f19942884370f11e9714b5440
|
{
"intermediate": 0.18453042209148407,
"beginner": 0.6747570633888245,
"expert": 0.14071249961853027
}
|
11,001
|
Исправь код result is not pylance. import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
import time
import
# Конфигурация почты
MY_EMAIL = "fariuman1@gmail.com"
MY_PASSWORD = "Minikraft839"
SMTP_SERVER = "smtp.example.com"
SMTP_PORT = 465
def main():
# Запрос на страницу Funpay
category = "game-goods/path-of-exile/orbs"
search_term = "exalted orb"
min_price = "300"
max_price = "500"
url = f"https://funpay.ru/{category}?search={search_term}&sort=price_desc&min_price={min_price}&max_price={max_price}"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
# Поиск всех лотов на странице
results = soup.select(".lot-item")
items = []
for result in results:
# Извлечение имени, стоимости и ссылки на лот
name = result.select(".lot-item__title a")[0].text
price = result.select(".lot-item__price .num")[0].text
link = result.select(".lot-item__title a")[0].get("href")
item = f"{name}: {price} <{link}>"
items.append(item)
# Создание сообщения для письма
subject = f"Funpay search results for {search_term}"
body = "\n\n".join(items)
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = MY_EMAIL
msg["To"] = MY_EMAIL
# Отправка письма
with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as smtp:
smtp.login(MY_EMAIL, MY_PASSWORD)
smtp.send_message(msg)
# поиск name element
name_element = result.select(".lot-item__title a")
if len(name_element) > 0:
name = name_element[0].text.strip()
else:
name = "Нет названия"
if name == "main":
while True:
main()
# Отправка сообщения через каждый час
time.sleep(3000)
|
350a78af5b9f8bd84ac4747663f5bc8d
|
{
"intermediate": 0.34013572335243225,
"beginner": 0.42583322525024414,
"expert": 0.23403102159500122
}
|
11,002
|
Write me a code for feature elimination for that model:
#Transforming into dedicated structures
xdm_train = xgboost.DMatrix(X, Y, enable_categorical=True, missing=True)
xdm_test = xgboost.DMatrix(X_test, Y_test, enable_categorical=True, missing=True)
#Model training
model = xgboost.train({'max_depth': 1, 'learning_rate': 0.1985084799854787, 'subsample': 0.7070790605484081, 'gamma': 12.877096754554092, 'reg_alpha': 0.515404617994273, 'reg_lambda': 0.603459056579974, 'min_split_loss': 1.986785725569312,'eval_metric': 'auc','objective': 'binary:logitraw'}, xdm_train,267, [(xdm_test, 'eval'), (xdm_train, 'train')])
print(model)
|
d4384a4952731a86f3f0cb40436fbf1a
|
{
"intermediate": 0.2554378807544708,
"beginner": 0.16986453533172607,
"expert": 0.5746976137161255
}
|
11,003
|
hello
|
be94173ee8e622b326f9880edf8c1ac6
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
11,004
|
# Оптимизированный!!! Возвращает адреса созданных токенов в указанном диапазоне блоков (Обрабатывет множество блоков)
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')
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
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:
print(f'New contract creation: Contract Address: {contract_address}')
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 = 28866529 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
Complete the code above so that it also determines whether the contract is verified or not
|
83791535aa87405f2d2c0521a6703bd3
|
{
"intermediate": 0.39617377519607544,
"beginner": 0.4186747372150421,
"expert": 0.18515151739120483
}
|
11,005
|
Найди и исправь ошибки в программе:
Program obsch;
const MAX_N = 100;
type
TEO = integer;
TQueue = record
arr: array[1..MAX_N] of TEO;
head, tail: integer;
end;
procedure cleanQ(var first, last: TQueue);
begin
first := nil;
last := nil;
end;
function emptyQ(var first, last: TQueue):boolean;
begin
if (first = nil) and (last = nil) then
emptyQ := true
else emptyQ := false;
end;
procedure addQ(var first, last: TQueue; e: TEO);
var pcurr: TypeNode;
begin
if first - last >= MAX_N then writeln('Ошибка 1');
new(pcurr);
pcurr^.a := e;
pcurr^.next := nil;
last^.next := pcurr;
end;
function deleteQ(var first, last:TQueue): boolean;
var pcurr: TypeNode;
begin
if(first = nil) and (last = nil) then
begin
writeln('Ошибка 1');
deleteQ := false;
end
else if (first = last) and (last <> nil) then
begin
pcurr := first;
first := nil;
last := nil;
dispose(pcurr);
deleteQ := true
end
else begin
pcurr := first;
first := first^.next;
dispose(pcurr);
deleteQ := true;
end;
end;
var
Q: TQueue;
i, n: integer;
value: TEO;
begin
Write('Введите размер очереди (n): ');
ReadLn(n);
cleanQ(Q);
for i := 1 to n do
begin
Write('Введите элемент очереди: ');
ReadLn(value);
addQ(Q, value);
end;
WriteLn;
end.
|
55c7fa799bad2b56930a2bfca38dbe61
|
{
"intermediate": 0.3207132816314697,
"beginner": 0.3769086003303528,
"expert": 0.3023780286312103
}
|
11,006
|
New contract creation: Contract Address: 0x18f82923150a1fece0cc870b21dcdcccf732cf7f, Verified: False, Contract Name:
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 101, in <module>
asyncio.run(main())
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 99, in main
await display_transactions(block_start, block_end)
File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 93, in display_transactions
await asyncio.gather(*tasks)
File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 88, in process_block
verified, contract_name = await get_contract_verification_status_and_name(contract_address)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 63, in get_contract_verification_status_and_name
contract_name = result.get("ContractName", "") if verified else ""
^^^^^^^^^^
AttributeError: 'str' object has no attribute 'get'
Process finished with exit code 1
|
d207de97f9c42e83c68e5f5a4878f423
|
{
"intermediate": 0.44116848707199097,
"beginner": 0.33927905559539795,
"expert": 0.21955251693725586
}
|
11,007
|
MACD Zero EA full code
|
bd454bf38d56499634e0ec7e82f0abfa
|
{
"intermediate": 0.2782939076423645,
"beginner": 0.21306206285953522,
"expert": 0.5086439847946167
}
|
11,008
|
1
2
#include <iostream> #include <cstdio>
3
#include <string>
5
#define pb push back #define FOR(i, n) for (int i=0;i<n;i++)
7 8
using namespace std;
9
10 11 12
int main ()
13
14
15 16 17
string a, b, c, a1, b1, c1; cin >>a>>b>>c; FOR (i, 200-a. length () )
a1. pb ( ' 0 ) ;
18
19
FOR (i, 200-b. length () ) b1. pb ( ;
20
21
22
FOR (i, 200-c. length () ) c1. pb ( 0*) ;
23 24
a1+=a;
25
b1+=b;
26
c1+=c;
27
28
if (a1>b1 && a1>c1) [cout <<a;return O;) else
29
30
if (b1>a1 b1>c1) [cout <<b; return else
31
32
cout <<c;
return O;
33 34
|
c0b288eb3e27c5d8df26ffd625892279
|
{
"intermediate": 0.3850851058959961,
"beginner": 0.45439833402633667,
"expert": 0.16051656007766724
}
|
11,009
|
# Оптимизированный!!! Возвращает адреса созданных токенов в указанном диапазоне блоков (Обрабатывет множество блоков)
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_and_name(contract_address: 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}"
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.get("result") is None or not isinstance(data.get("result"), str):
return False, ""
result = data.get("result", {})
verified = data["result"] != "Contract source code not verified"
contract_name = result.get("ContractName", "") if verified else ""
return verified, contract_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)
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, contract_name = await get_contract_verification_status_and_name(contract_address)
print(f"New contract creation: Contract Address: {contract_address}, Verified: {verified}, Contract Name: {contract_name}")
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 = 28866530 # Replace with your desired starting block number
block_end = 28866929 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
the above code is still throwing an error
Transactions in block 28866929:
New contract creation: Contract Address: 0x77c3da1b2878054175f61417167fe74f2de7cfdb, Verified: False, Contract Name:
New contract creation: Contract Address: 0x18f82923150a1fece0cc870b21dcdcccf732cf7f, Verified: False, Contract Name:
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 101, in <module>
asyncio.run(main())
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 99, in main
await display_transactions(block_start, block_end)
File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 93, in display_transactions
await asyncio.gather(*tasks)
File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 88, in process_block
verified, contract_name = await get_contract_verification_status_and_name(contract_address)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddress\main.py", line 63, in get_contract_verification_status_and_name
contract_name = result.get("ContractName", "") if verified else ""
^^^^^^^^^^
AttributeError: 'str' object has no attribute 'get'
Process finished with exit code 1
Fix it
|
7216a69cd64c0d6b52c476f0d46c95f2
|
{
"intermediate": 0.3706105649471283,
"beginner": 0.4434684216976166,
"expert": 0.18592102825641632
}
|
11,010
|
MACD Zero EA mt4 full code
|
99e176016f654f33a46b3a45dcdecd60
|
{
"intermediate": 0.27538546919822693,
"beginner": 0.22858525812625885,
"expert": 0.49602922797203064
}
|
11,011
|
In Python I have this code:
def model_call(path_in,path_out,model, dataset, debug):
import xgboost
import pandas as pd
import math
import category_encoders as ce
if dataset.endswith(".sas7bdat") > 1:
ds_path=path_in+dataset
else :
ds_path=path_in+dataset+".sas7bdat"
model_path=path_in+model
out_path=path_out+"outscore.csv"
if debug ==1:
print ("path: "+path_in)
print ("model name: " +model)
print ("dataset name: " +dataset)
print("DS_path: " +ds_path)
target_name='default12'
time_name='period'
intercept_name='Intercept'
event_value='outstanding_bad'
all_value='outstanding'
id_vars=['aid']
df = pd.read_sas(ds_path, encoding='LATIN2')
df[intercept_name]=1
df[event_value]=df['app_loan_amount']*df[target_name]
df[all_value]=df['app_loan_amount']
#List of variables
vars = [var for var in list(df) if var[0:3].lower() in ['app','act']]
# vars = [var for var in list(df) if var[0:3].lower() in ['app','act','agr','ags']]
#Splitting into numeric and character variables
varsc = list(df[vars].select_dtypes(include='object'))
varsn = list(df[vars].select_dtypes(include='number'))
#Categorical variables coding
enc = ce.BinaryEncoder(cols=varsc)
df_ce = enc.fit_transform(df[varsc])
varsc_ce = list(df_ce)
# df_ce = enc.fit_transform(df)
df_ce=df
vars_ce = varsn
# vars_ce = varsn + varsc_ce
test = df_ce
test[target_name]=1
X_test=test[vars_ce]
Y_test=test[target_name]
if debug ==1:
print (test.shape)
print (df.shape)
xdm_test = xgboost.DMatrix(X_test, Y_test, enable_categorical=True, missing=True)
model = xgboost.Booster()
model.load_model(model_path)
Y_pred_test = model.predict(xdm_test)
df_out=df
df_out['SCORECARD_POINTS']= pd.DataFrame(Y_pred_test)
fin_vars= ['SCORECARD_POINTS'] + [time_name] + id_vars
df_out=df_out[fin_vars]
df_out.to_csv(out_path, index=False)
return 0
Which is called by SAS here:
libname sclib "&scoring_dir";
data sclib.indata;
set &zbior;
run;
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",0);
Result = py.results["model_call"];
put Result=;
run;
However I want to call that Python function directly in SAS with the following arguments given in py.call.
|
65ea4dd4a165cbd765c0b037d3164a6d
|
{
"intermediate": 0.4244738817214966,
"beginner": 0.44914907217025757,
"expert": 0.12637704610824585
}
|
11,012
|
how to print names of several images in a folder using python
|
6dc716d8a01152721a23dfe9e145931a
|
{
"intermediate": 0.42570969462394714,
"beginner": 0.1848217397928238,
"expert": 0.38946858048439026
}
|
11,013
|
So I tried running this:
proc fcmp;
declare object py(python);
declare object py(python);
submit into py;
def model_call(path_in, path_out, model, dataset, debug):
import xgboost
import pandas as pd
import math
import category_encoders as ce
if dataset.endswith(".sas7bdat") > 1:
ds_path = path_in + dataset
else:
ds_path = path_in + dataset + ".sas7bdat"
model_path = path_in + model
out_path = path_out + "outscore.csv"
if debug == 1:
print("path: " + path_in)
print("model name: " + model)
print("dataset name: " + dataset)
print("DS_path: " + ds_path)
target_name = "default12"
time_name = "period"
intercept_name = "Intercept"
event_value = "outstanding_bad"
all_value = "outstanding"
id_vars = ["aid"]
df = pd.read_sas(ds_path, encoding="LATIN2")
df[intercept_name] = 1
df[event_value] = df["app_loan_amount"] * df[target_name]
df[all_value] = df["app_loan_amount"]
vars = [var for var in list(df) if var[0:3].lower() in ["app","act","agr","ags"]]
varsc = list(df[vars].select_dtypes(include="object"))
varsn = list(df[vars].select_dtypes(include="number"))
enc = ce.BinaryEncoder(cols=varsc)
df_ce = enc.fit_transform(df[varsc])
varsc_ce = list(df_ce)
df_ce = df
vars_ce = varsn
test = df_ce
test[target_name] = 1
X_test = test[vars_ce]
Y_test = test[target_name]
if debug == 1:
print(test.shape)
print(df.shape)
xdm_test = xgboost.DMatrix(X_test, Y_test, enable_categorical=True, missing=True)
model = xgboost.Booster()
model.load_model(model_path)
Y_pred_test = model.predict(xdm_test)
df_out = df
df_out["SCORECARD_POINTS"] = pd.DataFrame(Y_pred_test)
fin_vars = ["SCORECARD_POINTS"] + [time_name] + id_vars
df_out = df_out[fin_vars]
df_out.to_csv(out_path, index=False)
return 0,
endsubmit;
rc = py.publish();
rc = py.call("model_call", "&scoring_dir", "&scoring_dir", 'xgb1.model', "indata", 0);
Result = py.results["model_call"];
put Result=;
run;
but I get error:
/* <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS> */
1852
1853 /* model calibration process, cut-off calculation, to make a profitable products */
1854
1855 options mprint;
1856 options nomprint;
1857 %let dir=C:\Users\Użytkownik\Desktop\Credit Scoring\software\PROCSS_SIMULATION\;
1858
1859 libname data "&dir.process\data\" compress=yes;
NOTE: Libref DATA was successfully assigned as follows:
Engine: V9
Physical Name: C:\Users\Użytkownik\Desktop\Credit
Scoring\software\PROCSS_SIMULATION\process\data
1860
1861 %let apr_ins=0.01;
1862 %let apr_css=0.18;
1863 %let lgd_ins=0.45;
1864 %let lgd_css=0.55;
1865 %let provision_ins=0;
1866 %let provision_css=0;
1867
1868
1869
1870 data cal;
1871 set data.abt_app;
1872 if default12 in (0,.i,.d) then default12=0;
1873 where '197501'<=period<='198712' and decision='A';
1874 run;
NOTE: There were 31212 observations read from the data set DATA.ABT_APP.
WHERE (period>='197501' and period<='198712') and (decision='A');
NOTE: The data set WORK.CAL has 31212 observations and 219 variables.
NOTE: DATA statement used (Total process time):
real time 0.20 seconds
cpu time 0.18 seconds
1875
1876 %let zbior=cal;
1877 %let scoring_dir=&dir.process\calibration\model_XGBoost\;
1878 %include "&scoring_dir.scoring_code.sas";
NOTE: Libref SCLIB was successfully assigned as follows:
Engine: V9
Physical Name: C:\Users\Użytkownik\Desktop\Credit
Scoring\software\PROCSS_SIMULATION\process\calibration\model_XGBoost
NOTE: There were 31212 observations read from the data set WORK.CAL.
NOTE: The data set SCLIB.INDATA has 31212 observations and 219 variables.
NOTE: DATA statement used (Total process time):
real time 0.04 seconds
cpu time 0.04 seconds
WARNING: Method 'model_call' not found in module dictionary
ERROR: masSymCreate encountered a failure in sfSym2Create, rc=0x8B3FF0D3.
ERROR: Unable to call function 'model_call'. Possible missing 'Output:' return signature in Python
source code.
ERROR: Error reported in function 'python:CALL' in statement number 5 at line 2441 column 4.
The statement was:
1 (2441:4) rc = python:CALL( "model_call", "C:\Users\Użytkownik\Desktop\Credit
Scoring\software\PROCSS_SIMULATION\process\calibration\model_XGBoost\", "
C:\Users\Użytkownik\Desktop\Credit
Scoring\software\PROCSS_SIMULATION\process\calibration\model_XGBoost\", "xgb1.model", "indata", 0 )
NOTE: PROCEDURE FCMP used (Total process time):
real time 0.17 seconds
cpu time 0.00 seconds
ERROR: Physical file does not exist, C:\Users\Użytkownik\Desktop\Credit
Scoring\software\PROCSS_SIMULATION\process\calibration\model_XGBoost\outscore.csv.
NOTE: The SAS System stopped processing this step because of errors.
WARNING: The data set WORK.SCORE may be incomplete. When this step was stopped there were 0
observations and 3 variables.
WARNING: Data set WORK.SCORE was not replaced because this step was stopped.
NOTE: DATA statement used (Total process time):
real time 0.00 seconds
cpu time 0.00 seconds
|
05d0508cc3965dfd928c336a926afce4
|
{
"intermediate": 0.43004417419433594,
"beginner": 0.3990688920021057,
"expert": 0.17088687419891357
}
|
11,014
|
# Оптимизированный!!! Возвращает адреса созданных токенов в указанном диапазоне блоков (Обрабатывет множество блоков)
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"
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)
print( f"New contract creation: Contract Address: {contract_address}, 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 = 28866529 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
Complete the code above so that it also displays information about whether the contract address has a name or not
|
8e9226d3b9e7587028a571b5fd1c731e
|
{
"intermediate": 0.3218131959438324,
"beginner": 0.5130090117454529,
"expert": 0.16517776250839233
}
|
11,015
|
Допиши программу, чтобы можно было добавить и убрать элемент из очереди с выводом этой очереди
Program obsch;
type
TypeNode = ^Node;
Node = record
a: integer;
Next: TypeNode;
end;
procedure cleanQ(var first, last: TypeNode);
begin
first := nil;
last := nil;
end;
function emptyQ(var first, last: TypeNode):boolean;
begin
if (first = nil) and (last = nil) then
emptyQ := true
else emptyQ := false;
end;
procedure addQ(var first, last: TypeNode; e: TEO);
var pcurr: TypeNode;
begin
new(pcurr);
pcurr^.a := e;
pcurr^.next := nil;
last^.next := pcurr;
end;
function deleteQ(var first, last:TypeNode): boolean;
var pcurr: TypeNode;
begin
if(first = nil) and (last = nil) then
begin
deleteQ := false;
end
else if (first = last) and (last <> nil) then
begin
pcurr := first;
first := nil;
last := nil;
dispose(pcurr);
deleteQ := true
end
else begin
pcurr := first;
first := first^.next;
dispose(pcurr);
deleteQ := true;
end;
end;
|
8326b6a9dc1e433099db23c167db090f
|
{
"intermediate": 0.40226125717163086,
"beginner": 0.39868980646133423,
"expert": 0.1990489363670349
}
|
11,016
|
thumbContent Switch jetpack compose
|
d795bb844436ff2c3a74553ac3961a1c
|
{
"intermediate": 0.3545714318752289,
"beginner": 0.3604893982410431,
"expert": 0.284939169883728
}
|
11,017
|
Исправь программу:
Program obsch;
type
TypeNode = ^node;
node = record
s:char;
next:TypeNode;
end;
var
inn, ou: string;
i, j: integer;
c: char;
top: TypeNode;
function deleteS(var top: TypeNode; x: char): boolean;
var pcurr: TypeNode;
begin
if (top = nil) then
deleteS := false
else if (top^.next = nil) then begin
pcurr := top;
top := nil;
dispose(pcurr);
deleteS := true;
end
else begin
pcurr := top;
top := top^.next;
dispose(pcurr);
deleteS := true;
end;
end;
procedure addS(var Top: TypeNode; x: char);
var pcurr: TypeNode;
begin
new(pcurr);
pcurr^.s := x;
pcurr^.next := top;
top := pcurr;
end;
begin
j := 1;
addS(Top, '(');
read(inn);
for i := 1 to length(inn) do
begin
if(inn[i] >= '0') and (inn[i] <= '9') then
ou[j] := inn[i];
j += 1;
end;
if (inn[i] = '(') then
addS(top, '(');
if(inn[i] = ')') then begin
deleteS(top, c);
while(c <> '(') do begin
deleteS(top, c);
if(c = '+') or (c = '-') or (c = '*') or (c = '/') then begin
ou[j] := c;
j += 1;
end;
end;
if (c = '*') or (c = '/') then
while(c <> '(') do begin
deleteS(top, c);
ou[j] := c;
j += 1;
end;
if (c = '+') or (c = '-') then
while (c <> '*') and (c <> '/') and (c <> '(') do begin
deleteS(top, c);
ou[j] := c;
j += 1;
end;
end;
deleteS(top, c);
while(c <> '(') do begin
ou[j] := c;
j += 1;
deleteS(top, c);
end;
write(ou);
end.
|
410fc2c6a25c056158262c2cc0a85d99
|
{
"intermediate": 0.34044376015663147,
"beginner": 0.4136906564235687,
"expert": 0.2458655834197998
}
|
11,018
|
i need that when user clicks on button is sends the message on his email that they have successfully booked this post and then they can see it in profile
here is code of post
import { Text, View, Image, Pressable, ScrollView } from 'react-native';
import { gStyle } from '../styles/style';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { Ionicons, MaterialCommunityIcons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import moment from 'moment';
export default function SignUpForMK({route}) {
const {mkData}=route.params;
const navigation = useNavigation();
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<View style={gStyle.SupBox}>
<Text style={gStyle.header}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
<Text style={gStyle.SupDate}>{moment(mkData.time.toDate()).format('Do MMM YYYY')}</Text>
<View style={gStyle.SupContainer}>
<Image
source={{uri:mkData.image}}
style={gStyle.SupImg}
/>
<View style={gStyle.SupForm}>
<View style={gStyle.SupPrice}>
<Text style={gStyle.SupPrice1}>Цена: </Text>
<Text style={gStyle.SupNumber}>{mkData.price} Р.</Text>
</View>
</View>
<Text style={gStyle.SupDescription}>
{mkData.description}
</Text>
<Text style={gStyle.SupLine}></Text>
<View style={gStyle.SupContaier1}>
<View style={gStyle.SupBox1}>
<Ionicons name="person-outline" size={30} color="black" />
<Text style={gStyle.SupPerson}>{mkData.person} человек</Text>
</View>
<View style={gStyle.SupBox1}>
<MaterialCommunityIcons
name="clock-time-four-outline"
size={30}
color="black"
/>
<Text style={gStyle.SupAlarm}>{mkData.timeOfMK} час(а)</Text>
</View>
</View>
<Text style={gStyle.SupLine}></Text>
<Pressable style={gStyle.SupMoreDetails}
onPress={()=>navigation.navigate('FormAddMK')}
>
<Text style={gStyle.SupBtn}>Записаться</Text>
</Pressable>
</View>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
here is code of profile
import { Text, View, Image, ScrollView, Pressable } from 'react-native';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { gStyle } from '../styles/style';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState, useEffect} from 'react';
import { useNavigation } from '@react-navigation/native';
export default function Profile() {
const navigation = useNavigation();
const [userData, setUserData] = useState(null);
useEffect(() => {
const currentUserID = firebase.auth().currentUser.uid;
firebase
.database()
.ref('users/' + currentUserID)
.once('value')
.then((snapshot) => {
const data = snapshot.val();
setUserData(data);
});
}, []);
const handleLogOut = async () => {
try {
await firebase.auth().signOut();
navigation.navigate('Auth');
} catch (error) {
console.error(error);
}
};
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<View style={gStyle.ProfileBox}>
<View style={gStyle.ProfileGreeting}>
<Text style={gStyle.ProfileName}>{userData?.name},</Text>
<Text style={gStyle.ProfileHello}>Добро пожаловать в{'\n'}личный кабинет</Text>
</View>
<View style={gStyle.ProfileBlock}>
<View style={gStyle.ProfileChain}>
<Text style={gStyle.ProfileTitle}>Имя</Text>
<View style={gStyle.ProfileInfo}>
<Text style={gStyle.ProfileValue}>{userData?.name}</Text>
</View>
</View>
<View style={gStyle.ProfileChain}>
<Text style={gStyle.ProfileTitle}>Фамилия</Text>
<View style={gStyle.ProfileInfo}>
<Text style={gStyle.ProfileValue}>{userData?.surname}</Text>
</View>
</View>
<View style={gStyle.ProfileChain}>
<Text style={gStyle.ProfileTitle}>Электронная почта</Text>
<View style={gStyle.ProfileInfo}>
<Text style={gStyle.ProfileValue}>{userData?.email}</Text>
</View>
</View>
<View style={gStyle.ProfileChain}>
<Text style={gStyle.ProfileTitle}>Номер телефона</Text>
<View style={gStyle.ProfileInfo}>
<Text style={gStyle.ProfileValue}>{userData?.phone}</Text>
</View>
</View>
<Pressable style={gStyle.logout}
onPress={handleLogOut}
>
<Text>Выйти</Text>
</Pressable>
</View>
</View>
<View style={gStyle.ProfilePaidMK}>
<Text style={gStyle.ProfilePaid}>Забронированные{'\n'}мастер-классы</Text>
<Text style={gStyle.ProfileLine}></Text>
<View style={gStyle.ProfileDetails}>
<Image source={FutureMK.image}} style={gStyle.ProfileImg}/>
<View style={gStyle.ProfileDescription}>
<Text style={gStyle.ProfileTitleOfMK}>{fitireMK.name}</Text>
<Text style={gStyle.ProfileDate}>{futureMK.time}</Text>
<Text style={gStyle.ProfilePrice}>Цена: {futureMK.price} Р.</Text>
</View>
</View>
<Text style={gStyle.ProfileLine}></Text>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
|
aa808d294b43d370959f9ebd81dedda5
|
{
"intermediate": 0.5493606925010681,
"beginner": 0.3404850661754608,
"expert": 0.11015428602695465
}
|
11,019
|
Сделай пожалуйста, чтобы данная программа работала как польская обратная запись:
Program obsch;
type
TypeNode = ^node;
node = record
s:char;
next:TypeNode;
end;
var
inn, ou: string;
i, j: integer;
c: char;
top: TypeNode;
function deleteS(var top: TypeNode; x: char): boolean;
var pcurr: TypeNode;
begin
if (top = nil) then
deleteS := false
else if (top^.next = nil) then begin
pcurr := top;
top := nil;
dispose(pcurr);
deleteS := true;
end
else begin
pcurr := top;
top := top^.next;
dispose(pcurr);
deleteS := true;
end;
end;
procedure addS(var Top: TypeNode; x: char);
var pcurr: TypeNode;
begin
new(pcurr);
pcurr^.s := x;
pcurr^.next := top;
top := pcurr;
end;
begin
j := 1;
addS(Top, '(');
read(inn);
for i := 1 to length(inn) do
begin
if(inn[i] >= '0') and (inn[i] <= '9') then
ou[j] := inn[i];
j += 1;
end;
if (inn[i] = '(') then
addS(top, '(');
if(inn[i] = ')') then begin
deleteS(top, c);
while(c <> '(') do begin
deleteS(top, c);
if(c = '+') or (c = '-') or (c = '*') or (c = '/') then begin
ou[j] := c;
j += 1;
end;
end;
if (c = '*') or (c = '/') then
while(c <> '(') do begin
deleteS(top, c);
ou[j] := c;
j += 1;
end;
if (c = '+') or (c = '-') then
while (c <> '*') and (c <> '/') and (c <> '(') do begin
deleteS(top, c);
ou[j] := c;
j += 1;
end;
end;
deleteS(top, c);
while(c <> '(') do begin
ou[j] := c;
j += 1;
deleteS(top, c);
end;
write(ou);
end.
|
67963d829f0b0cf192c14e693d3e5361
|
{
"intermediate": 0.2941696047782898,
"beginner": 0.47736045718193054,
"expert": 0.22846990823745728
}
|
11,020
|
npx mikro-orm migration:create --initial команда не работает. npm ERR! could not determine executable to run
|
dbbac379fb233a507437abbceb48c805
|
{
"intermediate": 0.33334022760391235,
"beginner": 0.31043025851249695,
"expert": 0.3562295138835907
}
|
11,021
|
RSN eXtension IE
|
053a04a58d26e6878bfdca529fee30c3
|
{
"intermediate": 0.2937130033969879,
"beginner": 0.16524803638458252,
"expert": 0.5410389304161072
}
|
11,022
|
生成训练和测试数据
train_X, train_Y = generate_data(train_data[['red1', 'red2', 'red3', 'red4', 'red5', 'red6', 'blue']].values, lookback)
test_X, test_Y = generate_data(test_data[['red1', 'red2', 'red3', 'red4', 'red5', 'red6', 'blue']].values, lookback)
创建LSTM模型
model = Sequential()
model.add(LSTM(64, input_shape=(lookback, 7)))
model.add(Dense(32, activation='relu'))
model.add(Dense(7, activation='sigmoid'))
model.compile(loss='mean_squared_error', optimizer='adam')
训练模型
model.fit(train_X, train_Y, batch_size=batch_size, epochs=epochs, validation_data=(test_X, test_Y))
预测下一期双色球
last_data = data[['red1', 'red2', 'red3', 'red4', 'red5', 'red6', 'blue']].tail(lookback)
last_data = (last_data - 1) / np.array([33, 33, 33, 33, 33, 33, 16])
last_data = np.array(last_data)
last_data = np.reshape(last_data, (1, lookback, 7))
prediction = model.predict(last_data)
prediction = np.round(prediction * np.array([33, 33, 33, 33, 33, 33, 16]) + np.array([1, 1, 1, 1, 1, 1, 1]))
print("下一期双色球预测结果为:", prediction)
现在你是一个python专家,请优化上面的代码
|
89369abd164126ef26cc0a105e9b989c
|
{
"intermediate": 0.3026043474674225,
"beginner": 0.3304627239704132,
"expert": 0.3669328987598419
}
|
11,023
|
visual studio 遇到unable to access 'http://XXX.git /': URL using bad/illegal format or missing URL如何处理
|
dddf26f7d65531b5ecfc77d3bc88a07f
|
{
"intermediate": 0.2925150394439697,
"beginner": 0.3775215148925781,
"expert": 0.3299635052680969
}
|
11,024
|
Приведи пример корректного ввода в эту программу:
program obsch;
type
TypeNode = ^node;
node = record
s: char;
next: TypeNode;
end;
var
inn, ou: string;
i, j, len: integer;
c: char;
top: TypeNode;
function deleteS(var top: TypeNode; x: char): boolean;
var
pcurr: TypeNode;
begin
if (top = nil) then
deleteS := false
else
begin
pcurr := top;
top := top^.next;
dispose(pcurr);
deleteS := true;
end;
end;
procedure addS(var top: TypeNode; x: char);
var
pcurr: TypeNode;
begin
new(pcurr);
pcurr^.s := x;
pcurr^.next := top;
top := pcurr;
end;
begin
j := 1;
addS(top, '(');
readln(inn);
len := length(inn);
setlength(ou, len);
for i := 1 to len do
begin
if (inn[i] in ['0'..'9']) then // заменили сравнение на проверку диапазона
begin
ou[j] := inn[i];
j := j + 1; // заменили инкремент на j := j + 1
end;
end;
if (inn[length(inn)] = '(') then
addS(top, '(');
if(inn[length(inn)] = ')') then
begin
deleteS(top, c);
while(c <> '(') do
begin
deleteS(top, c);
if(c in ['+', '-', '*', '/']) then // заменили длинную проверку на проверку наличия в диапазоне
begin
if j <= len then begin
ou[j] := c;
j := j + 1; // заменили инкремент на j := j + 1
end;
end;
end;
if (c = '*') or (c = '/') then
while(c <> '(') do
begin
deleteS(top, c);
if j <= len then begin
ou[j] := c;
j := j + 1; // заменили инкремент на j := j + 1
end;
end;
if (c = '+') or (c = '-') then
while (c <> '*') and (c <> '/') and (c <> '(') do
begin
deleteS(top, c);
if j <= len then begin
ou[j] := c;
j := j + 1; // заменили инкремент на j := j + 1
end;
end;
end;
deleteS(top, c);
while(c <> '(') do
begin
if j <= len then
begin
ou[j] := c;
j := j + 1; // заменили инкремент на j := j + 1
end;
deleteS(top, c);
end;
write(ou);
end.
|
0b3e6590fa498bb3b577a74531bd16b9
|
{
"intermediate": 0.2826792001724243,
"beginner": 0.49093925952911377,
"expert": 0.2263815701007843
}
|
11,025
|
能否消除这个函数中的重复代码
hasp.logout();
setHaspSt(status);
除了使用将其作为函数封装之外的办法
bool SntlLicGenPrivate::clearBuffer(int startIdx, int ulSize,
const unsigned long featId)
{
vector<unsigned char> buffer(ulSize, 0);
ChaspFeature feature = ChaspFeature::fromFeature(featId);
Chasp hasp(feature);
const string scope = getProdIdScope();
auto status = hasp.login(vendorCode, scope);
if(HASP_SUCCEEDED(status)){
ChaspFile file = hasp.getFile(ChaspFile::fileReadWrite);
file.setFilePos(startIdx);
status = file.write(&buffer[0], ulSize);
if(HASP_SUCCEEDED(status)){
hasp.logout();
setHaspSt(status);
return true;
}
}
hasp.logout();
setHaspSt(status);
return false;
}
|
7f63e560ddae5d3b4da6ea9558f820c7
|
{
"intermediate": 0.45540714263916016,
"beginner": 0.3670106530189514,
"expert": 0.17758221924304962
}
|
11,026
|
Программа бесконечно выполняется. Можешь исправить?
Program obsch;
type
TypeNode = ^node;
node = record
s:char;
next:TypeNode;
end;
var
inn, ou: string;
i, j: integer;
c: char;
top: TypeNode;
function deleteS(var top: TypeNode; x: char): boolean;
var pcurr: TypeNode;
begin
if (top = nil) then
deleteS := false
else if (top^.next = nil) then begin
pcurr := top;
top := nil;
dispose(pcurr);
deleteS := true;
end
else begin
pcurr := top;
top := top^.next;
dispose(pcurr);
deleteS := true;
end;
end;
procedure addS(var Top: TypeNode; x: char);
var pcurr: TypeNode;
begin
new(pcurr);
pcurr^.s := x;
pcurr^.next := top;
top := pcurr;
end;
begin
j := 1;
addS(Top, '(');
read(inn);
ou := ' ';
for i := 1 to length(inn) do
begin
if(inn[i] >= '0') and (inn[i] <= '9') then
ou += inn[i];
j += 1;
end;
if (inn[i] = '(') then
addS(top, '(');
if(inn[i] = ')') then begin
deleteS(top, c);
while(c <> '(') do begin
deleteS(top, c);
if(c = '+') or (c = '-') or (c = '*') or (c = '/') then begin
ou[j] := c;
j += 1;
end;
end;
if (c = '*') or (c = '/') then
while(c <> '(') do begin
deleteS(top, c);
ou[j] := c;
j += 1;
end;
if (c = '+') or (c = '-') then
while (c <> '*') and (c <> '/') and (c <> '(') do begin
deleteS(top, c);
ou[j] := c;
j += 1;
end;
end;
deleteS(top, c);
while(c <> '(') do begin
ou[j] := c;
j += 1;
deleteS(top, c);
end;
write(ou);
end.
|
b5ec191a28dc6ac165a7de716d5f41e5
|
{
"intermediate": 0.1996069699525833,
"beginner": 0.6081857085227966,
"expert": 0.19220726191997528
}
|
11,027
|
Мне нужно сделать так, чтоб при регистрации и поиске пользователь мог выбрать подходящий город, регион из json файла russia.json с городами, регионами. Кроме того, при регистрации или поиске должна быть возможность быстрого поиска города: например, пользователь в поле вводит "Моск" и получает подсказку в виде автозаполняемого поля (что-то вроде подсказок в поисковике Google). Структура russia.json выглядит так:
[
{
“region”: “Москва и Московская обл.”,
“city”: “Москва”
},
{
“region”: “Москва и Московская обл.”,
“city”: “Абрамцево”
},
{
“region”: “Москва и Московская обл.”,
“city”: “Алабино”
},
{
“region”: “Москва и Московская обл.”,
“city”: “Апрелевка”
},
{
“region”: “Москва и Московская обл.”,
“city”: “Архангельское”
},
{
“region”: “Москва и Московская обл.”,
“city”: “Ашитково”
Сейчас у меня поиск организован по совпадению строк location.
Также город, регион должен отображаться в профиле
код:
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
const fuzzball = require(“fuzzball”);
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
/* function normalizeLocationName(userInput) {
//const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true });
const bestMatch = matches.sort((a, b) => b.score - a.score)[0];
return bestMatch.score >= 75 ? bestMatch.choice : userInput;
} */
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query = ‘’, role = ‘’, location = ‘’) {
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
location: musician.location
};
});
let results = [];
if (query || role || location) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
return nameScore + genreScore + locationScore > 0 && (role === ‘’ || musician.role === role) && (location === ‘’ || locationScore >= 75);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.location === result.location
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”);
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = “musician_” + newMusician.id + “" + file.name;
file.mv(“./public/img/” + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync(“./db/musicians.json”, JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect(“/profile/” + newMusician.id);
}
});
app.get(“/profile/:id”, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render(“profile”, { musician: musician });
} else {
res.status(404).send(“Musician not found”);
}
});
app.get(“/login”, (req, res) => {
res.render(“login”);
});
app.post(“/login”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect(“/profile/” + musician.id);
} else {
res.render(“login”, { error: “Invalid login or password” });
}
});
app.get(“/logout”, (req, res) => {
req.session.destroy();
res.redirect(“/”);
});
app.get(‘/search’, (req, res) => {
const query = req.query.query || ‘’;
const role = req.query.role || ‘’;
const location = req.query.location || ‘’; // Add location variable
let musicians = [];
if (query || role || location) {
musicians = search(query, role, location);
} else {
const data = fs.readFileSync(‘./db/musicians.json’);
musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: /profile/${musician.id},
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query, role, location });
//res.redirect(‘/search’);
});
app.get(“/profile/:id/edit”, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render(“edit-profile”, { musician: musician });
} else {
res.status(403).send(“Access denied”);
}
} else {
res.status(404).send(“Musician not found”);
}
});
app.post(‘/profile/:id/edit’, requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send(‘Please fill out all fields’);
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud;
musician.soundcloud1 = req.body.soundcloud1;
musician.soundcloud2 = req.body.soundcloud2;
musician.location = req.body.location;
musician.role = req.body.role;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician’ + musician.id + ‘_’ + file.name;
file.mv(‘./public/img/’ + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync(‘./db/musicians.json’);
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync(‘./db/musicians.json’, JSON.stringify(musicians));
res.redirect(‘/profile/’ + musician.id);
}
} else {
res.status(404).send(‘Musician not found’);
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith(‘https://soundcloud.com/’);
}
app.listen(3000, () => {
console.log(“Server started on port 3000”);
});
register.ejs:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8” />
<meta name=“viewport” content=“width=device-width, initial-scale=1.0” />
<meta http-equiv=“X-UA-Compatible” content=“ie=edge” />
<link rel=“stylesheet” href=”/css/main.css" />
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href=“/”>Home</a></li>
<li><a href=“/register”>Register</a></li>
<li><a href=“/search”>Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method=“post” enctype=“multipart/form-data”>
<label for=“name”>Name</label>
<input type=“text” id=“name” name=“name” required>
<label for=“role”>Role</label>
<select id=“role” name=“role” required onchange=“showInstrument(this.value)”>
<option value=“”>Select a role</option>
<option value=“Band”>A band</option>
<option value=“Artist”>Artist</option>
</select>
<label for=“genre”>Genre</label>
<select id=“genre” name=“genre” required>
<option value=“”>Select a genre</option>
<option value=“Rock”>Rock</option>
<option value=“Pop”>Pop</option>
<option value=“Hip hop”>Hip hop</option>
<option value=“Electronic”>Electronic</option>
</select>
<label for=“instrument” id=“instrument-label” style=“display: none”>Instrument</label>
<select id=“instrument” name=“instrument” style=“display: none”>
<option value=“”>Select a instrument</option>
<option value=“Bass”>Bass</option>
<option value=“Rythm guitar”>Rythm guitar</option>
<option value=“Lead guitar”>Lead guitar</option>
<option value=“Vocal”>Vocal</option>
</select>
<label for=“soundcloud”>SoundCloud URL</label>
<input type=“url” id=“soundcloud” name=“soundcloud”>
<label for=“password”>Password</label>
<input type=“password” id=“password” name=“password” required>
<label for=“location”>Location</label>
<input type=“text” id=“location” name=“location” required>
<label for=“login”>Login</label>
<input type=“text” id=“login” name=“login” required>
<label for=“thumbnail”>Thumbnail</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
<button type=“submit”>Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector(‘#instrument-label’);
const instrumentSelect = document.querySelector(‘#instrument’);
if (role === ‘Artist’) {
instrumentLabel.style.display = ‘block’;
instrumentSelect.style.display = ‘block’;
} else {
instrumentLabel.style.display = ‘none’;
instrumentSelect.style.display = ‘none’;
}
}
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
</head>
<body>
<h1>Search Musicians</h1>
<form action=“/search” method=“get”>
<label for=“query”>Search by name or genre:</label> <input id=“query” name=“query” type=“text” value=“<%= query %>”><br>
<br>
<label for=“role”>Search by role:</label> <select id=“role” name=“role”>
<option value=“”>
All
</option>
<option value=“Band”>
Band
</option>
<option value=“Artist”>
Artist
</option>
</select>
<label for=“location”>Search by location:</label>
<input id=“location” name=“location” type=“text” value=“<%= location %>”>
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type=“submit”>Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href=“<%= musician.profileLink %>”><%= musician.name %> <%if (musician.thumbnail) { %> <img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href=“%3C%=%20musician.soundcloud%20%%3E”>SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<!-- Update the form submission script --> <script> document.querySelector(“form”).addEventListener(“submit”, function (event) { event.preventDefault(); const query = document.querySelector(“#query”).value; const role = document.querySelector(“#role”).value; const location = document.querySelector(“#location”).value; const url = “/search?query=” + encodeURIComponent(query) + “&role=” + encodeURIComponent(role) + “&location=” + encodeURIComponent(location); window.location.href = url; }); </script>
</body>
</html>
|
571e33b65eb1a361d9c4071a55239fb5
|
{
"intermediate": 0.2796950340270996,
"beginner": 0.4907204210758209,
"expert": 0.22958454489707947
}
|
11,028
|
huggingface accelerate supported "engine" input
|
d7ac5216d147ef5eb21535432eb3fb45
|
{
"intermediate": 0.2790582776069641,
"beginner": 0.24903428554534912,
"expert": 0.47190746665000916
}
|
11,029
|
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
/* function normalizeLocationName(userInput) {
//const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true });
const bestMatch = matches.sort((a, b) => b.score - a.score)[0];
return bestMatch.score >= 75 ? bestMatch.choice : userInput;
} */
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json"));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query = '', role = '', location = '', 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,
location: musician.location
};
});
let results = [];
if (query || role || location) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === "" || musician.role === role) &&
(location === "" || locationScore >= 75) &&
(city === "" || cityMatch)
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.location === result.location
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register", { citiesAndRegions });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
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.toLowerCase() === req.body.location.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.location;
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 location = req.query.location || ''; // Add location variable
const city = req.query.city || '';
let musicians = [];
if (query || role || location) {
musicians = search(query, role, location, 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,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role, location, 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");
});
register.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/jquery-ui-dist/jquery-ui.min.js"></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/register">Register</a></li>
<li><a href="/search">Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method="post" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="role">Role</label>
<select id="role" name="role" required onchange="showInstrument(this.value)">
<option value="">Select a role</option>
<option value="Band">A band</option>
<option value="Artist">Artist</option>
</select>
<label for="genre">Genre</label>
<select id="genre" name="genre" required>
<option value="">Select a genre</option>
<option value="Rock">Rock</option>
<option value="Pop">Pop</option>
<option value="Hip hop">Hip hop</option>
<option value="Electronic">Electronic</option>
</select>
<label for="instrument" id="instrument-label" style="display: none">Instrument</label>
<select id="instrument" name="instrument" style="display: none">
<option value="">Select a instrument</option>
<option value="Bass">Bass</option>
<option value="Rythm guitar">Rythm guitar</option>
<option value="Lead guitar">Lead guitar</option>
<option value="Vocal">Vocal</option>
</select>
<label for="soundcloud">SoundCloud URL</label>
<input type="url" id="soundcloud" name="soundcloud">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<label for="city">City:</label>
<input id="city" name="city" type="text" value="<%= city %>"><br />
<label for="login">Login</label>
<input type="text" id="login" name="login" required>
<label for="thumbnail">Thumbnail</label>
<input type="file" id="thumbnail" name="thumbnail">
<button type="submit">Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector('#instrument-label');
const instrumentSelect = document.querySelector('#instrument');
if (role === 'Artist') {
instrumentLabel.style.display = 'block';
instrumentSelect.style.display = 'block';
} else {
instrumentLabel.style.display = 'none';
instrumentSelect.style.display = 'none';
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#location").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/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="location">Search by location:</label>
<input id="location" name="location" type="text" value="<%= location %>">
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type="submit">Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#location").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector("#city").value;
const url =
"/search?query=" +
encodeURIComponent(query) +
"&role=" +
encodeURIComponent(role) +
"&location=" +
encodeURIComponent(location) +
"&city=" +
encodeURIComponent(city);
</script>
</body>
</html>
ошибка:
ReferenceError: C:\Users\Ilya\Downloads\my-musician-network\views\register.ejs:63
61|
62| <label for="city">City:</label>
>> 63| <input id="city" name="city" type="text" value="<%= city %>"><br />
64|
65| <label for="login">Login</label>
66| <input type="text" id="login" name="login" required>
city is not defined
|
58eb3d2dd1cdda24526eae2a0f2acb43
|
{
"intermediate": 0.38004210591316223,
"beginner": 0.48643192648887634,
"expert": 0.13352595269680023
}
|
11,030
|
android studio Compiler error com.android.tools.r8.errors.a
|
87812d78ba3faab17ca561db2f2b2fe7
|
{
"intermediate": 0.42966634035110474,
"beginner": 0.2661404311656952,
"expert": 0.30419325828552246
}
|
11,031
|
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
const fuzzball = require(“fuzzball”);
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
/* function normalizeLocationName(userInput) {
//const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true });
const bestMatch = matches.sort((a, b) => b.score - a.score)[0];
return bestMatch.score >= 75 ? bestMatch.choice : userInput;
} */
const citiesAndRegions = JSON.parse(fs.readFileSync(“./db/russia.json”));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query = ‘’, role = ‘’, location = ‘’, 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,
location: musician.location
};
});
let results = [];
if (query || role || location) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === “” || musician.role === role) &&
(location === “” || locationScore >= 75) &&
(city === “” || cityMatch)
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.location === result.location
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”, { citiesAndRegions });
}
});
app.post(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
role: req.body.role,
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.toLowerCase() === req.body.location.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.location;
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 location = req.query.location || ‘’; // Add location variable
const city = req.query.city || ‘’;
let musicians = [];
if (query || role || location) {
musicians = search(query, role, location, 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,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query, role, location, 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”);
});
register.ejs:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8” />
<meta name=“viewport” content=“width=device-width, initial-scale=1.0” />
<meta http-equiv=“X-UA-Compatible” content=“ie=edge” />
<link rel=“stylesheet” href=”/css/main.css" />
<link rel=“stylesheet” href=“/node_modules/jquery-ui/themes/base/all.css” />
<script src=“/node_modules/jquery/dist/jquery.min.js”></script>
<script src=“/node_modules/jquery-ui-dist/jquery-ui.min.js”></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href=“/”>Home</a></li>
<li><a href=“/register”>Register</a></li>
<li><a href=“/search”>Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method=“post” enctype=“multipart/form-data”>
<label for=“name”>Name</label>
<input type=“text” id=“name” name=“name” required>
<label for=“role”>Role</label>
<select id=“role” name=“role” required onchange=“showInstrument(this.value)”>
<option value=“”>Select a role</option>
<option value=“Band”>A band</option>
<option value=“Artist”>Artist</option>
</select>
<label for=“genre”>Genre</label>
<select id=“genre” name=“genre” required>
<option value=“”>Select a genre</option>
<option value=“Rock”>Rock</option>
<option value=“Pop”>Pop</option>
<option value=“Hip hop”>Hip hop</option>
<option value=“Electronic”>Electronic</option>
</select>
<label for=“instrument” id=“instrument-label” style=“display: none”>Instrument</label>
<select id=“instrument” name=“instrument” style=“display: none”>
<option value=“”>Select a instrument</option>
<option value=“Bass”>Bass</option>
<option value=“Rythm guitar”>Rythm guitar</option>
<option value=“Lead guitar”>Lead guitar</option>
<option value=“Vocal”>Vocal</option>
</select>
<label for=“soundcloud”>SoundCloud URL</label>
<input type=“url” id=“soundcloud” name=“soundcloud”>
<label for=“password”>Password</label>
<input type=“password” id=“password” name=“password” required>
<label for=“city”>City:</label>
<input id=“city” name=“city” type=“text” value=“<%= city %>”><br />
<label for=“login”>Login</label>
<input type=“text” id=“login” name=“login” required>
<label for=“thumbnail”>Thumbnail</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
<button type=“submit”>Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector(‘#instrument-label’);
const instrumentSelect = document.querySelector(‘#instrument’);
if (role === ‘Artist’) {
instrumentLabel.style.display = ‘block’;
instrumentSelect.style.display = ‘block’;
} else {
instrumentLabel.style.display = ‘none’;
instrumentSelect.style.display = ‘none’;
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
(“#location”).autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel=“stylesheet” href=“/node_modules/jquery-ui/themes/base/all.css” />
<script src=“/node_modules/jquery/dist/jquery.min.js”></script>
<script src=“/node_modules/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=“location”>Search by location:</label>
<input id=“location” name=“location” type=“text” value=“<%= location %>”>
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type=“submit”>Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href=“<%= musician.profileLink %>”><%= musician.name %> <%if (musician.thumbnail) { %> <img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href=“%3C%=%20musician.soundcloud%20%%3E”>SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
(“#location”).autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector(“#city”).value;
const url =
“/search?query=” +
encodeURIComponent(query) +
“&role=” +
encodeURIComponent(role) +
“&location=” +
encodeURIComponent(location) +
“&city=” +
encodeURIComponent(city);
</script>
</body>
</html>
ошибка:
ReferenceError: C:\Users\Ilya\Downloads\my-musician-network\views\register.ejs:63
61|
62| <label for=“city”>City:</label>
>> 63| <input id=“city” name=“city” type=“text” value=“<%= city %>”><br />
64|
65| <label for=“login”>Login</label>
66| <input type=“text” id=“login” name=“login” required>
city is not defined
|
7d04ef952ed3de45758b37ea76d5d0b5
|
{
"intermediate": 0.35412296652793884,
"beginner": 0.47858431935310364,
"expert": 0.16729266941547394
}
|
11,032
|
I am trying to run main.py, the code is from somewhere else. But when i ran it the following error occured:
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "/Users/rui/PycharmProjects/pythonProject2/main.py", line 5, in <module>
from StrategyGame import *
ModuleNotFoundError: No module named 'StrategyGame'
|
4dd861fcb8a013ba706ffe6cbc4943ee
|
{
"intermediate": 0.652073323726654,
"beginner": 0.19310703873634338,
"expert": 0.15481960773468018
}
|
11,033
|
i have wifi connection and ethernet connection. i wanna use 2 different python script with selenium using 2 different connections. How do i do this?
|
cca5ce54a038b205bb4771164b30d2ce
|
{
"intermediate": 0.43017062544822693,
"beginner": 0.21656163036823273,
"expert": 0.35326775908470154
}
|
11,034
|
почему поиск по городам/регионам, подсказки (автозаполнение при вводе города) при выборе города при регистрации не работают? так же я получаю ошибку TypeError: Cannot read properties of undefined (reading 'toLowerCase')
at C:\Users\Ilya\Downloads\my-musician-network\app.js:169:44
так же надо убрать location, наверное, так как теперь мы используем city
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
/* function normalizeLocationName(userInput) {
//const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true });
const bestMatch = matches.sort((a, b) => b.score - a.score)[0];
return bestMatch.score >= 75 ? bestMatch.choice : userInput;
} */
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json"));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query = '', role = '', location = '', 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,
location: musician.location
};
});
let results = [];
if (query || role || location) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === "" || musician.role === role) &&
(location === "" || locationScore >= 75) &&
(city === "" || cityMatch)
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.location === result.location
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register", { 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,
location: req.body.location,
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.location.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.location;
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 location = req.query.location || ''; // Add location variable
const city = req.query.city || '';
let musicians = [];
if (query || role || location || city) {
musicians = search(query, role, location, 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,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role, location, 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");
});
register.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/jquery-ui-dist/jquery-ui.min.js"></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/register">Register</a></li>
<li><a href="/search">Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method="post" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="role">Role</label>
<select id="role" name="role" required onchange="showInstrument(this.value)">
<option value="">Select a role</option>
<option value="Band">A band</option>
<option value="Artist">Artist</option>
</select>
<label for="genre">Genre</label>
<select id="genre" name="genre" required>
<option value="">Select a genre</option>
<option value="Rock">Rock</option>
<option value="Pop">Pop</option>
<option value="Hip hop">Hip hop</option>
<option value="Electronic">Electronic</option>
</select>
<label for="instrument" id="instrument-label" style="display: none">Instrument</label>
<select id="instrument" name="instrument" style="display: none">
<option value="">Select a instrument</option>
<option value="Bass">Bass</option>
<option value="Rythm guitar">Rythm guitar</option>
<option value="Lead guitar">Lead guitar</option>
<option value="Vocal">Vocal</option>
</select>
<label for="soundcloud">SoundCloud URL</label>
<input type="url" id="soundcloud" name="soundcloud">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<label for="city">City:</label>
<input id="city" name="city" type="text" value="<%= citiesAndRegions[0].city %>"><br />
<label for="login">Login</label>
<input type="text" id="login" name="login" required>
<label for="thumbnail">Thumbnail</label>
<input type="file" id="thumbnail" name="thumbnail">
<button type="submit">Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector('#instrument-label');
const instrumentSelect = document.querySelector('#instrument');
if (role === 'Artist') {
instrumentLabel.style.display = 'block';
instrumentSelect.style.display = 'block';
} else {
instrumentLabel.style.display = 'none';
instrumentSelect.style.display = 'none';
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#location").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/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="location">Search by location:</label>
<input id="location" name="location" type="text" value="<%= location %>">
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type="submit">Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href="<%= musician.profileLink %>"><%= musician.name %> <%if (musician.thumbnail) { %> <img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>"> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href="%3C%=%20musician.soundcloud%20%%3E">SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#location").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector("#city").value;
const url =
"/search?query=" +
encodeURIComponent(query) +
"&role=" +
encodeURIComponent(role) +
"&location=" +
encodeURIComponent(location) +
"&city=" +
encodeURIComponent(city);
</script>
</body>
</html>
|
4dfe921908a824b01f8c7f071adcaea6
|
{
"intermediate": 0.41555073857307434,
"beginner": 0.5000918507575989,
"expert": 0.08435744047164917
}
|
11,035
|
почему поиск по городам/регионам, подсказки (автозаполнение при вводе города) при выборе города при регистрации не работают? так же я получаю ошибку TypeError: Cannot read properties of undefined (reading ‘toLowerCase’)
at C:\Users\Ilya\Downloads\my-musician-network\app.js:169:44
так же надо убрать location, наверное, так как теперь мы используем city
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
const fuzzball = require(“fuzzball”);
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
/* function normalizeLocationName(userInput) {
//const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true });
const bestMatch = matches.sort((a, b) => b.score - a.score)[0];
return bestMatch.score >= 75 ? bestMatch.choice : userInput;
} */
const citiesAndRegions = JSON.parse(fs.readFileSync(“./db/russia.json”));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query = ‘’, role = ‘’, location = ‘’, 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,
location: musician.location
};
});
let results = [];
if (query || role || location) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === “” || musician.role === role) &&
(location === “” || locationScore >= 75) &&
(city === “” || cityMatch)
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.location === result.location
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”, { 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,
location: req.body.location,
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.location.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.location;
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 location = req.query.location || ‘’; // Add location variable
const city = req.query.city || ‘’;
let musicians = [];
if (query || role || location || city) {
musicians = search(query, role, location, 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,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query, role, location, 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”);
});
register.ejs:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8” />
<meta name=“viewport” content=“width=device-width, initial-scale=1.0” />
<meta http-equiv=“X-UA-Compatible” content=“ie=edge” />
<link rel=“stylesheet” href=”/css/main.css" />
<link rel=“stylesheet” href=“/node_modules/jquery-ui/themes/base/all.css” />
<script src=“/node_modules/jquery/dist/jquery.min.js”></script>
<script src=“/node_modules/jquery-ui-dist/jquery-ui.min.js”></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href=“/”>Home</a></li>
<li><a href=“/register”>Register</a></li>
<li><a href=“/search”>Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method=“post” enctype=“multipart/form-data”>
<label for=“name”>Name</label>
<input type=“text” id=“name” name=“name” required>
<label for=“role”>Role</label>
<select id=“role” name=“role” required onchange=“showInstrument(this.value)”>
<option value=“”>Select a role</option>
<option value=“Band”>A band</option>
<option value=“Artist”>Artist</option>
</select>
<label for=“genre”>Genre</label>
<select id=“genre” name=“genre” required>
<option value=“”>Select a genre</option>
<option value=“Rock”>Rock</option>
<option value=“Pop”>Pop</option>
<option value=“Hip hop”>Hip hop</option>
<option value=“Electronic”>Electronic</option>
</select>
<label for=“instrument” id=“instrument-label” style=“display: none”>Instrument</label>
<select id=“instrument” name=“instrument” style=“display: none”>
<option value=“”>Select a instrument</option>
<option value=“Bass”>Bass</option>
<option value=“Rythm guitar”>Rythm guitar</option>
<option value=“Lead guitar”>Lead guitar</option>
<option value=“Vocal”>Vocal</option>
</select>
<label for=“soundcloud”>SoundCloud URL</label>
<input type=“url” id=“soundcloud” name=“soundcloud”>
<label for=“password”>Password</label>
<input type=“password” id=“password” name=“password” required>
<label for=“city”>City:</label>
<input id=“city” name=“city” type=“text” value=“<%= citiesAndRegions[0].city %>”><br />
<label for=“login”>Login</label>
<input type=“text” id=“login” name=“login” required>
<label for=“thumbnail”>Thumbnail</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
<button type=“submit”>Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector(‘#instrument-label’);
const instrumentSelect = document.querySelector(‘#instrument’);
if (role === ‘Artist’) {
instrumentLabel.style.display = ‘block’;
instrumentSelect.style.display = ‘block’;
} else {
instrumentLabel.style.display = ‘none’;
instrumentSelect.style.display = ‘none’;
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
(“#location”).autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel=“stylesheet” href=“/node_modules/jquery-ui/themes/base/all.css” />
<script src=“/node_modules/jquery/dist/jquery.min.js”></script>
<script src=“/node_modules/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=“location”>Search by location:</label>
<input id=“location” name=“location” type=“text” value=“<%= location %>”>
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type=“submit”>Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href=“<%= musician.profileLink %>”><%= musician.name %> <%if (musician.thumbnail) { %> <img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href=“%3C%=%20musician.soundcloud%20%%3E”>SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
(“#location”).autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector(“#city”).value;
const url =
“/search?query=” +
encodeURIComponent(query) +
“&role=” +
encodeURIComponent(role) +
“&location=” +
encodeURIComponent(location) +
“&city=” +
encodeURIComponent(city);
</script>
</body>
</html>
|
988d19c294afa484f4ac7b971096b7db
|
{
"intermediate": 0.46896427869796753,
"beginner": 0.4255736470222473,
"expert": 0.10546208173036575
}
|
11,036
|
почему поиск по городам/регионам, подсказки (автозаполнение при вводе города) при выборе города при регистрации не работают? так же я получаю ошибку TypeError: Cannot read properties of undefined (reading ‘toLowerCase’)
at C:\Users\Ilya\Downloads\my-musician-network\app.js:169:44
сделай так, чтобы поиск начал работать, дай мне инструкции
так же надо убрать location, наверное, так как теперь мы используем city
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
const fuzzball = require(“fuzzball”);
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
/* function normalizeLocationName(userInput) {
//const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true });
const bestMatch = matches.sort((a, b) => b.score - a.score)[0];
return bestMatch.score >= 75 ? bestMatch.choice : userInput;
} */
const citiesAndRegions = JSON.parse(fs.readFileSync(“./db/russia.json”));
const predefinedGenres = [‘Rock’, ‘Pop’, ‘Jazz’, ‘Hip Hop’, ‘Electronic’, ‘Blues’];
function getMusicianById(id) {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect(“/login”);
}
}
function search(query = ‘’, role = ‘’, location = ‘’, 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,
location: musician.location
};
});
let results = [];
if (query || role || location) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === “” || musician.role === role) &&
(location === “” || locationScore >= 75) &&
(city === “” || cityMatch)
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.location === result.location
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”, { 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,
location: req.body.location,
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.location.toLowerCase()
);
// Если найдено - сохраняем город и регион, если нет - оставляем только город
if (found) {
newMusician.city = found.city;
newMusician.region = found.region;
} else {
newMusician.city = req.body.location;
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 location = req.query.location || ‘’; // Add location variable
const city = req.query.city || ‘’;
let musicians = [];
if (query || role || location || city) {
musicians = search(query, role, location, 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,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query, role, location, 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”);
});
register.ejs:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8” />
<meta name=“viewport” content=“width=device-width, initial-scale=1.0” />
<meta http-equiv=“X-UA-Compatible” content=“ie=edge” />
<link rel=“stylesheet” href=”/css/main.css" />
<link rel=“stylesheet” href=“/node_modules/jquery-ui/themes/base/all.css” />
<script src=“/node_modules/jquery/dist/jquery.min.js”></script>
<script src=“/node_modules/jquery-ui-dist/jquery-ui.min.js”></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href=“/”>Home</a></li>
<li><a href=“/register”>Register</a></li>
<li><a href=“/search”>Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method=“post” enctype=“multipart/form-data”>
<label for=“name”>Name</label>
<input type=“text” id=“name” name=“name” required>
<label for=“role”>Role</label>
<select id=“role” name=“role” required onchange=“showInstrument(this.value)”>
<option value=“”>Select a role</option>
<option value=“Band”>A band</option>
<option value=“Artist”>Artist</option>
</select>
<label for=“genre”>Genre</label>
<select id=“genre” name=“genre” required>
<option value=“”>Select a genre</option>
<option value=“Rock”>Rock</option>
<option value=“Pop”>Pop</option>
<option value=“Hip hop”>Hip hop</option>
<option value=“Electronic”>Electronic</option>
</select>
<label for=“instrument” id=“instrument-label” style=“display: none”>Instrument</label>
<select id=“instrument” name=“instrument” style=“display: none”>
<option value=“”>Select a instrument</option>
<option value=“Bass”>Bass</option>
<option value=“Rythm guitar”>Rythm guitar</option>
<option value=“Lead guitar”>Lead guitar</option>
<option value=“Vocal”>Vocal</option>
</select>
<label for=“soundcloud”>SoundCloud URL</label>
<input type=“url” id=“soundcloud” name=“soundcloud”>
<label for=“password”>Password</label>
<input type=“password” id=“password” name=“password” required>
<label for=“city”>City:</label>
<input id=“city” name=“city” type=“text” value=“<%= citiesAndRegions[0].city %>”><br />
<label for=“login”>Login</label>
<input type=“text” id=“login” name=“login” required>
<label for=“thumbnail”>Thumbnail</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
<button type=“submit”>Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector(‘#instrument-label’);
const instrumentSelect = document.querySelector(‘#instrument’);
if (role === ‘Artist’) {
instrumentLabel.style.display = ‘block’;
instrumentSelect.style.display = ‘block’;
} else {
instrumentLabel.style.display = ‘none’;
instrumentSelect.style.display = ‘none’;
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
(“#location”).autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel=“stylesheet” href=“/node_modules/jquery-ui/themes/base/all.css” />
<script src=“/node_modules/jquery/dist/jquery.min.js”></script>
<script src=“/node_modules/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=“location”>Search by location:</label>
<input id=“location” name=“location” type=“text” value=“<%= location %>”>
<br>
<!-- Add new input field for location -->
<br>
<br>
<button type=“submit”>Search</button>
</form><%if (musicians.length > 0) { %>
<h2>Results:</h2>
<ul>
<%musicians.forEach(musician => { %>
<li>
<a href=“<%= musician.profileLink %>”><%= musician.name %> <%if (musician.thumbnail) { %> <img src=“/img/<%= musician.thumbnail %>” alt=“<%= musician.name %>”> <%} %></a> - <%= musician.genre %> - <%= musician.location %> <%if (musician.soundcloud) { %> <a href=“%3C%=%20musician.soundcloud%20%%3E”>SoundCloud</a> <%} %>
</li><%}); %>
</ul><%} else if (query || role) { %>
<p>No musicians found.</p><%} %>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
(“#location”).autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector(“#city”).value;
const url =
“/search?query=” +
encodeURIComponent(query) +
“&role=” +
encodeURIComponent(role) +
“&location=” +
encodeURIComponent(location) +
“&city=” +
encodeURIComponent(city);
</script>
</body>
</html>
|
d06499693e594518da367dfdf5367f75
|
{
"intermediate": 0.41734445095062256,
"beginner": 0.46455883979797363,
"expert": 0.1180967167019844
}
|
11,037
|
поиск по городам не работает, подсказки по городу не работают, город при регистрации, в коде много ошибок. Найди все и исправь, вот код:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
/* function normalizeLocationName(userInput) {
//const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true });
const bestMatch = matches.sort((a, b) => b.score - a.score)[0];
return bestMatch.score >= 75 ? bestMatch.choice : userInput;
} */
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json"));
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,
location: musician.location
};
});
let results = [];
if (query || role || location) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city && musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === "" || musician.role === role) &&
(location === "" || locationScore >= 75) &&
(city === "" || cityMatch)
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.location === result.location
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register", { 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,
location: req.body.location,
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.location;
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,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role, 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");
});
register.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/jquery-ui-dist/jquery-ui.min.js"></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/register">Register</a></li>
<li><a href="/search">Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method="post" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="role">Role</label>
<select id="role" name="role" required onchange="showInstrument(this.value)">
<option value="">Select a role</option>
<option value="Band">A band</option>
<option value="Artist">Artist</option>
</select>
<label for="genre">Genre</label>
<select id="genre" name="genre" required>
<option value="">Select a genre</option>
<option value="Rock">Rock</option>
<option value="Pop">Pop</option>
<option value="Hip hop">Hip hop</option>
<option value="Electronic">Electronic</option>
</select>
<label for="instrument" id="instrument-label" style="display: none">Instrument</label>
<select id="instrument" name="instrument" style="display: none">
<option value="">Select a instrument</option>
<option value="Bass">Bass</option>
<option value="Rythm guitar">Rythm guitar</option>
<option value="Lead guitar">Lead guitar</option>
<option value="Vocal">Vocal</option>
</select>
<label for="soundcloud">SoundCloud URL</label>
<input type="url" id="soundcloud" name="soundcloud">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<label for="city">City:</label>
<input id="city" name="city" type="text" value="<%= citiesAndRegions[0].city %>"><br />
<label for="login">Login</label>
<input type="text" id="login" name="login" required>
<label for="thumbnail">Thumbnail</label>
<input type="file" id="thumbnail" name="thumbnail">
<button type="submit">Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector('#instrument-label');
const instrumentSelect = document.querySelector('#instrument');
if (role === 'Artist') {
instrumentLabel.style.display = 'block';
instrumentSelect.style.display = 'block';
} else {
instrumentLabel.style.display = 'none';
instrumentSelect.style.display = 'none';
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#city").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/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" value="<%= musician.city %>">
<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>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#location").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector("#city").value;
const url =
"/search?query=" +
encodeURIComponent(query) +
"&role=" +
encodeURIComponent(role) +
"&location=" +
encodeURIComponent(location) +
"&city=" +
encodeURIComponent(city);
</script>
</body>
</html>
все пользовательские данные сохраняются в musicians.json:
{"musicians":[{"id":1,"name":"sukaAAAAAAA","genre":"BluesZ","instrument":"Guitar","soundcloud":"http://soundcloud.com/dasdasdasd","password":"password123","location":"New York","login":"suka","bio":""},{"id":2,"name":"Aerosmith111114446","genre":"Blues","password":"1111","location":"EnglandDdDDDDDDD","thumbnail":"musician_2_jX7hQvfoT2g (2).jpg","instrument":"","bio":"","soundcloud":"https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing","soundcloud1":"https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing"},{"id":3,"name":"Britpop","genre":"Pop","instrument":"bass","soundcloud":"http://google.com","password":"1111","location":"Sahara","login":"SS1VCSS@gmail.com","thumbnail":"musician_3_photo_2023-02-27_01-16-44.jpg"},{"id":4,"name":"Bobq","genre":"Hip hop","instrument":"keys","soundcloud":"http://cloudnine.ru","password":"1111","location":"Dallas","login":"SSSS1VYTFFSDDD@gmail.com","thumbnail":"musician_4_1mxwr7Ravu4.jpg"},{"id":5,"name":"LOL","genre":"Rock","instrument":"Bass","soundcloud":"https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing","password":"1111","location":"Manchester","role":"Artist","login":"111111111@gmail.com","thumbnail":"musician_5_photo_2023-02-27_01-16-43 (2).jpg"},{"id":6,"name":"pizda","genre":"Rock","instrument":"Bass","soundcloud":"","password":"1111","location":"Berlin","role":"Artist","login":"SSDSDSDSDS@gmail.com"},{"id":7,"name":"pizda2","genre":"Pop","instrument":"","soundcloud":"","password":"1111","location":"England","role":"Band","login":"sssssss22222@gmail.com"},{"id":8,"name":"Bandband","genre":"Rock","instrument":"","soundcloud":"","password":"1111","location":"Oklahoma","role":"Band","login":"DSDSDSDSDSDS@gmail.com"},{"id":9,"name":"Bandbandband","genre":"Pop","instrument":"","soundcloud":"","password":"1111","location":"London","role":"Band","login":"SVRSFSDFSD@gmail.com"},{"id":10,"name":"JOHN","genre":"Rock","instrument":"","soundcloud":"","password":"1111","location":"Москва","role":"Band","login":"jskjd4sssss@gmail.com"},{"id":11,"name":"GOVNO","genre":"Rock","instrument":"","soundcloud":"","password":"1111","location":"New York","role":"Band","login":"SJDJSDSSSS@gmail.com","soundcloud1":"","bio":""},{"id":12,"name":"bubba","genre":"Rock","instrument":"","soundcloud":"","password":"1111","location":"Москва","role":"Band","login":"dasdasdasdas@gmail.com"},{"id":13,"name":"SDSDSSDSDSDS","genre":"Rock","instrument":"","soundcloud":"","password":"1111","role":"Band","login":"dasdasdasSSSSSSSSSSSS@gmail.com","region":""}]}
|
fe114bdad8f09399239f64fb53a246a7
|
{
"intermediate": 0.3498185873031616,
"beginner": 0.4828720986843109,
"expert": 0.1673092097043991
}
|
11,038
|
поиск по городам из json файла не работает, подсказки по городу не работают, город при регистрации в register.ejs там тоже ошибки, в коде много ошибок. в musicians.json сохраняется "region":"", а не city. location и все что с этим связано мы теперь не используем, вместо этого используем city. Найди все и исправь, вот код:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
/* function normalizeLocationName(userInput) {
//const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true });
const bestMatch = matches.sort((a, b) => b.score - a.score)[0];
return bestMatch.score >= 75 ? bestMatch.choice : userInput;
} */
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json"));
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,
location: musician.location
};
});
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;
const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city && musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === "" || musician.role === role) &&
(location === "" || locationScore >= 75) &&
(city === "" || cityMatch)
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.location === result.location
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register", { 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,
location: req.body.location,
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.location;
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,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role, 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");
});
register.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/jquery-ui-dist/jquery-ui.min.js"></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/register">Register</a></li>
<li><a href="/search">Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method="post" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="role">Role</label>
<select id="role" name="role" required onchange="showInstrument(this.value)">
<option value="">Select a role</option>
<option value="Band">A band</option>
<option value="Artist">Artist</option>
</select>
<label for="genre">Genre</label>
<select id="genre" name="genre" required>
<option value="">Select a genre</option>
<option value="Rock">Rock</option>
<option value="Pop">Pop</option>
<option value="Hip hop">Hip hop</option>
<option value="Electronic">Electronic</option>
</select>
<label for="instrument" id="instrument-label" style="display: none">Instrument</label>
<select id="instrument" name="instrument" style="display: none">
<option value="">Select a instrument</option>
<option value="Bass">Bass</option>
<option value="Rythm guitar">Rythm guitar</option>
<option value="Lead guitar">Lead guitar</option>
<option value="Vocal">Vocal</option>
</select>
<label for="soundcloud">SoundCloud URL</label>
<input type="url" id="soundcloud" name="soundcloud">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<label for="city">City:</label>
<input id="city" name="city" type="text" value="<%= citiesAndRegions[0].city %>"><br />
<label for="login">Login</label>
<input type="text" id="login" name="login" required>
<label for="thumbnail">Thumbnail</label>
<input type="file" id="thumbnail" name="thumbnail">
<button type="submit">Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector('#instrument-label');
const instrumentSelect = document.querySelector('#instrument');
if (role === 'Artist') {
instrumentLabel.style.display = 'block';
instrumentSelect.style.display = 'block';
} else {
instrumentLabel.style.display = 'none';
instrumentSelect.style.display = 'none';
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#city").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/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" value="<%= musician.city %>">
<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>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#location").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector("#city").value;
const url =
"/search?query=" +
encodeURIComponent(query) +
"&role=" +
encodeURIComponent(role) +
"&location=" +
encodeURIComponent(location) +
"&city=" +
encodeURIComponent(city);
</script>
</body>
</html>
musicians.json:
{"musicians":[{"id":1,"name":"sukaAAAAAAA","genre":"BluesZ","instrument":"Guitar","soundcloud":"http://soundcloud.com/dasdasdasd","password":"password123","location":"New York","login":"suka","bio":"","region":""},
russia.json (где хранятся города) выглядит так:
[
{
"region": "Москва и Московская обл.",
"city": "Москва"
},
{
"region": "Москва и Московская обл.",
"city": "Абрамцево"
},
|
a9df0618581fcff0b06e797ec027615f
|
{
"intermediate": 0.4840504825115204,
"beginner": 0.3937095105648041,
"expert": 0.12223994731903076
}
|
11,039
|
поиск по городам из json файла не работает, подсказки по городу не работают, город при регистрации в register.ejs регистрируется пустой region вместо city, в коде много ошибок. в musicians.json сохраняется “region”:“”, а не city. location и все что с этим связано мы теперь не используем, вместо этого используем city.
app.js:
const express = require(“express”);
const fs = require(“fs”);
const session = require(“express-session”);
const fileUpload = require(“express-fileupload”);
const app = express();
const fuzzball = require(“fuzzball”);
app.set(“view engine”, “ejs”);
app.use(express.static(“public”));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: “mysecretkey”,
resave: false,
saveUninitialized: false
}));
/* function normalizeLocationName(userInput) {
//const matches = fuzzball.extract(userInput, locationNames, { scorer: fuzzball.token_set_ratio, returnObjects: true });
const bestMatch = matches.sort((a, b) => b.score - a.score)[0];
return bestMatch.score >= 75 ? bestMatch.choice : userInput;
} */
const citiesAndRegions = JSON.parse(fs.readFileSync(“./db/russia.json”));
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,
location: musician.location
};
});
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;
const locationScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city && musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === “” || musician.role === role) &&
(location === “” || locationScore >= 75) &&
(city === “” || cityMatch)
);
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
// Sort by name score, then genre score, then location score (descending)
if (aNameScore + aGenreScore + a.location < bNameScore + bGenreScore + b.location) {
return 1;
} else if (aNameScore + aGenreScore + a.location > bNameScore + bGenreScore + b.location) {
return -1;
} else {
return 0;
}
});
// Remove duplicates
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.location === result.location
))
);
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get(“/”, (req, res) => {
const data = fs.readFileSync(“./db/musicians.json”);
const musicians = JSON.parse(data);
res.render(“index”, { musicians: musicians.musicians });
});
app.get(“/register”, (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect(“/profile/” + musician.id);
} else {
res.render(“register”, { 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,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render(‘search’, { musicians, query, role, 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”);
});
register.ejs:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8” />
<meta name=“viewport” content=“width=device-width, initial-scale=1.0” />
<meta http-equiv=“X-UA-Compatible” content=“ie=edge” />
<link rel=“stylesheet” href=”/css/main.css" />
<link rel=“stylesheet” href=“/node_modules/jquery-ui/themes/base/all.css” />
<script src=“/node_modules/jquery/dist/jquery.min.js”></script>
<script src=“/node_modules/jquery-ui-dist/jquery-ui.min.js”></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href=“/”>Home</a></li>
<li><a href=“/register”>Register</a></li>
<li><a href=“/search”>Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method=“post” enctype=“multipart/form-data”>
<label for=“name”>Name</label>
<input type=“text” id=“name” name=“name” required>
<label for=“role”>Role</label>
<select id=“role” name=“role” required onchange=“showInstrument(this.value)”>
<option value=“”>Select a role</option>
<option value=“Band”>A band</option>
<option value=“Artist”>Artist</option>
</select>
<label for=“genre”>Genre</label>
<select id=“genre” name=“genre” required>
<option value=“”>Select a genre</option>
<option value=“Rock”>Rock</option>
<option value=“Pop”>Pop</option>
<option value=“Hip hop”>Hip hop</option>
<option value=“Electronic”>Electronic</option>
</select>
<label for=“instrument” id=“instrument-label” style=“display: none”>Instrument</label>
<select id=“instrument” name=“instrument” style=“display: none”>
<option value=“”>Select a instrument</option>
<option value=“Bass”>Bass</option>
<option value=“Rythm guitar”>Rythm guitar</option>
<option value=“Lead guitar”>Lead guitar</option>
<option value=“Vocal”>Vocal</option>
</select>
<label for=“soundcloud”>SoundCloud URL</label>
<input type=“url” id=“soundcloud” name=“soundcloud”>
<label for=“password”>Password</label>
<input type=“password” id=“password” name=“password” required>
<label for=“city”>City:</label>
<input id=“city” name=“city” type=“text” value=“<%= citiesAndRegions[0].city %>”><br />
<label for=“login”>Login</label>
<input type=“text” id=“login” name=“login” required>
<label for=“thumbnail”>Thumbnail</label>
<input type=“file” id=“thumbnail” name=“thumbnail”>
<button type=“submit”>Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector(‘#instrument-label’);
const instrumentSelect = document.querySelector(‘#instrument’);
if (role === ‘Artist’) {
instrumentLabel.style.display = ‘block’;
instrumentSelect.style.display = ‘block’;
} else {
instrumentLabel.style.display = ‘none’;
instrumentSelect.style.display = ‘none’;
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
(“#city”).autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel=“stylesheet” href=“/node_modules/jquery-ui/themes/base/all.css” />
<script src=“/node_modules/jquery/dist/jquery.min.js”></script>
<script src=“/node_modules/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” value=“<%= musician.city %>”>
<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>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
(“#location”).autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector(“#city”).value;
const url =
“/search?query=” +
encodeURIComponent(query) +
“&role=” +
encodeURIComponent(role) +
“&location=” +
encodeURIComponent(location) +
“&city=” +
encodeURIComponent(city);
</script>
</body>
</html>
musicians.json:
{“musicians”:[{“id”:1,“name”:“sukaAAAAAAA”,“genre”:“BluesZ”,“instrument”:“Guitar”,“soundcloud”:“http://soundcloud.com/dasdasdasd",“password”:“password123”,“location”:"New York”,“login”:“suka”,“bio”:“”,“region”:“”},
russia.json (где хранятся города) выглядит так:
[
{
“region”: “Москва и Московская обл.”,
“city”: “Москва”
},
{
“region”: “Москва и Московская обл.”,
“city”: “Абрамцево”
},
|
219ee52a1a83efcbd373510d057d8ca9
|
{
"intermediate": 0.46296191215515137,
"beginner": 0.4049522578716278,
"expert": 0.13208581507205963
}
|
11,040
|
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"));
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;
const cityScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city && musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || locationScore >= 75) &&
(city === "" || cityMatch)
);
}).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,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role, 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="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/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" value="<%= musician.city %>">
<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>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#city").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector("#city").value;
const url =
"/search?query=" +
encodeURIComponent(query) +
"&role=" +
encodeURIComponent(role) +
"&city=" +
encodeURIComponent(city);
</script>
</body>
</html>
ошибка:
ReferenceError: C:\Users\Ilya\Downloads\my-musician-network\views\search.ejs:26
24| </select>
25| <label for="city">Search by location:</label>
>> 26| <input id="city" name="city" type="text" value="<%= musician.city %>">
27| <br>
28| <!-- Add new input field for location -->
29|
musician is not defined
|
c71961a1293333acb69d28b763d2eab7
|
{
"intermediate": 0.3409574031829834,
"beginner": 0.34896987676620483,
"expert": 0.31007272005081177
}
|
11,041
|
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"));
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;
const cityScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city && musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || locationScore >= 75) &&
(city === "" || cityMatch)
);
}).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,
location: musician.location
};
});
}
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query, role, 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="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/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>
<% if (musicians.length > 0) { %>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" value="<%= city %>">
<% } %>
<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>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#city").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector("#city").value;
const url =
"/search?query=" +
encodeURIComponent(query) +
"&role=" +
encodeURIComponent(role) +
"&city=" +
encodeURIComponent(city);
</script>
</body>
</html>
ReferenceError: C:\Users\Ilya\Downloads\my-musician-network\views\search.ejs:27
25| <% if (musicians.length > 0) { %>
26| <label for="city">Search by location:</label>
>> 27| <input id="city" name="city" type="text" value="<%= city %>">
28| <% } %>
29| <br>
30| <!-- Add new input field for location -->
city is not defined
|
7f8396567a8fb0589b4f58ea5b3f8655
|
{
"intermediate": 0.346365749835968,
"beginner": 0.4044991731643677,
"expert": 0.2491350769996643
}
|
11,042
|
are u up to date
|
aa5c29e39ef9f19f3ef627d7fef2e17f
|
{
"intermediate": 0.36574798822402954,
"beginner": 0.23631447553634644,
"expert": 0.3979375660419464
}
|
11,043
|
поиск по городам из json файла не работает, подсказки по городу не работают, город при регистрации в register.ejs регистрируется пустой region вместо city, в коде много ошибок. в musicians.json сохраняется “region”:“”, а не city. location и все что с этим связано мы теперь не используем, вместо этого используем city.
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"));
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;
const cityScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city && musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || locationScore >= 75) &&
(city === "" || cityMatch)
);
}).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;
res.render('search', { musicians, query, role, 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");
});
register.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/jquery-ui-dist/jquery-ui.min.js"></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/register">Register</a></li>
<li><a href="/search">Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method="post" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="role">Role</label>
<select id="role" name="role" required onchange="showInstrument(this.value)">
<option value="">Select a role</option>
<option value="Band">A band</option>
<option value="Artist">Artist</option>
</select>
<label for="genre">Genre</label>
<select id="genre" name="genre" required>
<option value="">Select a genre</option>
<option value="Rock">Rock</option>
<option value="Pop">Pop</option>
<option value="Hip hop">Hip hop</option>
<option value="Electronic">Electronic</option>
</select>
<label for="instrument" id="instrument-label" style="display: none">Instrument</label>
<select id="instrument" name="instrument" style="display: none">
<option value="">Select a instrument</option>
<option value="Bass">Bass</option>
<option value="Rythm guitar">Rythm guitar</option>
<option value="Lead guitar">Lead guitar</option>
<option value="Vocal">Vocal</option>
</select>
<label for="soundcloud">SoundCloud URL</label>
<input type="url" id="soundcloud" name="soundcloud">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<label for="city">City:</label>
<input id="city" name="city" type="text" value="<%= citiesAndRegions[0].city %>"><br />
<label for="login">Login</label>
<input type="text" id="login" name="login" required>
<label for="thumbnail">Thumbnail</label>
<input type="file" id="thumbnail" name="thumbnail">
<button type="submit">Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector('#instrument-label');
const instrumentSelect = document.querySelector('#instrument');
if (role === 'Artist') {
instrumentLabel.style.display = 'block';
instrumentSelect.style.display = 'block';
} else {
instrumentLabel.style.display = 'none';
instrumentSelect.style.display = 'none';
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#city").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/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>
<% if (musicians.length > 0) { %>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" value="<%= city %>">
<% } %>
<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>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#city").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector("#city").value;
const url =
"/search?query=" +
encodeURIComponent(query) +
"&role=" +
encodeURIComponent(role) +
"&city=" +
encodeURIComponent(city);
</script>
</body>
</html>
ReferenceError: C:\Users\Ilya\Downloads\my-musician-network\views\search.ejs:27
25| <% if (musicians.length > 0) { %>
26| <label for="city">Search by location:</label>
>> 27| <input id="city" name="city" type="text" value="<%= city %>">
28| <% } %>
29| <br>
30| <!-- Add new input field for location -->
city is not defined
|
7061897564f39c31541ee90667418718
|
{
"intermediate": 0.35267049074172974,
"beginner": 0.5284776091575623,
"expert": 0.11885184794664383
}
|
11,044
|
поиск по городам из json файла не работает, подсказки по городу не работают, город при регистрации в register.ejs регистрируется пустой region вместо city, в коде много ошибок. в musicians.json сохраняется “region”:“”, а не city. location и все что с этим связано мы теперь не используем, вместо этого используем city.
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"));
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;
const cityScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city && musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || locationScore >= 75) &&
(city === "" || cityMatch)
);
}).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;
res.render('search', { musicians, query, role, 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");
});
register.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/jquery-ui-dist/jquery-ui.min.js"></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/register">Register</a></li>
<li><a href="/search">Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method="post" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="role">Role</label>
<select id="role" name="role" required onchange="showInstrument(this.value)">
<option value="">Select a role</option>
<option value="Band">A band</option>
<option value="Artist">Artist</option>
</select>
<label for="genre">Genre</label>
<select id="genre" name="genre" required>
<option value="">Select a genre</option>
<option value="Rock">Rock</option>
<option value="Pop">Pop</option>
<option value="Hip hop">Hip hop</option>
<option value="Electronic">Electronic</option>
</select>
<label for="instrument" id="instrument-label" style="display: none">Instrument</label>
<select id="instrument" name="instrument" style="display: none">
<option value="">Select a instrument</option>
<option value="Bass">Bass</option>
<option value="Rythm guitar">Rythm guitar</option>
<option value="Lead guitar">Lead guitar</option>
<option value="Vocal">Vocal</option>
</select>
<label for="soundcloud">SoundCloud URL</label>
<input type="url" id="soundcloud" name="soundcloud">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<label for="city">City:</label>
<input id="city" name="city" type="text" value="<%= citiesAndRegions[0].city %>"><br />
<label for="login">Login</label>
<input type="text" id="login" name="login" required>
<label for="thumbnail">Thumbnail</label>
<input type="file" id="thumbnail" name="thumbnail">
<button type="submit">Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector('#instrument-label');
const instrumentSelect = document.querySelector('#instrument');
if (role === 'Artist') {
instrumentLabel.style.display = 'block';
instrumentSelect.style.display = 'block';
} else {
instrumentLabel.style.display = 'none';
instrumentSelect.style.display = 'none';
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#city").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/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>
<% if (musicians.length > 0) { %>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" value="<%= city %>">
<% } %>
<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>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#city").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector("#city").value;
const url =
"/search?query=" +
encodeURIComponent(query) +
"&role=" +
encodeURIComponent(role) +
"&city=" +
encodeURIComponent(city);
</script>
</body>
</html>
ReferenceError: C:\Users\Ilya\Downloads\my-musician-network\views\search.ejs:27
25| <% if (musicians.length > 0) { %>
26| <label for="city">Search by location:</label>
>> 27| <input id="city" name="city" type="text" value="<%= city %>">
28| <% } %>
29| <br>
30| <!-- Add new input field for location -->
city is not defined
|
534c14f99fa70302cfa715648d242264
|
{
"intermediate": 0.35267049074172974,
"beginner": 0.5284776091575623,
"expert": 0.11885184794664383
}
|
11,045
|
import requests
from bs4 import BeautifulSoup
import tkinter as tk
from tkinter import ttk
# Create a function to scrape the website and extract the second table tag
def get_table_data():
# Send a GET request to the website
response = requests.get("http://10.29.70.115:8080/apex/f?p=102:2::::::")
# Use BeautifulSoup to parse the HTML content
soup = BeautifulSoup(response.content, "html.parser")
# print(soup)
# Find all table tags and extract the second one
table = soup.find_all("table")[1]
# Extract the data from the table and return it
data = []
for row in table.find_all("tr"):
row_data = []
for cell in row.find_all("th"):
row_data.append(cell.text)
for cell in row.find_all("td"):
row_data.append(cell.text)
data.append(row_data)
return data
# Create a function to display the table data in a tkinter window
def display_table_data():
# Create a new tkinter window
window = tk.Tk()
# Set the window title
window.title("Table Data")
# Set the window size
# window.geometry("1000x800")
# Get the table data
table_data = get_table_data()
# Create a tkinter frame to hold the treeview and scrollbar
frame = tk.Frame(window)
frame.pack(fill=tk.BOTH, expand=True)
# Create a tkinter treeview for the table data
# treeview = ttk.Treeview(frame, columns=range(len(table_data[0])), show="headings")
treeview = ttk.Treeview(frame, columns=table_data[0], show="headings")
print(table_data)
print(table_data[0])
print(len(table_data[0]))
print(range(len(table_data[0])))
# Add each column of data to the treeview
# for i, column in enumerate(table_data[0]):
# treeview.heading(i, text=column)
# treeview.column(i, width=1000, anchor='center')
# Add each row of data to the treeview
for row in table_data[0:]:
treeview.insert("", tk.END, values=row)
# Create a tkinter scrollbar for the treeview
scrollbar = tk.Scrollbar(frame)
# Link the scrollbar to the treeview
treeview.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=treeview.yview)
# scrollbar.config(yscrollincrement=1)
# Pack the treeview and scrollbar into the frame
treeview.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Run the tkinter event loop
window.mainloop()
# Call the display_table_data function to show the table data in a tkinter window
display_table_data()
很卡如何优化一起加载所有行
|
39c7d8f6bc229b9077cff43e22a02985
|
{
"intermediate": 0.36079925298690796,
"beginner": 0.4875240921974182,
"expert": 0.15167661011219025
}
|
11,046
|
поиск по городам не работает. в musicians.json заносится "region":"", а не city. при заходе в search получаю ошибку: musician is not defined
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"));
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;
const cityScore = fuzzball.token_set_ratio(musician.location.toLowerCase(), location.toLowerCase()); // изменено здесь
const cityMatch = musician.city && musician.city.toLowerCase() === city.toLowerCase();
return (
nameScore + genreScore + locationScore > 0 &&
(role === "" || musician.role === role) &&
(city === "" || locationScore >= 75) &&
(city === "" || cityMatch)
);
}).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;
res.render('search', { musicians, query, role, 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");
});
register.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="/css/main.css" />
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/jquery-ui-dist/jquery-ui.min.js"></script>
<title>Register as a Musician</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/register">Register</a></li>
<li><a href="/search">Search</a></li>
</ul>
</nav>
</header>
<main>
<h1>Register as a Musician</h1>
<form method="post" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="role">Role</label>
<select id="role" name="role" required onchange="showInstrument(this.value)">
<option value="">Select a role</option>
<option value="Band">A band</option>
<option value="Artist">Artist</option>
</select>
<label for="genre">Genre</label>
<select id="genre" name="genre" required>
<option value="">Select a genre</option>
<option value="Rock">Rock</option>
<option value="Pop">Pop</option>
<option value="Hip hop">Hip hop</option>
<option value="Electronic">Electronic</option>
</select>
<label for="instrument" id="instrument-label" style="display: none">Instrument</label>
<select id="instrument" name="instrument" style="display: none">
<option value="">Select a instrument</option>
<option value="Bass">Bass</option>
<option value="Rythm guitar">Rythm guitar</option>
<option value="Lead guitar">Lead guitar</option>
<option value="Vocal">Vocal</option>
</select>
<label for="soundcloud">SoundCloud URL</label>
<input type="url" id="soundcloud" name="soundcloud">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<label for="city">City:</label>
<input id="city" name="city" type="text" value="<%= citiesAndRegions[0].city %>"><br />
<label for="login">Login</label>
<input type="text" id="login" name="login" required>
<label for="thumbnail">Thumbnail</label>
<input type="file" id="thumbnail" name="thumbnail">
<button type="submit">Register</button>
</form>
</main>
<script>
function showInstrument(role) {
const instrumentLabel = document.querySelector('#instrument-label');
const instrumentSelect = document.querySelector('#instrument');
if (role === 'Artist') {
instrumentLabel.style.display = 'block';
instrumentSelect.style.display = 'block';
} else {
instrumentLabel.style.display = 'none';
instrumentSelect.style.display = 'none';
}
}
</script>
<script>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#city").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
</body>
</html>
search.ejs:
<!DOCTYPE html>
<html>
<head>
<title>Search Musicians</title>
<link rel="stylesheet" href="/node_modules/jquery-ui/themes/base/all.css" />
<script src="/node_modules/jquery/dist/jquery.min.js"></script>
<script src="/node_modules/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>
<% if (musicians.length > 0) { %>
<label for="city">Search by location:</label>
<input id="city" name="city" type="text" value="<%= musician.city %>">
<% } %>
<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>
(function () {
const cities = <%= JSON.stringify(citiesAndRegions.map(item => item.city)) %>;
("#city").autocomplete({
source: cities,
minLength: 3,
});
});
</script>
<script>
const city = document.querySelector("#city").value;
const url =
"/search?query=" +
encodeURIComponent(query) +
"&role=" +
encodeURIComponent(role) +
"&city=" +
encodeURIComponent(city);
</script>
</body>
</html>
|
bd43622f04390c87b12d121a15b5f2b3
|
{
"intermediate": 0.29534611105918884,
"beginner": 0.5940272212028503,
"expert": 0.1106266900897026
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.