row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
10,646
|
i have a extracted some text from an invoice using ocr. Now i have both the word and its corresponding bounding boxes. how do i concat the words such that it mimics the text structure as in the invoice?
|
c189250fcf1b06bda1d7c35179fa4179
|
{
"intermediate": 0.36990857124328613,
"beginner": 0.20303624868392944,
"expert": 0.4270552098751068
}
|
10,647
|
c# word document create title
|
8118484f098c89cc8c6a914072d3d067
|
{
"intermediate": 0.26294994354248047,
"beginner": 0.24023304879665375,
"expert": 0.49681705236434937
}
|
10,648
|
os.getenv是什么python命令?
|
f3daba1c01e550fc941d45843878399c
|
{
"intermediate": 0.3225279152393341,
"beginner": 0.3221556544303894,
"expert": 0.35531648993492126
}
|
10,649
|
UserWarning: Usage of gradio.inputs is deprecated, and will not be supported in the future, please import your component from gradio.components, how to fix this?
|
04d3cc7825ef3c88c3a421256e4900cd
|
{
"intermediate": 0.5558527708053589,
"beginner": 0.1688644289970398,
"expert": 0.2752828299999237
}
|
10,650
|
undefined reference to `__printf_chk'
|
c380ea48e471a1320502c82c14994919
|
{
"intermediate": 0.29522332549095154,
"beginner": 0.42768242955207825,
"expert": 0.2770942151546478
}
|
10,651
|
How to initial SDL
|
a22d321c99a5c65d50c0d92eb073abaf
|
{
"intermediate": 0.4148203134536743,
"beginner": 0.17738232016563416,
"expert": 0.40779736638069153
}
|
10,652
|
Улучшить данный код, расширить возможности:
# Pornhub Video Downloader
This script was made by using python 3.6, pretty simple and no advanced option required, just a simple directory and video link and you're good to go.
(ps this script are looped, press Control + C to stop it)
## Installation
Use the package manager [pip](https://pip.pypa.io/en/stable/) to install foobar.
|
ca7f587153b2ad0c85140d3eb1d156ab
|
{
"intermediate": 0.24164582788944244,
"beginner": 0.5482132434844971,
"expert": 0.21014094352722168
}
|
10,653
|
Hello analyse this website https://huggingface.co/HuggingFaceH4/starchat-alpha/tree/main
|
d52b2296bce82141dfaf32618f0cf296
|
{
"intermediate": 0.29427266120910645,
"beginner": 0.2340092808008194,
"expert": 0.47171804308891296
}
|
10,654
|
I have this code
import requests
import json
# download the files from the website
url = "https://huggingface.co/HuggingFaceH4/starchat-alpha/tree/main"
files = [“model.tar.gz”, “vocab.json”, “merges.txt”]
for file in files:
response = requests.get(url + file)
with open(file, “wb”) as f:
f.write(response.content)
# load the downloaded files into a chatbot
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
tokenizer = AutoTokenizer.from_pretrained(”./“)
model = AutoModelForCausalLM.from_pretrained(”./")
chatbot = pipeline(“text-generation”, model=model, tokenizer=tokenizer)
# interact with the chatbot
while True:
user_input = input("You: ")
response = chatbot(user_input)
print(“Bot:”, response[0][“generated_text”]) and this error File "<ipython-input-4-c0a8fd01bac7>", line 6
files = [“model.tar.gz”, “vocab.json”, “merges.txt”]
^
SyntaxError: invalid character '“' (U+201C)
|
5ecd987710b2afeaddbd746a62507b7b
|
{
"intermediate": 0.3675103485584259,
"beginner": 0.44644472002983093,
"expert": 0.18604490160942078
}
|
10,655
|
check a string starts with certain characters in C
|
bf48b40cffb19bdd06d893b6cf800803
|
{
"intermediate": 0.2381475865840912,
"beginner": 0.5311819911003113,
"expert": 0.23067042231559753
}
|
10,656
|
im trying to show posts from collection but there is empty, collections name is FutureMK. I need that all users even guests could read posts and only admin can write it. here is my rules in firebase
{
"rules": {
"users":{
"$uid":{
".read":
"$uid===auth.uid",
".write":
"$uid===auth.uid"
}
},
"FutureMK":{
".read":
true,
".write": "root.child('users').child(auth.uid).child('admin').val() === true"
}
}
}
|
474397b415a943f72f05bdcb4ac8d047
|
{
"intermediate": 0.3662424087524414,
"beginner": 0.30076178908348083,
"expert": 0.33299583196640015
}
|
10,657
|
how to use datataloader with batch size after train test split
|
8069a647547a76b283723fb9b8ecd745
|
{
"intermediate": 0.41907429695129395,
"beginner": 0.1359207034111023,
"expert": 0.44500502943992615
}
|
10,658
|
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_transactions_from_block(block_number, session):
async with semaphore:
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_newly_created_contracts(start_block, end_block):
contract_list = []
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_transactions_from_block(block_number, session)
filter_address = '0x863b49ae97c3d2a87fd43186dfd921f42783c853'
return [tx for tx in transactions if tx['isError'] == '0' and tx['contractAddress'] != '' and tx['from'] == filter_address]
async with aiohttp.ClientSession() as session:
tasks = [process_block(block_number) for block_number in range(start_block, end_block + 1)]
results = await asyncio.gather(*tasks)
for contracts in results:
contract_list.extend(contracts)
return contract_list
def display_new_contracts(start_block, end_block):
loop = asyncio.get_event_loop()
contracts = loop.run_until_complete(get_newly_created_contracts(start_block, end_block))
if not contracts:
print('No new contracts found.')
else:
print(f'Newly created smart contracts between blocks {start_block} and {end_block}: ')
for contract in contracts:
print(f"Block: {contract['blockNumber']} - Address: {contract['contractAddress']}")
start_block = 28864500 # Replace with your desired start block
end_block = 28864999 # Replace with your desired end block
display_new_contracts(start_block, end_block)
The code above throws an error
C:\Users\AshotxXx\PycharmProjects\UNCX\Add_Liquidity_and_Lock\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py", line 58, in <module>
display_new_contracts(start_block, end_block)
File "C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py", line 46, in display_new_contracts
contracts = loop.run_until_complete(get_newly_created_contracts(start_block, end_block))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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\UNCX\Project1\main.py", line 37, in get_newly_created_contracts
results = await asyncio.gather(*tasks)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py", line 33, in process_block
return [tx for tx in transactions if tx['isError'] == '0' and tx['contractAddress'] != '' and tx['from'] == filter_address]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py", line 33, in <listcomp>
return [tx for tx in transactions if tx['isError'] == '0' and tx['contractAddress'] != '' and tx['from'] == filter_address]
~~^^^^^^^^^^^
KeyError: 'isError'
Process finished with exit code -1073741819 (0xC0000005)
Fix it
|
f82e5daec4870474c1334e6bbf4c3b7f
|
{
"intermediate": 0.33978500962257385,
"beginner": 0.5370384454727173,
"expert": 0.12317650765180588
}
|
10,659
|
ERROR [2023-06-07T05:13:56.208Z] @firebase/firestore: Firestore (9.22.1): Uncaught Error in snapshot listener: FirebaseError: [code=permission-denied]: Missing or insufficient permissions.
i need to set up cloudstore firebase. where i can find it?
|
2cb692c7695d142cd3b1c52f81edf3ff
|
{
"intermediate": 0.5389596223831177,
"beginner": 0.24406974017620087,
"expert": 0.21697057783603668
}
|
10,660
|
how to transform date to specific string format in javascript
|
6eea9778eac2e42211154556296a9d6b
|
{
"intermediate": 0.46993619203567505,
"beginner": 0.17770501971244812,
"expert": 0.35235875844955444
}
|
10,661
|
TypeError: Cannot read property 'uid' of null
import { Pressable, Text, TextInput, View, Image, TouchableOpacity, Modal } from 'react-native';
import { gStyle } from '../styles/style';
import { Feather } from '@expo/vector-icons';
import React, { useState, useEffect } from 'react';
import { useNavigation } from '@react-navigation/native';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
export default function Header() {
const [userAuthenticated, setUserAuthenticated] = useState(false);
const [isModalVisible, setIsModalVisible] = useState(false);
const showModal = () => {
setIsModalVisible(true);
};
const hideModal = () => {
setIsModalVisible(false);
};
const navigation = useNavigation();
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
if (user) {
setUserAuthenticated(true);
} else {
setUserAuthenticated(false);
}
});
return unsubscribe;
}, []);
return (
<View style={gStyle.main}>
<View style={gStyle.headerContainer}>
<Image
source={require('../assets/logo.png')}
style={gStyle.logoImg}
/>
<View style={gStyle.menu}>
<TouchableOpacity onPress={showModal}>
<Text style={gStyle.menuRedLine}></Text>
<Text style={gStyle.menuRedLine}></Text>
<Text style={gStyle.menuRedLine}></Text>
<Modal visible={isModalVisible} animationType='fade' transparent={true}>
<View style={gStyle.modal}>
<TouchableOpacity onPress={hideModal}>
<Text style={gStyle.close}>Х</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={()=>navigation.navigate('Home')}
>
<Text style={gStyle.menuItem}>Главная</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={()=>navigation.navigate('AllFutureMK')}
>
<Text style={gStyle.menuItem}>Будущие мастер-классы</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={()=>navigation.navigate('AllPastMK')}
>
<Text style={gStyle.menuItem}>Архив мастер-классов</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={()=>navigation.navigate('FormAddMK')}
>
<Text style={gStyle.menuItem}>Добавить мастер-класс</Text>
</TouchableOpacity>
{userAuthenticated ?
<TouchableOpacity
onPress={()=>navigation.navigate('Profile')}
>
<Text style={gStyle.menuItem}>Личный кабинет</Text>
</TouchableOpacity>
:
<TouchableOpacity
onPress={()=>navigation.navigate('Auth')}
>
<Text style={gStyle.menuItem}>Личный кабинет</Text>
</TouchableOpacity>
}
</View>
</Modal>
</TouchableOpacity>
</View>
</View>
<View style={gStyle.searchBox}>
<TextInput style={gStyle.search} placeholder="Поиск" />
<View style={gStyle.boxBtn}>
<Pressable style={gStyle.searchBtn}>
<Feather name="search" size={25} color="white" />
</Pressable>
</View>
</View>
</View>
);
}
import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity } from 'react-native';
import { gStyle } from '../styles/style';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { useNavigation } from '@react-navigation/native';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState} from 'react';
export default function Auth() {
const navigation = useNavigation();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleLogin = () => {
firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
const user = userCredential.user;
console.log('Пользователь вошел:', user.email);
})
.catch((error) => {
const errorMessage = error.message;
console.log(errorMessage);
Alert.alert('Ошибка!', errorMessage);
});
};
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<Text style={gStyle.header}>Войти в личный{"\n"}кабинет</Text>
<View style={gStyle.AuthContainer}>
<View style={gStyle.AuthBox}>
<View style={gStyle.AuthBox1}>
<Text style={gStyle.AuthName}>Почта</Text>
<TextInput style={gStyle.AuthInfo}
onChangeText={setEmail}
/>
</View>
<View style={gStyle.AuthBox1}>
<Text style={gStyle.AuthName}>Пароль</Text>
<TextInput style={gStyle.AuthInfo}
onChange={setPassword}
secureTextEntry={true}
/>
</View>
</View>
<Pressable style={gStyle.AuthForgotPassword} onPress={''}>
<Text style={gStyle.AuthPass}>Забыли пароль?</Text>
</Pressable>
<TouchableOpacity style={gStyle.AuthLogin} onPress={handleLogin}>
<Text style={gStyle.AuthBtnLogin}>Войти</Text>
</TouchableOpacity>
<Pressable
onPress={()=>navigation.navigate('Registration')}
>
<Text style={gStyle.AuthRegistr}>Я не зарегистрирован(а)</Text>
</Pressable>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
whats wrong?
|
5955591fea6d2ab1f5a471d7a4a6c965
|
{
"intermediate": 0.44104593992233276,
"beginner": 0.43142837285995483,
"expert": 0.1275256872177124
}
|
10,662
|
when I deploy an app to huggingface, it shows this error information:
Runtime error
Traceback (most recent call last):
File "/home/user/app/app.py", line 1, in <module>
import openai
ModuleNotFoundError: No module named 'openai'
what does that mean and how do I fix it?
|
c22574b8f75092fbff6065ef0729d28a
|
{
"intermediate": 0.7559495568275452,
"beginner": 0.11880044639110565,
"expert": 0.12524999678134918
}
|
10,663
|
how to install docker?
|
6a5204e4427445255bbb87506720669c
|
{
"intermediate": 0.5559177994728088,
"beginner": 0.23823918402194977,
"expert": 0.2058430165052414
}
|
10,664
|
Write bash loop
|
71a029f6b08886d81b471a9497ef8931
|
{
"intermediate": 0.2083727866411209,
"beginner": 0.6299597024917603,
"expert": 0.16166745126247406
}
|
10,665
|
when I try to deploy an app build with python 3 on hugging face, it says this error: File "/home/user/.local/lib/python3.10/site-packages/gradio/blocks.py", line 1834, in launch
raise RuntimeError("Share is not supported when you are in Spaces"), how to solve it?
|
4d73975352660ce1506326af562c4afe
|
{
"intermediate": 0.7419136762619019,
"beginner": 0.13081927597522736,
"expert": 0.1272670328617096
}
|
10,666
|
in java how to create new date with value "Thu, 06 Jun 2024 12:15:24 CST"
|
3e54c27e977c97f9907b26e576db4f52
|
{
"intermediate": 0.46665769815444946,
"beginner": 0.19354817271232605,
"expert": 0.3397941589355469
}
|
10,667
|
import { Text, View, Image, Pressable } from ‘react-native’;
import { gStyle } from ‘…/styles/style’;
import React, {useState, useEffect} from ‘react’;
import { useNavigation } from ‘@react-navigation/native’;
import {firebase} from ‘…/Firebase/firebase’;
export default function FutureMK() {
const navigation = useNavigation();
const [futureMKData, setFutureMKData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const futureMKRef = firebase.firestore().collection(‘FutureMK’);
const snapshot = await futureMKRef.get();
const data = snapshot.docs.map((doc) => doc.data());
setFutureMKData(data);
} catch (error) {
console.log(error);
}
};
fetchData();
}, []);
return (
<View style={gStyle.main}>
{futureMKData.map((mkData, index)=>(
<View key={index} style={gStyle.mainFMK}>
<Text style={gStyle.dateFutureMK}>{mkData.time}</Text>
<View style={gStyle.FutureMKimg}>
<Image source={{uri:mkData.imageUrl}} style={gStyle.FutureMKbannerImg}/>
<Text style={gStyle.FutureMKnameOfMK}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
</View>
<Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>{mkData.price} P.</Text></Text>
<Text style={gStyle.FutureMKdescription}>
{mkData.description}
</Text>
<Pressable style={gStyle.FutureMKmoreDetails}
onPress={()=>{navigation.navigate(‘SignUpForMK’,{mkData:mkData});}}
>
<Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text>
</Pressable>
<Text style={gStyle.FutureMKline}></Text>
</View>
))}
</View>
);
}
[FirebaseError: Missing or insufficient permissions.]
|
95217ccb061832350a0d8eb3b0b7b528
|
{
"intermediate": 0.5773279666900635,
"beginner": 0.23454579710960388,
"expert": 0.18812625110149384
}
|
10,668
|
how to set server's date and time to added_at class OurDoc(Base):
__tablename__ = 'our_doc'
doc_name: Mapped[str] = mapped_column(VARCHAR(32), unique=True, nullable=False)
added_at: Mapped[datetime] = mapped_column(TIMESTAMP, nullable=False, server_default=func.now())
novalid_date: Mapped[datetime] = mapped_column(TIMESTAMP, nullable=False)
|
dafe1a194ce2c0169ec30cc83498ebec
|
{
"intermediate": 0.47769755125045776,
"beginner": 0.3130175769329071,
"expert": 0.20928488671779633
}
|
10,669
|
Write a letter reply to the lawyer of bank of westpac regarding the following points, Dear Mr Ma
Your Indebtedness to Westpac Banking Corporation (Westpac)
41 Frederick Street, Balwyn in the State of Victoria (Property)
Loan Account ending in 413 (Loan Account)
1. As you know, we act on behalf of Westpac. We refer to your email of 31 August 2022 and your
recent telephone discussion with Rachel Rouyanian of our office.
2. By our correspondence of 15 August 2022, Westpac offered to apply a partial debt reduction of
$10,000, subject to you strictly complying with the handback requirements as set out in that letter.
That offer was made on a purely commercial basis to resolve the matter without further delay.
3. We understand from our recent communications with you that you are not prepared to accept
Westpac's offer, and that you seek a much higher debt reduction.
4. Based on your response, Westpac understands that a negotiated resolution of this matter now
appears unlikely. In the circumstances, Westpac is now considering its options to progress
enforcement action.
5. As mentioned previously, there are complications associated with a mortgagee sale of an owner-
built dwelling. Westpac needs to consider alternative options to enforce its mortgage, such as
demolishing the dwelling on the Property and selling the vacant land.
6. Before forming a decision about demolition, Westpac is first seeking to ascertain whether it can
obtain an exemption from the relevant legislative requirements for sale of owner-built property in
this case. Westpac is taking steps to progress an application to the Victorian Civil and
Administrative Tribunal for this purpose.
7. If Westpac is not able to obtain the exemption, and no satisfactory arrangement has been
reached to hand the Property back to you, Westpac will need to seriously consider demolishing
the dwelling on the Property so that Westpac can sell the vacant land.
8. Please feel free to submit an alternative proposal for Westpac's consideration at any time. In the
meantime, the above steps will continue.
|
9a57a3d8ca6a50463f0304fb6649c278
|
{
"intermediate": 0.34069499373435974,
"beginner": 0.349164754152298,
"expert": 0.3101402223110199
}
|
10,670
|
can I temporarily downgrade to python3.9 from python 3.10 on windows 10? how to do it
|
1c813c50e0313c7cf32dadec2b808e03
|
{
"intermediate": 0.40205976366996765,
"beginner": 0.28165456652641296,
"expert": 0.3162856698036194
}
|
10,671
|
Is it true that, in C++, programming errors violating const will cause runtime errors?
|
e650c94434fbbe939f8ad92a33214ae9
|
{
"intermediate": 0.32445475459098816,
"beginner": 0.36423662304878235,
"expert": 0.31130868196487427
}
|
10,672
|
import { Text, View, Image, Pressable } from 'react-native';
import { gStyle } from '../styles/style';
import React, {useState, useEffect} from 'react';
import { useNavigation } from '@react-navigation/native';
import {firebase} from '../Firebase/firebase';
import moment from 'moment';
export default function FutureMK() {
const navigation = useNavigation();
const [futureMKData, setFutureMKData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const futureMKRef = firebase.firestore().collection('FutureMK');
const snapshot = await futureMKRef.get();
const data = snapshot.docs.map((doc) => doc.data());
setFutureMKData(data);
} catch (error) {
console.log(error);
}
};
fetchData();
}, []);
return (
<View style={gStyle.main}>
{futureMKData.map((mkData, index)=>(
<View key={index} style={gStyle.mainFMK}>
<Text style={gStyle.dateFutureMK}>{moment(mkData.time.toDate()).format('DD-MM-YYYY')}</Text>
<View style={gStyle.FutureMKimg}>
<Image source={{uri:mkData.imageUrl}} style={gStyle.FutureMKbannerImg}/>
<Text style={gStyle.FutureMKnameOfMK}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
</View>
<Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>{mkData.price} P.</Text></Text>
<Text style={gStyle.FutureMKdescription}>
{mkData.description}
</Text>
<Pressable style={gStyle.FutureMKmoreDetails}
onPress={()=>{navigation.navigate('SignUpForMK',{mkData:mkData});}}
>
<Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text>
</Pressable>
<Text style={gStyle.FutureMKline}></Text>
</View>
))}
</View>
);
}
there arent any pics though i have uploaded them in storage bucket
|
141476246ec124f038bea399ac6452d4
|
{
"intermediate": 0.42840883135795593,
"beginner": 0.3783518373966217,
"expert": 0.19323934614658356
}
|
10,673
|
C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\gradio\inputs.py:27: UserWarning: Usage of gradio.inputs is deprecated, and will not be supported in the future, please import your component from gradio.components how do I solve this problem?
|
474bf02f341a831518d57a2117235d20
|
{
"intermediate": 0.7502734661102295,
"beginner": 0.07877374440431595,
"expert": 0.17095282673835754
}
|
10,674
|
import { Text, View, Image, Pressable } from 'react-native';
import { gStyle } from '../styles/style';
import React, {useState, useEffect} from 'react';
import { useNavigation } from '@react-navigation/native';
import {firebase} from '../Firebase/firebase';
import moment from 'moment';
export default function FutureMK() {
const navigation = useNavigation();
const [futureMKData, setFutureMKData] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const futureMKRef = firebase.firestore().collection('FutureMK');
const snapshot = await futureMKRef.get();
const data = snapshot.docs.map((doc) => doc.data());
setFutureMKData(data);
const storage = firebase.storage();
const ref = storage.ref('https://firebasestorage.googleapis.com/v0/b/white-rose-e2a26.appspot.com/o/FutureMK%2Fhotela-podderzhat-podrugu-i-za_1668857760.jpg?alt=media&token=ec586186-3aab-428a-bb26-77a5f89f41e1&_gl=1*5k94v9*_ga*MTUyNDE5NTYyMi4xNjg1ODA3ODQ0*_ga_CW55HF8NVT*MTY4NjExNzU1My4yNi4xLjE2ODYxMjEyMTYuMC4wLjA.');
const url = await ref.getDownloadURL();
console.log('URL:', url); // Add this line to log the URL to the console
} catch (error) {
console.log(error);
}
};
fetchData();
}, []);
return (
<View style={gStyle.main}>
{futureMKData.map((mkData, index)=>(
<View key={index} style={gStyle.mainFMK}>
<Text style={gStyle.dateFutureMK}>{moment(mkData.time.toDate()).format('DD-MM-YYYY')}</Text>
<View style={gStyle.FutureMKimg}>
<Image source={{uri:mkData.imageUrl}} style={gStyle.FutureMKbannerImg}/>
<Text style={gStyle.FutureMKnameOfMK}>{mkData.name}</Text>
<Text style={gStyle.hr}></Text>
</View>
<Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>{mkData.price} P.</Text></Text>
<Text style={gStyle.FutureMKdescription}>
{mkData.description}
</Text>
<Pressable style={gStyle.FutureMKmoreDetails}
onPress={()=>{navigation.navigate('SignUpForMK',{mkData:mkData});}}
>
<Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text>
</Pressable>
<Text style={gStyle.FutureMKline}></Text>
</View>
))}
{imageUrl ? (
<Image source={{ uri: imageUrl }} />
) : (
<Text>No image available</Text>
)}
</View>
);
}
|
a61badbc83fb316b98abba33fa78daf1
|
{
"intermediate": 0.47111037373542786,
"beginner": 0.4423845112323761,
"expert": 0.08650507032871246
}
|
10,675
|
Solve the last function using the streamapi and lambda
package ex11;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class BatchStore<T> {
ArrayList<List> batches = new ArrayList<>();
public void addBatch(List<T> batch) {
batches.add(batch);
}
public int getSize() {
return batches.size();
}
public Integer getSizeOfLargestBatch() {
return batches.stream().max(Comparator.comparingInt(List::size)).orElse(Collections.emptyList()).size();
}
public List<?> getBatchWithMaxSum() {
}
}
|
d75a8ade9a5b290f3b05297823571f78
|
{
"intermediate": 0.49001362919807434,
"beginner": 0.3464590609073639,
"expert": 0.163527250289917
}
|
10,676
|
can you help create slides for plant information reference architecture
|
5ffd0bd14041d9463e6115080a05586a
|
{
"intermediate": 0.4185960292816162,
"beginner": 0.30809569358825684,
"expert": 0.27330827713012695
}
|
10,677
|
I have an application - a social network for musicians. In this script, in the profile of the authorized user, it is now possible to add ONLY ONE MUSIC TRACK from soundcloud. I added the ability to add multiple tracks, but it doesn't work, only the first one added is added. Help me to fix this. Here is the code:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud || [];
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width="100%" height="300" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">SoundCloud:</label>
<div id="music-fields">
<% if (musician.soundcloud) { %>
<% if (Array.isArray(musician.soundcloud)) { musician.soundcloud.forEach(function(url) { %>
<div>
<input type="text" name="soundcloud[]" value="<%= url %>">
<button type="button" class="delete-music-button">×</button>
</div>
<% }); %> <!-- Add this closing tag -->
<% } %>
<% } %>
<div>
<input type="text" name="soundcloud" value="<%= musician.soundcloud %>" placeholder="Soundcloud track URL">
<button type="button" class="add-music-button">Add Music</button>
</div>
</div>
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
const musicFields = document.getElementById("music-fields");
const addMusicButton = document.querySelector(".add-music-button");
addMusicButton.addEventListener("click", (event) => {
event.preventDefault();
const musicField = document.createElement("div");
musicField.innerHTML = '<br/> <input type="text" name="soundcloud[]" placeholder="SoundCloud track URL"><br/> <button type="button" class="delete-music-button">×</button><br/>';
musicFields.insertBefore(musicField, addMusicButton.parentNode);
});
musicFields.addEventListener("click", (event) => {
if (event.target.classList.contains("delete-music-button")) {
event.preventDefault();
event.target.parentNode.remove();
}
});
</script>
</body>
</html>
Also, user datebase saved in json file musicians.json (where also stored soundcloud data):
{"musicians":[{"id":1,"name":"sukaAAAAAAA","genre":"BluesZ","instrument":"Guitar","soundcloud":"http://soundcloud.com/dasdasdasd","password":"password123","location":"New York","login":"suka","bio":""},{"id":2,"name":"Aerosmith111114446","genre":"Blues","password":"1111","location":"EnglandDdD","thumbnail":"musician_2_jX7hQvfoT2g (2).jpg","instrument":"","bio":"","soundcloud":"https://soundcloud.com/ty-segall-official/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"}]}
|
72c538e6b7e3378983807d28cabb41d2
|
{
"intermediate": 0.374794602394104,
"beginner": 0.4287233352661133,
"expert": 0.19648204743862152
}
|
10,678
|
how to start scan with wifite tool in kali
|
290a75322cd55251ed601145dae6fda2
|
{
"intermediate": 0.3602069020271301,
"beginner": 0.19186553359031677,
"expert": 0.44792765378952026
}
|
10,679
|
I have an application - a social network for musicians. In this script, in the profile of the authorized user, it is now possible to add ONLY ONE MUSIC TRACK from soundcloud. I added the ability to add multiple tracks, but it doesn't work, only the first one added is added. Help me to fix this. Here is the code:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
musician.soundcloud = req.body.soundcloud || [];
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<iframe width="100%" height="300" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">SoundCloud:</label>
<div id="music-fields">
<% if (musician.soundcloud) { %>
<% if (Array.isArray(musician.soundcloud)) { musician.soundcloud.forEach(function(url) { %>
<div>
<input type="text" name="soundcloud[]" value="<%= url %>">
<button type="button" class="delete-music-button">×</button>
</div>
<% }); %> <!-- Add this closing tag -->
<% } %>
<% } %>
<div>
<input type="text" name="soundcloud" value="<%= musician.soundcloud %>" placeholder="Soundcloud track URL">
<button type="button" class="add-music-button">Add Music</button>
</div>
</div>
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
const musicFields = document.getElementById("music-fields");
const addMusicButton = document.querySelector(".add-music-button");
addMusicButton.addEventListener("click", (event) => {
event.preventDefault();
const musicField = document.createElement("div");
musicField.innerHTML = '<br/> <input type="text" name="soundcloud[]" placeholder="SoundCloud track URL"><br/> <button type="button" class="delete-music-button">×</button><br/>';
musicFields.insertBefore(musicField, addMusicButton.parentNode);
});
musicFields.addEventListener("click", (event) => {
if (event.target.classList.contains("delete-music-button")) {
event.preventDefault();
event.target.parentNode.remove();
}
});
</script>
</body>
</html>
Also, user datebase saved in json file musicians.json (where also stored soundcloud data):
{"musicians":[{"id":1,"name":"sukaAAAAAAA","genre":"BluesZ","instrument":"Guitar","soundcloud":"http://soundcloud.com/dasdasdasd","password":"password123","location":"New York","login":"suka","bio":""},{"id":2,"name":"Aerosmith111114446","genre":"Blues","password":"1111","location":"EnglandDdD","thumbnail":"musician_2_jX7hQvfoT2g (2).jpg","instrument":"","bio":"","soundcloud":"https://soundcloud.com/ty-segall-official/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"}]}
|
81e47085fae7f0aafefbcc3997852b9b
|
{
"intermediate": 0.374794602394104,
"beginner": 0.4287233352661133,
"expert": 0.19648204743862152
}
|
10,680
|
привет, помоги с рефакторингом этого класса
public class CollidersSpawnerFireExtinguisher : MonoBehaviour
{
[SerializeField]
private FireExtinguisher[] collidersToSpawn;
[SerializeField]
private FireExtinguisherBoxTrigger[] colliders;
[Inject]
private ISubscriber subscriber = null;
void Start()
{
subscriber.Subscriber<StartSessionMessage>(SpawnColliders);
}
void SpawnColliders(StartSessionMessage message)
{
var i = 0;
foreach (FireExtinguisher info in collidersToSpawn)
{
colliders[i].transform.position = info.gameObject.transform.position;
i++;
}
}
private void OnEnable()
{
subscriber.UnSudscribe<StartSessionMessage>(SpawnColliders);
}
}
|
1f1ac0ce82aecd8ad5e5922b8c205275
|
{
"intermediate": 0.4105583131313324,
"beginner": 0.411262571811676,
"expert": 0.17817910015583038
}
|
10,681
|
Please give me code to find rows with similar x1 and a high difference in x2.
> testDF
X1 X2
imageimagesD249.jpg 2.41 -0.06
imageimagesD242.jpg 2.62 -0.02
imageimagesD251.jpg 2.66 0.12
imageimagesD255.jpg 2.68 0.24
imageimagesD198.jpg 2.98 -0.09
imageimagesD239.jpg 3.16 -0.25
imageimagesD9.jpg 3.17 -0.08
imageimagesD219.jpg 3.18 0.07
imageimagesD230.jpg 3.18 -0.14
imageimagesD149.jpg 3.20 -0.32
imageimagesD136.jpg 3.20 -0.04
imageimagesD50.jpg 3.29 -0.37
imageimagesD201.jpg 3.31 -0.06
imageimagesD152.jpg 3.31 -0.33
imageimagesD10.jpg 3.31 -0.46
imageimagesD247.jpg 3.33 -0.11
imageimagesD216.jpg 3.33 -0.18
imageimagesD256.jpg 3.34 -0.16
imageimagesD221.jpg 3.35 -0.01
imageimagesD181.jpg 3.35 -0.45
imageimagesD199.jpg 3.38 -0.23
imageimagesD197.jpg 3.40 -0.19
imageimagesD174.jpg 3.42 -0.25
imageimagesD209.jpg 3.43 0.12
imageimagesD208.jpg 3.43 0.01
imageimagesD238.jpg 3.45 -0.02
imageimagesD160.jpg 3.46 -0.31
imageimagesD16.jpg 3.46 -0.41
imageimagesD233.jpg 3.47 -0.23
imageimagesD140.jpg 3.47 -0.09
imageimagesD18.jpg 3.49 -0.03
imageimagesD180.jpg 3.49 -0.32
imageimagesD14.jpg 3.49 -0.21
imageimagesD248.jpg 3.50 -0.05
imageimagesD212.jpg 3.51 -0.21
imageimagesD165.jpg 3.52 -0.43
imageimagesD170.jpg 3.52 -0.13
imageimagesD138.jpg 3.53 -0.13
imageimagesD189.jpg 3.53 -0.33
imageimagesD185.jpg 3.53 -0.35
imageimagesD236.jpg 3.55 -0.17
imageimagesD151.jpg 3.56 -0.31
imageimagesD194.jpg 3.56 -0.28
imageimagesD164.jpg 3.60 -0.42
imageimagesD144.jpg 3.61 -0.34
imageimagesD1.jpg 3.61 -0.11
imageimagesD147.jpg 3.62 -0.21
imageimagesD43.jpg 3.62 -0.32
imageimagesD202.jpg 3.63 -0.11
imageimagesD204.jpg 3.63 -0.05
imageimagesD150.jpg 3.64 -0.26
imageimagesD131.jpg 3.64 -0.18
imageimagesD237.jpg 3.64 -0.28
imageimagesD211.jpg 3.65 -0.08
imageimagesD188.jpg 3.66 -0.27
imageimagesD241.jpg 3.66 -0.14
imageimagesD139.jpg 3.67 -0.25
imageimagesD62.jpg 3.67 -0.28
imageimagesD142.jpg 3.68 -0.01
imageimagesD190.jpg 3.69 -0.28
imageimagesD161.jpg 3.69 -0.34
imageimagesD203.jpg 3.70 -0.15
imageimagesD224.jpg 3.72 -0.23
imageimagesD61.jpg 3.72 -0.42
imageimagesD205.jpg 3.74 -0.08
imageimagesD235.jpg 3.75 -0.11
imageimagesD146.jpg 3.75 -0.34
imageimagesD193.jpg 3.76 -0.10
imageimagesD250.jpg 3.76 -0.34
imageimagesD176.jpg 3.76 -0.44
imageimagesD19.jpg 3.76 -0.26
imageimagesD178.jpg 3.77 -0.22
imageimagesD186.jpg 3.78 -0.39
imageimagesD154.jpg 3.78 -0.53
imageimagesD3.jpg 3.78 -0.36
imageimagesD13.jpg 3.79 -0.36
imageimagesD167.jpg 3.79 -0.38
imageimagesD166.jpg 3.80 -0.36
imageimagesD145.jpg 3.81 -0.17
imageimagesD163.jpg 3.81 -0.44
imageimagesD179.jpg 3.82 -0.31
imageimagesD183.jpg 3.83 -0.38
imageimagesD133.jpg 3.83 -0.33
imageimagesD243.jpg 3.84 -0.17
imageimagesD51.jpg 3.84 -0.27
imageimagesD234.jpg 3.84 -0.20
imageimagesD158.jpg 3.85 -0.31
imageimagesD64.jpg 3.85 -0.34
imageimagesD143.jpg 3.87 -0.41
imageimagesD196.jpg 3.87 -0.39
imageimagesD175.jpg 3.87 -0.34
imageimagesD228.jpg 3.87 -0.33
imageimagesD52.jpg 3.88 -0.29
imageimagesD182.jpg 3.88 -0.33
imageimagesD168.jpg 3.88 -0.58
imageimagesD172.jpg 3.89 -0.31
imageimagesD2.jpg 3.89 -0.25
imageimagesD240.jpg 3.90 -0.26
imageimagesD155.jpg 3.90 -0.43
imageimagesD156.jpg 3.91 -0.44
imageimagesD191.jpg 3.91 -0.22
imageimagesD153.jpg 3.91 -0.25
imageimagesD35.jpg 3.91 -0.47
imageimagesD141.jpg 3.92 -0.42
imageimagesD137.jpg 3.92 -0.36
imageimagesD173.jpg 3.93 -0.36
imageimagesD132.jpg 3.93 -0.17
imageimagesD215.jpg 3.93 -0.17
imageimagesD135.jpg 3.94 -0.43
imageimagesD187.jpg 3.95 -0.38
imageimagesD157.jpg 3.95 -0.26
imageimagesD159.jpg 3.95 -0.59
imageimagesD244.jpg 3.95 -0.25
imageimagesD12.jpg 3.97 -0.42
imageimagesD59.jpg 3.97 -0.29
imageimagesD210.jpg 3.97 -0.38
imageimagesD54.jpg 3.97 -0.36
imageimagesD222.jpg 3.97 -0.27
imageimagesD171.jpg 3.97 -0.35
imageimagesD49.jpg 3.98 -0.01
imageimagesD46.jpg 3.98 -0.30
imageimagesD169.jpg 3.99 -0.45
imageimagesD24.jpg 3.99 -0.49
imageimagesD195.jpg 3.99 -0.55
imageimagesD226.jpg 3.99 -0.17
imageimagesD48.jpg 4.00 -0.34
imageimagesD177.jpg 4.00 -0.16
imageimagesD223.jpg 4.00 -0.50
imageimagesD200.jpg 4.02 -0.36
imageimagesD252.jpg 4.02 -0.23
imageimagesD17.jpg 4.03 -0.55
imageimagesD29.jpg 4.04 -0.33
imageimagesD56.jpg 4.04 -0.37
imageimagesD22.jpg 4.05 -0.30
imageimagesD162.jpg 4.05 -0.72
imageimagesD47.jpg 4.07 -0.49
imageimagesD184.jpg 4.07 -0.46
imageimagesD246.jpg 4.08 0.08
imageimagesD53.jpg 4.08 -0.71
imageimagesD20.jpg 4.09 -0.47
imageimagesD134.jpg 4.10 -0.40
imageimagesD4.jpg 4.10 -0.24
imageimagesD229.jpg 4.10 -0.25
imageimagesD129.jpg 4.10 -0.39
One example of this could be
imageimagesD246.jpg 4.08 0.08
imageimagesD53.jpg 4.08 -0.71
|
c319e67644db5a2e7a9f6491ff8bd0f1
|
{
"intermediate": 0.3500218987464905,
"beginner": 0.4607546627521515,
"expert": 0.18922346830368042
}
|
10,682
|
Can you give me an example of N+1 problem in sequalize ORM?
|
a3c5bfddd1cc8dc638c3d4dee6553f21
|
{
"intermediate": 0.2744613289833069,
"beginner": 0.0906265377998352,
"expert": 0.6349120736122131
}
|
10,683
|
Can you give me an example of N+1 problem in sequalize ORM?
|
f1ea414a4154178c51b22c0670b09616
|
{
"intermediate": 0.2744613289833069,
"beginner": 0.0906265377998352,
"expert": 0.6349120736122131
}
|
10,684
|
Ich möchte für die Anfahrt ans Klinikum PatientAppCard genau die gleiche Funktionalität haben wie für E-Mail und Phone. Es soll createMapPermissionGuardCallback und createLaunchMapCallback verwendet werden.
class NavigationLauncher extends StatelessWidget {
const NavigationLauncher(
{Key? key, required this.geoLabel, required this.geoLocation})
: super(key: key);
final String geoLabel;
final Position geoLocation;
@override
Widget build(BuildContext context) {
AppLocalizations l10n = AppLocalizations.of(context)!;
return PatientAppCard(
action: LauncherExpert.createLaunchMapCallback(geoLabel, geoLocation),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
l10n.appointmentDetailsLocationMapHeader,
style: Theme.of(context).textTheme.displaySmall,
),
const SizedBox(height: theme.atomSpacing),
Text(l10n.appointmentDetailsLocationMapAction)
],
),
),
const Icon(Icons.location_on_outlined,
color: theme.defaultIconCardColor),
],
),
);
}
}
und so soll es umgesetzt werden.
Widget _buildTelephone(BuildContext context, String phoneNumber) {
return Column(
children: [
_buildLauncherButton(
Icons.call_outlined,
() => _openPhoneApp(context, phoneNumber),
context,
),
Text(phoneNumber),
],
);
}
Future<void> _openPhoneApp(BuildContext context, String phoneNumber) async {
bool canLaunch =
await LauncherPermissionExpert.createPhonePermissionGuardCallback(
context);
if (canLaunch) {
LauncherExpert.createLaunchTelCallback(phoneNumber)!();
}
}
Widget _buildMail(BuildContext context, String emailAddress) {
return Column(
children: [
_buildLauncherButton(
Icons.email_outlined,
() => _openEMailApp(context, emailAddress),
context,
),
Text(emailAddress),
],
);
}
Future<void> _openEMailApp(BuildContext context, String emailAddress) async {
bool canLaunch =
await LauncherPermissionExpert.createEMailPermissionGuardCallback(
context);
if (canLaunch) {
LauncherExpert.createLaunchEMailCallback(emailAddress)();
}
}
Widget _buildLocation(BuildContext context, String streetName,
String zipCodeAndCity, String? geoLabel, Position? geoLocation) {
return Column(
children: [
_buildLauncherButton(
Icons.place_outlined,
(geoLabel != null && geoLocation != null)
? () => _openMapApp(context, geoLabel, geoLocation)
: () {},
context,
),
Text(
streetName,
textAlign: TextAlign.center,
),
Text(
zipCodeAndCity,
textAlign: TextAlign.center,
),
],
);
}
Future<void> _openMapApp(
BuildContext context, String geoLabel, Position geoLocation) async {
bool canLaunch =
await LauncherPermissionExpert.createMapPermissionGuardCallback(
context);
if (canLaunch) {
LauncherExpert.createLaunchMapCallback(geoLabel, geoLocation)();
}
}
Widget _buildLauncherButton(
IconData iconData,
VoidCallback? onPressedCallback,
BuildContext context,
) {
return PatientAppIconButton(
iconData: iconData,
onPressed: onPressedCallback,
);
}
}
|
91b6e511c3595eaa456871b9017f0d6c
|
{
"intermediate": 0.34089455008506775,
"beginner": 0.34080997109413147,
"expert": 0.3182954788208008
}
|
10,685
|
polish the following words: Work Ethic/Dependability: (Willingness to work, learn and accept responsibility. Trustworthy/maintains confidentiality.)
Comments: Huixin is a highly dependable team member, she can work independently with minimal guidance, she exhibited a willingness to learn and accept responsibility on the new challenge.
|
ae00707a9ba5f225e95db79e9ee55702
|
{
"intermediate": 0.29183414578437805,
"beginner": 0.24505886435508728,
"expert": 0.4631069600582123
}
|
10,686
|
im trying to write to the localconfig.vdf file to create my own collection or grouping of games how would i do this? is this the correct file to do so? im on arch linux and steam is installed in its default location?
|
ad71cd7ffaedc6a3dce7f465ee33fda7
|
{
"intermediate": 0.5759045481681824,
"beginner": 0.21729715168476105,
"expert": 0.20679828524589539
}
|
10,687
|
pyqt 中 treewview怎么设置 checbox
|
9d274ed43868186f7c3f192d6c4cc18a
|
{
"intermediate": 0.3005129396915436,
"beginner": 0.31826022267341614,
"expert": 0.38122689723968506
}
|
10,688
|
i'm using node.js to make web requests. I'm getting this error "requests Error: write EPIPE"
|
0c1c9a6500009042052dc228ad9dc693
|
{
"intermediate": 0.45242568850517273,
"beginner": 0.20128989219665527,
"expert": 0.346284419298172
}
|
10,689
|
hi
|
d344300c0eb80df2bd7decf509c7d9d7
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,690
|
cmakelist中定义一个宏来控制include_directories、link_directories和target_link_libraries中的一些库需不需要编译
|
70750090606c9ed1f541cd1da9abc615
|
{
"intermediate": 0.5074960589408875,
"beginner": 0.2091434746980667,
"expert": 0.28336045145988464
}
|
10,691
|
how to generate a version 2 certificate using openssl
|
436175d87f31cc043286d40bb031655f
|
{
"intermediate": 0.2930043339729309,
"beginner": 0.2901224195957184,
"expert": 0.4168732464313507
}
|
10,692
|
Echarts title的文字大小
|
13c46e450dacf333fedd26ff351aedce
|
{
"intermediate": 0.3376387357711792,
"beginner": 0.27568528056144714,
"expert": 0.38667595386505127
}
|
10,693
|
write a script to upload data from python aiohttp document urls
|
147368e0a95b15371f70e2f50dfbfe49
|
{
"intermediate": 0.5715954303741455,
"beginner": 0.10505673289299011,
"expert": 0.32334789633750916
}
|
10,694
|
cmakelist中定义一个宏来控制include_directories、link_directories和target_link_libraries中的一些库需不需要编译
|
7b94c28d6343dd39af4b55afa5a938ff
|
{
"intermediate": 0.5074960589408875,
"beginner": 0.2091434746980667,
"expert": 0.28336045145988464
}
|
10,695
|
How to use multiplie souncloud track in author profile page?
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
if (typeof req.body.soundcloud === 'string') {
musician.soundcloud = [req.body.soundcloud];
} else {
musician.soundcloud = req.body.soundcloud || [];
}
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<% if (Array.isArray(musician.soundcloud)) { %>
<% musician.soundcloud.forEach(function(url) { %>
<iframe width="100%" height="300" scrolling="no" frameborder="no" allow="autoplay" src="https://w.soundcloud.com/player/?url=<%= url %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% }); %>
<% } %>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">SoundCloud:</label>
<div id="music-fields">
<% if (musician.soundcloud) { %>
<% if (Array.isArray(musician.soundcloud)) { musician.soundcloud.forEach(function(url) { %>
<div>
<input type="text" name="soundcloud[]" value="<%= url %>">
<button type="button" class="delete-music-button">×</button>
</div>
<% }); %> <!-- Add this closing tag -->
<% } %>
<% } %>
<div>
<input type="text" name="soundcloud" value="<%= musician.soundcloud %>" placeholder="Soundcloud track URL">
<button type="button" class="add-music-button">Add Music</button>
</div>
</div>
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
const musicFields = document.getElementById("music-fields");
const addMusicButton = document.querySelector(".add-music-button");
addMusicButton.addEventListener("click", (event) => {
event.preventDefault();
const musicField = document.createElement("div");
musicField.innerHTML = '<br/> <input type="text" name="soundcloud[]" placeholder="SoundCloud track URL"><br/> <button type="button" class="delete-music-button">×</button><br/>';
musicFields.insertBefore(musicField, addMusicButton.parentNode);
});
musicFields.addEventListener("click", (event) => {
if (event.target.classList.contains("delete-music-button")) {
event.preventDefault();
event.target.parentNode.remove();
}
});
</script>
</body>
</html>
user data (include soundcloud link) storoed in musicians.json:
{"musicians":[{"id":1,"name":"sukaAAAAAAA","genre":"BluesZ","instrument":"Guitar","soundcloud":"http://soundcloud.com/dasdasdasd","password":"password123","location":"New York","login":"suka","bio":""},{"id":2,"name":"Aerosmith111114446","genre":"Blues","password":"1111","location":"EnglandDdD","thumbnail":"musician_2_jX7hQvfoT2g (2).jpg","instrument":"","bio":"","soundcloud":["https://soundcloud.com/ty-segall-official/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"}]}
Now i have feature with adding only one song, but i have few fields for song: <label for="soundcloud">SoundCloud:</label>
<div id="music-fields">
<% if (musician.soundcloud) { %>
<% if (Array.isArray(musician.soundcloud)) { musician.soundcloud.forEach(function(url) { %>
<div>
<input type="text" name="soundcloud[]" value="<%= url %>">
<button type="button" class="delete-music-button">×</button>
</div>
<% }); %> <!-- Add this closing tag -->
<% } %>
<% } %>
<div>
<input type="text" name="soundcloud" value="<%= musician.soundcloud %>" placeholder="Soundcloud track URL">
<button type="button" class="add-music-button">Add Music</button>
in musicians.json soundcloud saves only one track, check musicians.json
|
bd0e10db47b479551a05b668fd503cfe
|
{
"intermediate": 0.4310203790664673,
"beginner": 0.42189648747444153,
"expert": 0.14708317816257477
}
|
10,696
|
Error: Cannot find module 'D:\BS\BSSource\FEDevelopment\DataManager\front-end\node_modules\webpack-dev-server\bin\webpack-dev-server.js
|
2851441b5db9442bcb4b30e5efead020
|
{
"intermediate": 0.5202831625938416,
"beginner": 0.274262934923172,
"expert": 0.20545390248298645
}
|
10,697
|
How to use multiplie souncloud tracks in author profile page? Now i have feature with adding only one song, but i have few fields for song (music-fields). in musicians.json (where i stored username, passwords and profile data) soundcloud saves only one track, check musicians.json, there i have only one field for soundcloud tracks:
"soundcloud":["https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing"]},
there is the full code:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
if (typeof req.body.soundcloud === 'string') {
musician.soundcloud = [req.body.soundcloud];
} else {
musician.soundcloud = req.body.soundcloud || [];
}
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<% if (Array.isArray(musician.soundcloud)) { %>
<% musician.soundcloud.forEach(function(url) { %>
<iframe width="100%" height="300" scrolling="no" frameborder="no" allow="autoplay" src="https://w.soundcloud.com/player/?url=<%= url %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% }); %>
<% } %>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">SoundCloud:</label>
<div id="music-fields">
<% if (musician.soundcloud) { %>
<% if (Array.isArray(musician.soundcloud)) { musician.soundcloud.forEach(function(url) { %>
<div>
<input type="text" name="soundcloud[]" value="<%= url %>">
<button type="button" class="delete-music-button">×</button>
</div>
<% }); %> <!-- Add this closing tag -->
<% } %>
<% } %>
<div>
<input type="text" name="soundcloud" value="<%= musician.soundcloud %>" placeholder="Soundcloud track URL">
<button type="button" class="add-music-button">Add Music</button>
</div>
</div>
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
const musicFields = document.getElementById("music-fields");
const addMusicButton = document.querySelector(".add-music-button");
addMusicButton.addEventListener("click", (event) => {
event.preventDefault();
const musicField = document.createElement("div");
musicField.innerHTML = '<br/> <input type="text" name="soundcloud[]" placeholder="SoundCloud track URL"><br/> <button type="button" class="delete-music-button">×</button><br/>';
musicFields.insertBefore(musicField, addMusicButton.parentNode);
});
musicFields.addEventListener("click", (event) => {
if (event.target.classList.contains("delete-music-button")) {
event.preventDefault();
event.target.parentNode.remove();
}
});
</script>
</body>
</html>
musicians.json:
{"musicians":[{"id":1,"name":"sukaAAAAAAA","genre":"BluesZ","instrument":"Guitar","soundcloud":"http://soundcloud.com/dasdasdasd","password":"password123","location":"New York","login":"suka","bio":""},{"id":2,"name":"Aerosmith111114446","genre":"Blues","password":"1111","location":"EnglandDdD","thumbnail":"musician_2_jX7hQvfoT2g (2).jpg","instrument":"","bio":"","soundcloud":["https://soundcloud.com/ty-segall-official/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"}]}
|
b5ec0449208bff4f61e0731d42c9c8c2
|
{
"intermediate": 0.3517462909221649,
"beginner": 0.4073815941810608,
"expert": 0.2408720850944519
}
|
10,698
|
File_name = 'd:\lion\python\ogkb_220101_230531.txt'
with open(File_name, mode='r') as f
SyntaxError: incomplete input
|
299e932622d60d80531a967056c731d9
|
{
"intermediate": 0.27748844027519226,
"beginner": 0.47172877192497253,
"expert": 0.2507827579975128
}
|
10,699
|
I have this react query hook:
import { useTranslation } from 'react-i18next';
import { getListCompetitionsAPI } from 'api/ManualActionsAPI';
import { activityLogHooks } from 'constants/ActivityLog';
import { BranchStatus } from 'models/BranchStatus';
import { Competition } from 'models/Competition';
import { pleaseTryAgainMessage } from 'utils/Context';
import { useQueryWrapper } from '../shared';
interface UseListCompetitionsInterface {
result: Competition[];
status: BranchStatus;
}
export const useListCompetitions = (
sportId: number,
): UseListCompetitionsInterface => {
const { t } = useTranslation();
const { result, branchStatus: status } = useQueryWrapper<
Competition[],
number
>(
[activityLogHooks.listAudits, sportId],
() => getListCompetitionsAPI(sportId),
{
meta: {
errorMessage: pleaseTryAgainMessage(t, 'listing the competitions'),
},
enabled: !!sportId,
},
);
return { result, status };
};
This is the useQueryWrapper:
import {
QueryFunction,
QueryObserverResult,
QueryStatus,
RefetchOptions,
RefetchQueryFilters,
UseQueryOptions,
useQuery,
} from '@tanstack/react-query';
import { BranchStatus } from 'models/BranchStatus';
const queryStatusToBranchStatus: Record<
QueryStatus | 'loading' | 'error' | 'success' | 'idle',
BranchStatus
> = {
success: BranchStatus.FINISHED,
loading: BranchStatus.LOADING,
error: BranchStatus.ERROR,
idle: BranchStatus.IDLE,
};
interface UseQueryWrapperInterface<T> {
result: T;
branchStatus: BranchStatus;
refetch: <TPageData>(
options?: (RefetchOptions & RefetchQueryFilters<TPageData>) | undefined,
) => Promise<QueryObserverResult>;
}
export const useQueryWrapper = <T, K>(
key: string[] | [string, K],
func: QueryFunction<T>,
opts?: UseQueryOptions<T>,
): UseQueryWrapperInterface<T> => {
const { data, status, refetch } = useQuery<T>(key, func, opts);
const result = data as T;
const branchStatus = queryStatusToBranchStatus[status];
return { result, branchStatus, refetch };
};
When running this unit test:
it('should handle fetch failure', async () => {
(getListCompetitionsAPI as jest.Mock).mockImplementationOnce(() =>
Promise.reject('Error'),
);
const { result } = renderHook(() => useListCompetitions(sportId), {
wrapper: ({ children }) => (
<QueryClientProvider client={queryClient}>
{children}
</QueryClientProvider>
),
});
await waitFor(() => {
expect(getListCompetitionsAPI).toHaveBeenCalled();
expect(result.current.status).toBe('error');
});
});
I get this error:
Expected: "error"
Received: "loading"
|
87e3e2ec9f697e84b30bd68cc5d9517d
|
{
"intermediate": 0.3285401165485382,
"beginner": 0.3972857892513275,
"expert": 0.2741740643978119
}
|
10,700
|
How to use multiplie souncloud tracks in author profile page? Now i have feature with adding only one song, but i have few fields for song (music-fields in profile.ejs). in musicians.json (where i stored username, passwords and profile data) soundcloud saves only one track, check musicians.json, there i have only one field for soundcloud tracks:
"soundcloud":["https://soundcloud.com/ty-segall-official/my-ladys-on-fire?si=55e4a9622a824ddeb3e725dfa2c41d1d&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing"]},
there is the full code:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
function getMusicianById(id) {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
return musicians.musicians.find(musician => musician.id === id);
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
function search(query) {
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data).musicians.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud
};
});
let results = musicians;
if (query) {
const lowerQuery = query.toLowerCase();
results = musicians.filter(musician => {
const nameScore = musician.name.toLowerCase().startsWith(lowerQuery) ? 2 : musician.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const genreScore = musician.genre.toLowerCase().startsWith(lowerQuery) ? 2 : musician.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return nameScore + genreScore > 0;
}).sort((a, b) => {
const aNameScore = a.name.toLowerCase().startsWith(lowerQuery) ? 2 : a.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bNameScore = b.name.toLowerCase().startsWith(lowerQuery) ? 2 : b.name.toLowerCase().includes(lowerQuery) ? 1 : 0;
const aGenreScore = a.genre.toLowerCase().startsWith(lowerQuery) ? 2 : a.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
const bGenreScore = b.genre.toLowerCase().startsWith(lowerQuery) ? 2 : b.genre.toLowerCase().includes(lowerQuery) ? 1 : 0;
return (bNameScore + bGenreScore) - (aNameScore + aGenreScore);
});
}
return results;
}
app.use((req, res, next) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
res.render("index", { musicians: musicians.musicians });
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register");
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const newMusician = {
id: musicians.musicians.length + 1,
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
location: req.body.location,
login: req.body.login
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + newMusician.id + "_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
musicians.musicians.push(newMusician);
fs.writeFileSync("./db/musicians.json", JSON.stringify(musicians));
req.session.musicianId = newMusician.id;
res.redirect("/profile/" + newMusician.id);
}
});
app.get("/profile/:id", (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
res.render("profile", { musician: musician });
} else {
res.status(404).send("Musician not found");
}
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
const data = fs.readFileSync("./db/musicians.json");
const musicians = JSON.parse(data);
const musician = musicians.musicians.find(musician => musician.login === req.body.login && musician.password === req.body.password);
if (musician) {
req.session.musicianId = musician.id;
res.redirect("/profile/" + musician.id);
} else {
res.render("login", { error: "Invalid login or password" });
}
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
const query = req.query.query || '';
const musicians = search(query);
res.locals.predefinedGenres = predefinedGenres;
res.render('search', { musicians, query });
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
});
app.post('/profile/:id/edit', requireLogin, (req, res) => {
const musician = getMusicianById(parseInt(req.params.id));
if (musician) {
if (!req.body.name || !req.body.genre) {
res.status(400).send('Please fill out all fields');
} else {
musician.name = req.body.name;
musician.genre = req.body.genre;
musician.instrument = req.body.instrument;
if (typeof req.body.soundcloud === 'string') {
musician.soundcloud = [req.body.soundcloud];
} else {
musician.soundcloud = req.body.soundcloud || [];
}
musician.location = req.body.location;
musician.bio = req.body.bio;
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = 'musician_' + musician.id + '_' + file.name;
file.mv('./public/img/' + filename);
musician.thumbnail = filename;
}
const data = fs.readFileSync('./db/musicians.json');
const musicians = JSON.parse(data);
const index = musicians.musicians.findIndex(m => m.id === musician.id);
musicians.musicians[index] = musician;
fs.writeFileSync('./db/musicians.json', JSON.stringify(musicians));
res.redirect('/profile/' + musician.id);
}
} else {
res.status(404).send('Musician not found');
}
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
</head>
<body>
<img src="/img/<%= musician.thumbnail %>" alt="<%= musician.name %>">
<h1><%= musician.name %></h1>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<% if (Array.isArray(musician.soundcloud)) { %>
<% musician.soundcloud.forEach(function(url) { %>
<iframe width="100%" height="300" scrolling="no" frameborder="no" allow="autoplay" src="https://w.soundcloud.com/player/?url=<%= url %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
<% }); %>
<% } %>
<% if (userLoggedIn && username === musician.name) { %>
<a href="/profile/<%= musician.id %>/edit">Edit profile</a>
<div id="edit-profile-modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Profile</h2>
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>">
</div>
<div>
<label for="genre">Genre:</label>
<input type="text" id="genre" name="genre" value="<%= musician.genre %>">
</div>
<div>
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument %>">
</div>
<div>
<label for="location">Location:</label>
<input type="text" id="location" name="location" value="<%= musician.location %>">
</div>
<div>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio"><%= musician.bio %></textarea>
</div>
<div>
<label for="soundcloud">SoundCloud:</label>
<div id="music-fields">
<% if (musician.soundcloud) { %>
<% if (Array.isArray(musician.soundcloud)) { musician.soundcloud.forEach(function(url) { %>
<div>
<input type="text" name="soundcloud[]" value="<%= url %>">
<button type="button" class="delete-music-button">×</button>
</div>
<% }); %> <!-- Add this closing tag -->
<% } %>
<% } %>
<div>
<input type="text" name="soundcloud" value="<%= musician.soundcloud %>" placeholder="Soundcloud track URL">
<button type="button" class="add-music-button">Add Music</button>
</div>
</div>
</div>
<div>
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail">
</div>
<button type="submit">Save</button>
</form>
</div>
</div>
<% } %>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
const musicFields = document.getElementById("music-fields");
const addMusicButton = document.querySelector(".add-music-button");
addMusicButton.addEventListener("click", (event) => {
event.preventDefault();
const musicField = document.createElement("div");
musicField.innerHTML = '<br/> <input type="text" name="soundcloud[]" placeholder="SoundCloud track URL"><br/> <button type="button" class="delete-music-button">×</button><br/>';
musicFields.insertBefore(musicField, addMusicButton.parentNode);
});
musicFields.addEventListener("click", (event) => {
if (event.target.classList.contains("delete-music-button")) {
event.preventDefault();
event.target.parentNode.remove();
}
});
</script>
</body>
</html>
musicians.json:
{"musicians":[{"id":1,"name":"sukaAAAAAAA","genre":"BluesZ","instrument":"Guitar","soundcloud":"http://soundcloud.com/dasdasdasd","password":"password123","location":"New York","login":"suka","bio":""},{"id":2,"name":"Aerosmith111114446","genre":"Blues","password":"1111","location":"EnglandDdD","thumbnail":"musician_2_jX7hQvfoT2g (2).jpg","instrument":"","bio":"","soundcloud":["https://soundcloud.com/ty-segall-official/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"}]}
|
fecbc5d4176816589765327d5802f75c
|
{
"intermediate": 0.386627733707428,
"beginner": 0.4039514660835266,
"expert": 0.20942075550556183
}
|
10,701
|
can you improve this react code <Connect
setIsNextStepAllowed={setIsNextStepAllowed}
nextClicked={nextClicked}
configurationData={configurationData}
setAvailableSenders={setAvailableSenders}
setConfigurationData={setConfigurationData}
setToastMessage={setToastMessage}
/>
|
6d6ab240afdd42c191380c2da6efce8e
|
{
"intermediate": 0.4319213032722473,
"beginner": 0.29280152916908264,
"expert": 0.27527716755867004
}
|
10,702
|
I have the following model estimation structure:
#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': 5, "seed": 123, 'objective': 'binary:logitraw','learning_rate': 0.2,
'min_split_loss': 3, 'eval_metric': 'auc'}, xdm_train, 20, [(xdm_test, 'eval'), (xdm_train, 'train')])
print(model)
I need to add standard scaler in there somehow. Furthermore I want to optimize hyperparameter space using the following code:
def validate(model, X, y, X_test=None, y_test=None, show_results=False):
is_classification = is_classifier(model)
use_cross_validation = X_test is None or y_test is None
if use_cross_validation:
if is_classification:
scoring = "roc_auc"
else:
scoring = "r2"
val_results = cross_validate(model, X, y, scoring=scoring, n_jobs=-1, return_train_score=True, cv=3)
train_score = np.mean(val_results["train_score"])
test_score = np.mean(val_results["test_score"])
else:
model.fit(X, y)
pred_train = model.predict(X)
pred_test = model.predict(X_test)
if is_classification:
train_score = metrics.accuracy_score(y, pred_train)
test_score = metrics.accuracy_score(y_test, pred_test)
if show_results:
plot_confusion_matrix(y_test, pred_test)
else:
train_score = metrics.r2_score(y, pred_train)
test_score = metrics.r2_score(y_test, pred_test)
if show_results:
raw_y_train = exp_y(y)
raw_y_test = exp_y(y_test)
raw_pred_train = exp_y(pred_train)
raw_pred_test = exp_y(pred_test)
plot_pred_data(raw_y_test, raw_pred_test)
print(f"train MAE on y:", metrics.mean_absolute_error(raw_y_train, raw_pred_train))
print(f"test MAE on y:", metrics.mean_absolute_error(raw_y_test, raw_pred_test))
is_overfitted = train_score - test_score > 0.05
if show_results:
if is_classification:
print(f"train acc:", train_score)
print(f"test acc:", test_score)
else:
print(f"train r2 on log y:", train_score)
print(f"test r2 on log y:", test_score)
if is_overfitted:
print("Overfitted")
return test_score, is_overfitted
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_validate
from sklearn.base import is_classifier
def objective(trial):
n_estimators = trial.suggest_int('n_estimators', 15,500)
max_depth=trial.suggest_int('max_depth',1,15)
learning_rate= trial.suggest_float('learning_rate',0,0.3)
subsample= trial.suggest_float('subsample',0,1)
gamma = trial.suggest_float("gamma", 1e-4, 1e2)
reg_alpha=trial.suggest_float('reg_alpha',0,1)
reg_lambda=trial.suggest_float('reg_lambda',0,1)
model= xgboost.DMatrix(X, Y, enable_categorical=True, missing=True)
score, is_overfitted = validate(model, X,Y)
if is_overfitted:
return 0
else:
return score
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=500)
If you think that roc_auc is not the right choice for the problem of credit scoring (binary). ADUJST THE WHOLE CODE so it would work.
|
c6e3ddd1c6d29f25246364dacaef6583
|
{
"intermediate": 0.3216991126537323,
"beginner": 0.3949325978755951,
"expert": 0.283368319272995
}
|
10,703
|
Please give me R code to find rows with similar x1 and a high difference in x2.
> testDF
X1 X2
imageimagesD249.jpg 2.41 -0.06
imageimagesD242.jpg 2.62 -0.02
imageimagesD251.jpg 2.66 0.12
imageimagesD255.jpg 2.68 0.24
imageimagesD198.jpg 2.98 -0.09
imageimagesD239.jpg 3.16 -0.25
imageimagesD9.jpg 3.17 -0.08
imageimagesD219.jpg 3.18 0.07
imageimagesD230.jpg 3.18 -0.14
imageimagesD149.jpg 3.20 -0.32
imageimagesD136.jpg 3.20 -0.04
imageimagesD50.jpg 3.29 -0.37
imageimagesD201.jpg 3.31 -0.06
imageimagesD152.jpg 3.31 -0.33
imageimagesD10.jpg 3.31 -0.46
imageimagesD247.jpg 3.33 -0.11
imageimagesD216.jpg 3.33 -0.18
imageimagesD256.jpg 3.34 -0.16
imageimagesD221.jpg 3.35 -0.01
imageimagesD181.jpg 3.35 -0.45
imageimagesD199.jpg 3.38 -0.23
imageimagesD197.jpg 3.40 -0.19
imageimagesD174.jpg 3.42 -0.25
imageimagesD209.jpg 3.43 0.12
imageimagesD208.jpg 3.43 0.01
imageimagesD238.jpg 3.45 -0.02
imageimagesD160.jpg 3.46 -0.31
imageimagesD16.jpg 3.46 -0.41
imageimagesD233.jpg 3.47 -0.23
imageimagesD140.jpg 3.47 -0.09
imageimagesD18.jpg 3.49 -0.03
imageimagesD180.jpg 3.49 -0.32
imageimagesD14.jpg 3.49 -0.21
imageimagesD248.jpg 3.50 -0.05
imageimagesD212.jpg 3.51 -0.21
imageimagesD165.jpg 3.52 -0.43
imageimagesD170.jpg 3.52 -0.13
imageimagesD138.jpg 3.53 -0.13
imageimagesD189.jpg 3.53 -0.33
imageimagesD185.jpg 3.53 -0.35
imageimagesD236.jpg 3.55 -0.17
imageimagesD151.jpg 3.56 -0.31
imageimagesD194.jpg 3.56 -0.28
imageimagesD164.jpg 3.60 -0.42
imageimagesD144.jpg 3.61 -0.34
imageimagesD1.jpg 3.61 -0.11
imageimagesD147.jpg 3.62 -0.21
imageimagesD43.jpg 3.62 -0.32
imageimagesD202.jpg 3.63 -0.11
imageimagesD204.jpg 3.63 -0.05
imageimagesD150.jpg 3.64 -0.26
imageimagesD131.jpg 3.64 -0.18
imageimagesD237.jpg 3.64 -0.28
imageimagesD211.jpg 3.65 -0.08
imageimagesD188.jpg 3.66 -0.27
imageimagesD241.jpg 3.66 -0.14
imageimagesD139.jpg 3.67 -0.25
imageimagesD62.jpg 3.67 -0.28
imageimagesD142.jpg 3.68 -0.01
imageimagesD190.jpg 3.69 -0.28
imageimagesD161.jpg 3.69 -0.34
imageimagesD203.jpg 3.70 -0.15
imageimagesD224.jpg 3.72 -0.23
imageimagesD61.jpg 3.72 -0.42
imageimagesD205.jpg 3.74 -0.08
imageimagesD235.jpg 3.75 -0.11
imageimagesD146.jpg 3.75 -0.34
imageimagesD193.jpg 3.76 -0.10
imageimagesD250.jpg 3.76 -0.34
imageimagesD176.jpg 3.76 -0.44
imageimagesD19.jpg 3.76 -0.26
imageimagesD178.jpg 3.77 -0.22
imageimagesD186.jpg 3.78 -0.39
imageimagesD154.jpg 3.78 -0.53
imageimagesD3.jpg 3.78 -0.36
imageimagesD13.jpg 3.79 -0.36
imageimagesD167.jpg 3.79 -0.38
imageimagesD166.jpg 3.80 -0.36
imageimagesD145.jpg 3.81 -0.17
imageimagesD163.jpg 3.81 -0.44
imageimagesD179.jpg 3.82 -0.31
imageimagesD183.jpg 3.83 -0.38
imageimagesD133.jpg 3.83 -0.33
imageimagesD243.jpg 3.84 -0.17
imageimagesD51.jpg 3.84 -0.27
imageimagesD234.jpg 3.84 -0.20
imageimagesD158.jpg 3.85 -0.31
imageimagesD64.jpg 3.85 -0.34
imageimagesD143.jpg 3.87 -0.41
imageimagesD196.jpg 3.87 -0.39
imageimagesD175.jpg 3.87 -0.34
imageimagesD228.jpg 3.87 -0.33
imageimagesD52.jpg 3.88 -0.29
imageimagesD182.jpg 3.88 -0.33
imageimagesD168.jpg 3.88 -0.58
imageimagesD172.jpg 3.89 -0.31
imageimagesD2.jpg 3.89 -0.25
imageimagesD240.jpg 3.90 -0.26
imageimagesD155.jpg 3.90 -0.43
imageimagesD156.jpg 3.91 -0.44
imageimagesD191.jpg 3.91 -0.22
imageimagesD153.jpg 3.91 -0.25
imageimagesD35.jpg 3.91 -0.47
imageimagesD141.jpg 3.92 -0.42
imageimagesD137.jpg 3.92 -0.36
imageimagesD173.jpg 3.93 -0.36
imageimagesD132.jpg 3.93 -0.17
imageimagesD215.jpg 3.93 -0.17
imageimagesD135.jpg 3.94 -0.43
imageimagesD187.jpg 3.95 -0.38
imageimagesD157.jpg 3.95 -0.26
imageimagesD159.jpg 3.95 -0.59
imageimagesD244.jpg 3.95 -0.25
imageimagesD12.jpg 3.97 -0.42
imageimagesD59.jpg 3.97 -0.29
imageimagesD210.jpg 3.97 -0.38
imageimagesD54.jpg 3.97 -0.36
imageimagesD222.jpg 3.97 -0.27
imageimagesD171.jpg 3.97 -0.35
imageimagesD49.jpg 3.98 -0.01
imageimagesD46.jpg 3.98 -0.30
imageimagesD169.jpg 3.99 -0.45
imageimagesD24.jpg 3.99 -0.49
imageimagesD195.jpg 3.99 -0.55
imageimagesD226.jpg 3.99 -0.17
imageimagesD48.jpg 4.00 -0.34
imageimagesD177.jpg 4.00 -0.16
imageimagesD223.jpg 4.00 -0.50
imageimagesD200.jpg 4.02 -0.36
imageimagesD252.jpg 4.02 -0.23
imageimagesD17.jpg 4.03 -0.55
imageimagesD29.jpg 4.04 -0.33
imageimagesD56.jpg 4.04 -0.37
imageimagesD22.jpg 4.05 -0.30
imageimagesD162.jpg 4.05 -0.72
imageimagesD47.jpg 4.07 -0.49
imageimagesD184.jpg 4.07 -0.46
imageimagesD246.jpg 4.08 0.08
imageimagesD53.jpg 4.08 -0.71
imageimagesD20.jpg 4.09 -0.47
imageimagesD134.jpg 4.10 -0.40
imageimagesD4.jpg 4.10 -0.24
imageimagesD229.jpg 4.10 -0.25
imageimagesD129.jpg 4.10 -0.39
One example of this could be
imageimagesD246.jpg 4.08 0.08
imageimagesD53.jpg 4.08 -0.71
|
591703a91203f5d589bca44c0dabe6e3
|
{
"intermediate": 0.3600270450115204,
"beginner": 0.41957905888557434,
"expert": 0.22039389610290527
}
|
10,704
|
how can i avoid adding ternary statements like this const icon = type === "SUCCESS" ? successIcon : warningIcon;
const alt = type === "SUCCESS" ? "Success icon" : "Warning icon";
|
9b994dc192cbe066978d8ff4f08ec6e5
|
{
"intermediate": 0.40936753153800964,
"beginner": 0.3640482425689697,
"expert": 0.22658421099185944
}
|
10,705
|
Hi, could you provide an example of aws lambda function which transform RDS data into kinesis stream?
|
de3d2399d8c59c9017d3640bb5c321fb
|
{
"intermediate": 0.5025072693824768,
"beginner": 0.14147554337978363,
"expert": 0.35601717233657837
}
|
10,706
|
في هذا الكود كيف يمكن اختيار صورة من الهاتف ووضع قيمتها مكان قيمة logosendwhats .... logo {
drawable = ContextCompat.getDrawable(this@Qr_generator, R.drawable.logosendwhats)
size = .25f
padding = QrVectorLogoPadding.Natural(.2f)
shape = QrVectorLogoShape
.Circle
}
|
15bfe778fc6805ed7eea2d7248fa86b8
|
{
"intermediate": 0.3953723609447479,
"beginner": 0.3261285722255707,
"expert": 0.27849912643432617
}
|
10,707
|
I want to run this code at gpu import easyocr
# Define the languages you want to perform OCR in
languages = ['en', 'fr'] # English and French
# Create an EasyOCR reader object
reader = easyocr.Reader(languages)
# Provide the path to an image file you want to extract text from
image_path = 'test.png'
print('_____________________________________________________________________')
results = reader.readtext(image_path, detail=1, paragraph=False)
# Print the extracted text and its bounding box coordinates
for result in results:
text = result[1] # Extract the text from the second element of the tuple
bbox = result[0] # Extract the bounding box from the first element of the tuple
print(f'Text: {text}')
print(f'Bounding Box: {bbox}')
print(), using vscodee, I have 2 version of cuda 11.5 and 12.1 ; how can do everything from 0 point to end
|
8e0802cba0f8e1721df1738e5c22e9eb
|
{
"intermediate": 0.6030725836753845,
"beginner": 0.1487451046705246,
"expert": 0.24818237125873566
}
|
10,708
|
Add to this OneHotEncoder with infrequent_if_exist to this:
def objective(trial):
n_estimators = trial.suggest_int('n_estimators', 15,1000)
max_depth = trial.suggest_int('max_depth', 1,20)
learning_rate = trial.suggest_float('learning_rate', 0,0.5)
subsample = trial.suggest_float('subsample', 0,1)
gamma = trial.suggest_float("gamma", 1e-4, 1e2)
reg_alpha = trial.suggest_float('reg_alpha', 0,1)
reg_lambda = trial.suggest_float('reg_lambda', 0,1)
pipeline = Pipeline([
('scaler', StandardScaler()),
('xgb', XGBClassifier(
n_estimators=n_estimators,
max_depth=max_depth,
learning_rate=learning_rate,
subsample=subsample,
gamma=gamma,
reg_alpha=reg_alpha,
reg_lambda=reg_lambda,
eval_metric='auc'
))
])
score, is_overfitted = validate(pipeline, X, Y)
if is_overfitted:
return 0
else:
return score
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=500)
so it would make sense with standarscaler.
|
0daa5151704e690912f4b53d7317de3e
|
{
"intermediate": 0.324476420879364,
"beginner": 0.2761383354663849,
"expert": 0.3993852436542511
}
|
10,709
|
Представь что ты программист Django. У меня есть методы отправки подтверждения юзера по номеру телефона:
class SendOrResendSMSAPIView(GenericAPIView):
"""
Check if submitted phone number is a valid phone number and send OTP.
"""
serializer_class = PhoneNumberSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
# Send OTP
phone_number = str(serializer.validated_data['phone_number'])
user = CustomUser.objects.filter(
phone__phone_number=phone_number).first()
sms_verification = PhoneNumber.objects.filter(
user=user, is_verified=False).first()
sms_verification.send_confirmation()
return Response(status=status.HTTP_200_OK)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
и метод отправки подтверждения юзера по email:
from dj_rest_auth.registration.views import ResendEmailVerificationView
Нужно переписать логику обновления у юзера email, phone_number, first_name и last_name. У меня для этого есть модель юзера:
class CustomUser(AbstractUser):
APPLICANT = "Applicant"
EMPLOYER = "Employer"
ROLE_CHOICES = (
(APPLICANT, "Applicant"),
(EMPLOYER, "Employer"),
)
username = models.CharField(max_length=255, unique=True, blank=True, null=True)
email = models.EmailField(_("email address"), unique=False, max_length=254, blank=True,null=True)
role = models.CharField(max_length=50, choices=ROLE_CHOICES)
avatar = models.ImageField(_("avatar"), upload_to="avatars/", null=True, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
blocked_until = models.DateTimeField(null=True, blank=True)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
@property
def fullname(self):
return f"{self.first_name} {self.last_name}"
модель телефона:
class PhoneNumber(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.OneToOneField(CustomUser, related_name='phone', on_delete=models.CASCADE)
phone_number = PhoneNumberField(unique=True)
security_code = models.CharField(max_length=120)
is_verified = models.BooleanField(default=False)
sent = models.DateTimeField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created_at', )
def __str__(self):
return self.phone_number.as_e164
def generate_security_code(self):
"""
Returns a unique random `security_code` for given `TOKEN_LENGTH` in the settings.
Default token length = 6
"""
token_length = getattr(base, "TOKEN_LENGTH", 6)
return get_random_string(token_length, allowed_chars="0123456789")
def is_security_code_expired(self):
expiration_date = self.sent + datetime.timedelta(
minutes=base.TOKEN_EXPIRE_MINUTES
)
return expiration_date <= timezone.now()
def send_confirmation(self):
twilio_account_sid = base.TWILIO_ACCOUNT_SID
twilio_auth_token = base.TWILIO_AUTH_TOKEN
twilio_phone_number = base.TWILIO_PHONE_NUMBER
self.security_code = self.generate_security_code()
# print(
# f'Sending security code {self.security_code} to phone {self.phone_number}')
if all(
[
twilio_account_sid,
twilio_auth_token,
twilio_phone_number
]
):
try:
twilio_client = Client(
twilio_account_sid, twilio_auth_token
)
twilio_client.messages.create(
body=f'Your activation code is {self.security_code}',
to=str(self.phone_number),
from_=twilio_phone_number,
)
self.sent = timezone.now()
self.save()
return True
except TwilioRestException as e:
print(e)
else:
print("Twilio credentials are not set")
def check_verification(self, security_code):
if (
not self.is_security_code_expired() and
security_code == self.security_code and
self.is_verified == False
):
self.is_verified = True
self.save()
else:
raise NotAcceptable(
_("Your security code is wrong, expired or this phone is verified before."))
return self.is_verified
сериализатор обновления номера телефона:
class PhoneNumberUpdateSerializer(serializers.ModelSerializer):
class Meta:
model = PhoneNumber
fields = ('phone_number',)
сериализатор обновления юзера:
class UserUpdateSerializer(serializers.ModelSerializer):
phone = PhoneNumberUpdateSerializer()
class Meta:
model = CustomUser
fields = ('email', 'first_name', 'last_name', 'phone')
def update(self, instance, validated_data):
if 'email' in validated_data:
instance.email = validated_data['email']
if 'first_name' in validated_data:
instance.first_name = validated_data['first_name']
if 'last_name' in validated_data:
instance.last_name = validated_data['last_name']
if 'phone' in validated_data:
phone_data = validated_data.pop('phone')
phone = instance.phone
if not phone:
phone = PhoneNumber(user=instance)
for key, value in phone_data.items():
setattr(phone, key, value)
phone.save()
instance.save()
return instance
и представление обновления юзера, которое вызывает ошибку: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.
представление:
class UserUpdateApi(generics.UpdateAPIView):
serializer_class = UserUpdateSerializer
def get_object(self):
return self.request.user
def _send_sms(self, request, *args, **kwargs):
res = SendOrResendSMSAPIView.as_view()(request._request, *args, **kwargs)
return res.status_code == 200
def _send_email_verification(self, request, *args, **kwargs):
res = ResendEmailVerificationView.as_view()(request._request, *args, **kwargs)
return res.status_code == 200
def _send_verification_messages(self, request, email, phone, *args, **kwargs):
response_data = {}
if phone:
phone_data = request.data.get('phone', {})
phone_serializer = PhoneNumberUpdateSerializer(phone, data=phone_data, partial=True)
if phone_serializer.is_valid(raise_exception=True):
phone_serializer.save()
response_data['phone'] = phone_serializer.data
if email:
if self._send_email_verification(request, *args, **kwargs):
response_data['email'] = {'detail': _('Verification e-mail sent.')}
if phone and self._send_sms(request, *args, **kwargs):
message = _('Verification e-mail and SMS sent.')
elif not phone and email:
message = _('Verification e-mail sent.')
elif phone and not email:
message = _('Verification SMS sent.')
if self._send_sms(request, *args, **kwargs):
response_data['detail'] = message
elif not phone and not email:
message = _('No verification method specified.')
else:
message = _('Verification e-mail and SMS sent.')
response_data['detail'] = message
return response_data
def update(self, request, *args, **kwargs):
response_data = {}
user = self.get_object()
phone = user.phone if hasattr(user, 'phone') else None
email = request.data.get('email', None)
serializer = self.get_serializer(user, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
response_data.update(self._send_verification_messages(request, email, phone, *args, **kwargs))
return Response({**serializer.data, **response_data}, status=status.HTTP_200_OK)
Нужно переписать код таким образом, чтоб любые поля юзера обновлялись без ошибок и отправлялись в зависимости от обновляемого поля подтверждения по смс либо email.
|
89ea9cc10a3576cc93b22aa88182a09c
|
{
"intermediate": 0.3121734857559204,
"beginner": 0.4183618724346161,
"expert": 0.2694646120071411
}
|
10,710
|
please provide me C# code that converts JsonElement to object. This function should check JsonElement ValueKind property and return JsonElement value via GetString(), GetDecimal() and other methods
|
b3a869792f2e8d98e567ad75fe8ecfd2
|
{
"intermediate": 0.5989317297935486,
"beginner": 0.2552363872528076,
"expert": 0.145831897854805
}
|
10,711
|
При обновлении юзера, мне выдает ошибку:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.9/contextlib.py", line 79, in inner
return func(*args, **kwds)
File "/usr/local/lib/python3.9/site-packages/django/db/transaction.py", line 290, in __exit__
connection.set_autocommit(True)
File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 431, in set_autocommit
self.run_and_clear_commit_hooks()
File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 664, in run_and_clear_commit_hooks
func()
File "/app/authentication/api/users.py", line 275, in <lambda>
transaction.on_commit(lambda: self._send_email_verification(self.request.user))
File "/app/authentication/api/users.py", line 259, in _send_email_verification
res = ResendEmailVerificationView.as_view()(request._request, *args, **kwargs)
Exception Type: AttributeError at /user/user-update/
Exception Value: 'CustomUser' object has no attribute '_request'
Вот мое представление:
class UserUpdateApi(generics.UpdateAPIView):
serializer_class = UserUpdateSerializer
def get_object(self):
return self.request.user
def _send_sms(self, request, *args, **kwargs):
res = SendOrResendSMSAPIView.as_view()(request._request, *args, **kwargs)
return res.status_code == 200
def _send_email_verification(self, request, *args, **kwargs):
res = ResendEmailVerificationView.as_view()(request._request, *args, **kwargs)
return res.status_code == 200
def _send_verification_messages(self, email, phone, *args, **kwargs):
response_data = {}
sent_sms = False
sent_email = False
email = self.request.data.get("email")
phone_data = self.request.data.get("phone")
phone_number = phone_data["phone_number"] if phone_data else None
if phone_number:
transaction.on_commit(lambda: self._send_sms(phone_number))
sent_sms = True
if email:
transaction.on_commit(lambda: self._send_email_verification(self.request.user))
sent_email = True
if sent_sms and sent_email:
message = _('Verification e-mail and SMS sent.')
elif sent_sms:
message = _('Verification SMS sent.')
elif sent_email:
message = _('Verification e-mail sent.')
else:
message = _('No verification method specified.')
response_data['detail'] = message
return response_data
def update(self, request, *args, **kwargs):
response_data = {}
user = self.get_object()
phone = user.phone if hasattr(user, 'phone') else None
email = request.data.get('email', None)
serializer = self.get_serializer(user, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
response_data.update(self._send_verification_messages(request, email, phone, *args, **kwargs))
return Response({**serializer.data, **response_data}, status=status.HTTP_200_OK)
Вот моя модель юзера:
class CustomUser(AbstractUser):
APPLICANT = "Applicant"
EMPLOYER = "Employer"
ROLE_CHOICES = (
(APPLICANT, "Applicant"),
(EMPLOYER, "Employer"),
)
username = models.CharField(max_length=255, unique=True, blank=True, null=True)
email = models.EmailField(_("email address"), unique=False, max_length=254, blank=True,null=True)
role = models.CharField(max_length=50, choices=ROLE_CHOICES)
avatar = models.ImageField(_("avatar"), upload_to="avatars/", null=True, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
blocked_until = models.DateTimeField(null=True, blank=True)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = []
objects = UserManager()
def __str__(self):
return self.email
@property
def fullname(self):
return f"{self.first_name} {self.last_name}"
Вот модель телефона:
class PhoneNumber(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.OneToOneField(CustomUser, related_name='phone', on_delete=models.CASCADE)
phone_number = PhoneNumberField(unique=True)
security_code = models.CharField(max_length=120)
is_verified = models.BooleanField(default=False)
sent = models.DateTimeField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created_at', )
def __str__(self):
return self.phone_number.as_e164
def generate_security_code(self):
"""
Returns a unique random `security_code` for given `TOKEN_LENGTH` in the settings.
Default token length = 6
"""
token_length = getattr(base, "TOKEN_LENGTH", 6)
return get_random_string(token_length, allowed_chars="0123456789")
def is_security_code_expired(self):
expiration_date = self.sent + datetime.timedelta(
minutes=base.TOKEN_EXPIRE_MINUTES
)
return expiration_date <= timezone.now()
def send_confirmation(self):
twilio_account_sid = base.TWILIO_ACCOUNT_SID
twilio_auth_token = base.TWILIO_AUTH_TOKEN
twilio_phone_number = base.TWILIO_PHONE_NUMBER
self.security_code = self.generate_security_code()
# print(
# f'Sending security code {self.security_code} to phone {self.phone_number}')
if all(
[
twilio_account_sid,
twilio_auth_token,
twilio_phone_number
]
):
try:
twilio_client = Client(
twilio_account_sid, twilio_auth_token
)
twilio_client.messages.create(
body=f'Your activation code is {self.security_code}',
to=str(self.phone_number),
from_=twilio_phone_number,
)
self.sent = timezone.now()
self.save()
return True
except TwilioRestException as e:
print(e)
else:
print("Twilio credentials are not set")
def check_verification(self, security_code):
if (
not self.is_security_code_expired() and
security_code == self.security_code and
self.is_verified == False
):
self.is_verified = True
self.save()
else:
raise NotAcceptable(
_("Your security code is wrong, expired or this phone is verified before."))
return self.is_verified
Вот мой сериализатор:
class UserUpdateSerializer(serializers.ModelSerializer):
phone = PhoneNumberUpdateSerializer()
class Meta:
model = CustomUser
fields = ('email', 'first_name', 'last_name', 'phone')
|
471fd221a035bc82059113b330f6d8e9
|
{
"intermediate": 0.2877455949783325,
"beginner": 0.5431730151176453,
"expert": 0.1690814197063446
}
|
10,712
|
Hello
|
654815806b30d45a0f4bba196c2561d8
|
{
"intermediate": 0.3123404085636139,
"beginner": 0.2729349136352539,
"expert": 0.4147246778011322
}
|
10,713
|
nginx: [emerg] bind() to 0.0.0.0:7051 failed (98: Address already in use)怎么解决
|
f29e004667d663a23e308bd2bdb34be8
|
{
"intermediate": 0.3589096665382385,
"beginner": 0.3501940667629242,
"expert": 0.2908962070941925
}
|
10,714
|
https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true;
замени этот плеер на более компактный
|
067e272edf4fcec69fefa435b02bef7e
|
{
"intermediate": 0.3140185475349426,
"beginner": 0.2922128438949585,
"expert": 0.3937686085700989
}
|
10,715
|
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_transactions_from_block(block_number, session):
async with semaphore:
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_newly_created_contracts(start_block, end_block):
contract_list = []
async def process_block(block_number, session):
transactions = await get_transactions_from_block(block_number, session)
return [tx for tx in transactions if 'from' in tx and tx['from'] == filter_address]
async with aiohttp.ClientSession() as session:
tasks = [process_block(hex(block_number), session) for block_number in range(start_block, end_block + 1)]
results = await asyncio.gather(*tasks)
for contracts in results:
contract_list.extend(contracts)
return contract_list
async def display_new_contracts(start_block, end_block):
filter_address = '0x863b49ae97c3d2a87fd43186dfd921f42783c853'
contracts = await get_newly_created_contracts(start_block, end_block)
if not contracts:
print('No new contracts found.')
else:
print(f'Newly created smart contracts between blocks {start_block} and {end_block}: ')
for contract in contracts:
print(f"Block: {contract['blockNumber']} - Address: {contract['contractAddress']}")
async def main():
start_block = 2826940 # Replace with your desired start block
end_block = 2826940 # Replace with your desired end block
await display_new_contracts(start_block, end_block)
asyncio.run(main())
The code above throws an error
C:\Users\AshotxXx\PycharmProjects\UNCX\Project2\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py", line 58, 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\UNCX\Project1\main.py", line 56, in main
await display_new_contracts(start_block, end_block)
File "C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py", line 43, in display_new_contracts
contracts = await get_newly_created_contracts(start_block, end_block)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py", line 34, in get_newly_created_contracts
results = await asyncio.gather(*tasks)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py", line 30, in process_block
return [tx for tx in transactions if 'from' in tx and tx['from'] == filter_address]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\UNCX\Project1\main.py", line 30, in <listcomp>
return [tx for tx in transactions if 'from' in tx and tx['from'] == filter_address]
^^^^^^^^^^^^^^
NameError: name 'filter_address' is not defined
Process finished with exit code 1
Fix it
|
f84838e4b589db72b204c972780fe528
|
{
"intermediate": 0.3334985673427582,
"beginner": 0.41503751277923584,
"expert": 0.251463919878006
}
|
10,716
|
write me a c++ code to read from file1 and paste the info of file1 to file2
|
5640c94970187e7d358e02d2e8e2d2af
|
{
"intermediate": 0.559514045715332,
"beginner": 0.19368624687194824,
"expert": 0.24679967761039734
}
|
10,717
|
من انت
|
1d813e7a54112b4f5c00789446471006
|
{
"intermediate": 0.34290367364883423,
"beginner": 0.33264803886413574,
"expert": 0.32444828748703003
}
|
10,718
|
You know in macbook keyboard settings which allows you to change modifier keys. I want to automate it with python
|
e4a10046930779d3a6a0f18f2a97054c
|
{
"intermediate": 0.37143221497535706,
"beginner": 0.28154149651527405,
"expert": 0.3470262885093689
}
|
10,719
|
In roblox, I want the players to always be facing one direction. It is a 2D player fighting game, so naturally I want them to be facing eachother. How do I make this happen
|
e1f541c2e01c07dc66f07ef481a7cb8b
|
{
"intermediate": 0.37659603357315063,
"beginner": 0.22443003952503204,
"expert": 0.3989739716053009
}
|
10,720
|
Give me the longest string of random punctuation that you can
|
f97b9f609925c6fd25a0934bcc74ee9f
|
{
"intermediate": 0.43851035833358765,
"beginner": 0.23857121169567108,
"expert": 0.32291844487190247
}
|
10,721
|
okay, in collection i added a field image and selected as a reference and added after that a document, i uploadded image in storage and after that i just added a link in the document. Is it right or not? im usin firebase in my react native project
|
ef276d34676af85d7270dd5379bda233
|
{
"intermediate": 0.5864107012748718,
"beginner": 0.11672113835811615,
"expert": 0.2968681752681732
}
|
10,722
|
write code in C for Arduino that reads the state of pin 1 every 50 milliseconds, then increments a counter if that pin is high. keep doing this and print the accumulated counter result every 5 seconds
|
d6d1c57dd8fc5f1314b89135b917d584
|
{
"intermediate": 0.4443090856075287,
"beginner": 0.1825181543827057,
"expert": 0.373172789812088
}
|
10,723
|
the below code is a c++ code the first code is for reading from a file and the second code is for writing in a file i want you to combine theses two code into one code and the code can read from file1 and write the content of file1 to file2
first code:
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#include <string>
#define BUF_SIZE 5
int main(int argc,LPCSTR argv[])
{
HANDLE hIn;
DWORD nIn;
CHAR Buffer[BUF_SIZE];
if (argc != 2)
{printf (“Wrong Number of arguments: it should take the file name or path from where to read data\n”);
return 1;}
hIn = CreateFile (argv[1], GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hIn == INVALID_HANDLE_VALUE)
{
printf (“Cannot open filev\n”);
return 2;
}
while (ReadFile (hIn, Buffer, BUF_SIZE, &nIn, NULL) && nIn > 0)
{
printf (“%s”,Buffer);
}
CloseHandle (hIn);
return 0;
}
second code:
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#include <string>
int main(int argc,LPCSTR argv[])
{
HANDLE hOut;
DWORD nOut;
if (argc != 3)
{
printf (“Wrong Number of arguments: it should take the file name or path and the text that will be wrriten in the file??\n”);
return 0;
}
hOut = CreateFile ( argv[1] , GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hOut == INVALID_HANDLE_VALUE)
{
printf (“Cannot open file\n”);
return 0;
}
WriteFile (hOut, argv[2],strlen(argv[2]), &nOut, NULL);
CloseHandle (hOut);
return 1;
}
|
9de98413a8739cc92a8226c7e995eac3
|
{
"intermediate": 0.4287509024143219,
"beginner": 0.24968236684799194,
"expert": 0.32156673073768616
}
|
10,724
|
DirectX::CreateTextureEx 示例
|
78711895e1a406cf3323b2e9ecd66d3f
|
{
"intermediate": 0.2959804832935333,
"beginner": 0.20404960215091705,
"expert": 0.49996984004974365
}
|
10,725
|
Write a java program that runs two threads, each one of them prints on the screen a counter value (which starts from 0 until a20) associated with its thread ID.
Print the output screen which will have
• counter/threadID.
|
6f026dda2259372193d98925d227d649
|
{
"intermediate": 0.4250127673149109,
"beginner": 0.21016736328601837,
"expert": 0.36481988430023193
}
|
10,726
|
Hi
|
a4c60e72e769161df74135c10deb7d81
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
10,727
|
Consider the following differential equation y′′(x) = 2x+ sin[y′(x)]−cos[y(x)] for 0< x <2 y(0) = 0, y(2) = 1)
(1)Solve the equation, numerically, following the procedure outlined today.
that isSet Initial Guess,y(0)ifori= 0, ..., N•DefineF,Fy,Fy′•DefineJi,j(y0, ..., yN)HINT:(Consider tridag function!)•Defineφi(y0, ..., yN)•Solve the system of equationsJ(yk)∆y=−φ(y(k))•Update youry, usingy(k+1)=y(k)+∆y•Run iterations until a ”satisfying” result appears aty(1)
|
9609b2ad8c69b9b966a58dee7622f225
|
{
"intermediate": 0.3115310072898865,
"beginner": 0.3557130992412567,
"expert": 0.3327558934688568
}
|
10,728
|
Please write a shell script for batch squeezing PDF files with CoherentPDF (cpdf)]
|
20c6f38b7c29adc40d721577fd247e8e
|
{
"intermediate": 0.35574671626091003,
"beginner": 0.17692768573760986,
"expert": 0.4673255681991577
}
|
10,729
|
Hi there!
|
21ecf74fbacce5170da4bde12d99acb6
|
{
"intermediate": 0.32267293334007263,
"beginner": 0.25843358039855957,
"expert": 0.4188934564590454
}
|
10,730
|
Hi there
|
1065937f568f535f76d0ef189a3d3e2c
|
{
"intermediate": 0.32728445529937744,
"beginner": 0.24503648281097412,
"expert": 0.42767903208732605
}
|
10,731
|
run powershell script in background
|
d774f67cd4844d7d05249a11155fdcca
|
{
"intermediate": 0.3207547962665558,
"beginner": 0.27376189827919006,
"expert": 0.40548327565193176
}
|
10,732
|
create a python code for calculator
|
b1f0773fb05d8eb634ecaebf0fd546d4
|
{
"intermediate": 0.41868895292282104,
"beginner": 0.33070626854896545,
"expert": 0.2506047785282135
}
|
10,733
|
Please write a shell script for batch squeezing PDF files with CoherentPDF (cpdf)
|
55d927477379a74133fc2ee9209a0f17
|
{
"intermediate": 0.34056544303894043,
"beginner": 0.1884678602218628,
"expert": 0.47096672654151917
}
|
10,734
|
root@truenas[~]# pkg install -y cifs-utils
Updating local repository catalogue...
pkg: file:///usr/ports/packages/meta.txz: No such file or directory
repository local has no meta file, using default settings
pkg: file:///usr/ports/packages/packagesite.pkg: No such file or directory
pkg: file:///usr/ports/packages/packagesite.txz: No such file or directory
Unable to update repository local
Error updating repositories!
|
8ecb09166f20df55324958d99c5a022e
|
{
"intermediate": 0.3843959867954254,
"beginner": 0.38936883211135864,
"expert": 0.22623510658740997
}
|
10,735
|
` if args[0] == "sportsbook":
sports_task = self._tasks.get('sportsbook')
if sports_task:
sports_task.cancel()
elif args[0] == "line":
line_task = self._tasks.get('line')
if line_task:
line_task.cancel()` is this production ready python code?
|
c1319eb842c05b1e56f4db14fe7891a3
|
{
"intermediate": 0.3930662274360657,
"beginner": 0.37723538279533386,
"expert": 0.2296983152627945
}
|
10,736
|
Please write a shell script for batch squeezing PDF files with CoherentPDF (cpdf)
|
b3762ff0f3bafda21b2670414d4be96d
|
{
"intermediate": 0.34056544303894043,
"beginner": 0.1884678602218628,
"expert": 0.47096672654151917
}
|
10,737
|
I have an asp.net core mvc project, write me a view page for displaying a list of products coming from the dbcontext. Also i need you to make a search functionality withing the page. The searchbar should neglect and "display:none" any unmatching product. The search should be by the name and it all runs at realtime without reloading the page. The page should be responsive using tailwindcss. you can use this for the searchbar theme: "<div class="mb-3">
<div class="relative mb-4 flex w-full flex-wrap items-stretch">
<input
type="search"
class="relative m-0 block w-[1px] min-w-0 flex-auto rounded border border-solid border-neutral-300 bg-transparent bg-clip-padding px-3 py-[0.25rem] text-base font-normal leading-[1.6] text-neutral-700 outline-none transition duration-200 ease-in-out focus:z-[3] focus:border-primary focus:text-neutral-700 focus:shadow-[inset_0_0_0_1px_rgb(59,113,202)] focus:outline-none dark:border-neutral-600 dark:text-neutral-200 dark:placeholder:text-neutral-200 dark:focus:border-primary"
placeholder="Search"
aria-label="Search"
aria-describedby="button-addon2" />
<!--Search icon-->
<span
class="input-group-text flex items-center whitespace-nowrap rounded px-3 py-1.5 text-center text-base font-normal text-neutral-700 dark:text-neutral-200"
id="basic-addon2">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="h-5 w-5">
<path
fill-rule="evenodd"
d="M9 3.5a5.5 5.5 0 100 11 5.5 5.5 0 000-11zM2 9a7 7 0 1112.452 4.391l3.328 3.329a.75.75 0 11-1.06 1.06l-3.329-3.328A7 7 0 012 9z"
clip-rule="evenodd" />
</svg>
</span>
</div>
</div>"
|
0cb728e63c157ffd57986f3bb2a18407
|
{
"intermediate": 0.5365156531333923,
"beginner": 0.17863893508911133,
"expert": 0.2848454713821411
}
|
10,738
|
I have a .env file where i declared 2 variables that i read from my function:
let initial_reward_duration = _.get(CONNECTION, "INITIAL_REWARD_DURATION_IN_MONTHS");
const rewardId = _.get(CONNECTION, "INITIAL_REWARD_ID");
console.log("---INITIAL_REWARD_DURATION_IN_MONTHS",initial_reward_duration)
console.log("---INITIAL_REWARD_ID",rewardId)
let specificReward = null;
let expiration_date = new Date();
if(rewardId && initial_reward_duration){
console.log("---ENTRATO DENTRO ALL'IF")
initial_reward_duration = parseInt(initial_reward_duration);
expiration_date.setMonth(expiration_date.getMonth() + initial_reward_duration);
specificReward = await getSpecificReward(req,rewardId);
}
I want to test the case where those 2 variables are undefined (""), i've added an if to check if they are present, if so it has to execute those lines. Is it correct to check like this? What is the default value of undefined and how to check it?
|
cd1bb0a37cc1b02e77b7e31f3d11290b
|
{
"intermediate": 0.3144979476928711,
"beginner": 0.5463667511940002,
"expert": 0.13913533091545105
}
|
10,739
|
how can i resize video from file on storage then save it to storage in react native expo
|
158e4a1b28544d7075235fe1371d1d56
|
{
"intermediate": 0.6064019203186035,
"beginner": 0.1241258904337883,
"expert": 0.2694721221923828
}
|
10,740
|
how do i insert and remove scrollers from ant design
|
d109f58ccbc9b0e3e69c30af442cf244
|
{
"intermediate": 0.2570435404777527,
"beginner": 0.3059940040111542,
"expert": 0.43696242570877075
}
|
10,741
|
I have an asp.net core mvc project, I have a products class and i want you to create an "add" view to get data from the user including: name,text,image. using the best practices save the data coming from the user into the dbcontext.
|
0d0c1aedef1cf4516078c4dffc6833d5
|
{
"intermediate": 0.5497936606407166,
"beginner": 0.24471798539161682,
"expert": 0.2054883986711502
}
|
10,742
|
run powershell script as service
|
322514d188594cc823ea02cdac5a75ac
|
{
"intermediate": 0.32922735810279846,
"beginner": 0.32280489802360535,
"expert": 0.3479676842689514
}
|
10,743
|
I need to optimize hyperparameters of this structure in Python:
#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({'n_estimators': 908, 'max_depth': 1, 'learning_rate': 0.11575834769675744, 'subsample': 0.5942016415422035, 'gamma': 8.93125490769455, 'reg_alpha': 0.14364869510112377, 'reg_lambda': 0.7243048640150956,'eval_metric': 'auc','objective': 'binary:logitraw'}, xdm_train, 20, [(xdm_test, 'eval'), (xdm_train, 'train')])
print(model)
using those optuna functions:
def objective(trial):
n_estimators = trial.suggest_int('n_estimators', 15,1000)
max_depth = trial.suggest_int('max_depth', 1,20)
learning_rate = trial.suggest_float('learning_rate', 0,0.5)
subsample = trial.suggest_float('subsample', 0,1)
gamma = trial.suggest_float("gamma", 1e-4, 1e2)
reg_alpha = trial.suggest_float('reg_alpha', 0,1)
reg_lambda = trial.suggest_float('reg_lambda', 0,1)
model = XGBClassifier(
n_estimators=n_estimators,
max_depth=max_depth,
learning_rate=learning_rate,
subsample=subsample,
gamma=gamma,
reg_alpha=reg_alpha,
reg_lambda=reg_lambda,
eval_metric='auc'
)
score, is_overfitted = validate(model, X, Y)
if is_overfitted:
return 0
else:
return score
study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=500)
and
def validate(model, X, y, X_test=None, y_test=None, show_results=False):
is_classification = is_classifier(model)
use_cross_validation = X_test is None or y_test is None
if use_cross_validation:
if is_classification:
scoring = "roc_auc"
else:
scoring = "r2"
val_results = cross_validate(model, X, y, scoring=scoring, n_jobs=-1, return_train_score=True, cv=3)
train_score = np.mean(val_results["train_score"])
test_score = np.mean(val_results["test_score"])
else:
model.fit(X, y)
pred_train = model.predict(X)
pred_test = model.predict(X_test)
if is_classification:
train_score = metrics.accuracy_score(y, pred_train)
test_score = metrics.accuracy_score(y_test, pred_test)
if show_results:
plot_confusion_matrix(y_test, pred_test)
else:
train_score = metrics.r2_score(y, pred_train)
test_score = metrics.r2_score(y_test, pred_test)
if show_results:
raw_y_train = exp_y(y)
raw_y_test = exp_y(y_test)
raw_pred_train = exp_y(pred_train)
raw_pred_test = exp_y(pred_test)
plot_pred_data(raw_y_test, raw_pred_test)
print(f"train MAE on y:", metrics.mean_absolute_error(raw_y_train, raw_pred_train))
print(f"test MAE on y:", metrics.mean_absolute_error(raw_y_test, raw_pred_test))
is_overfitted = train_score - test_score > 0.025
if show_results:
if is_classification:
print(f"train acc:", train_score)
print(f"test acc:", test_score)
else:
print(f"train r2 on log y:", train_score)
print(f"test r2 on log y:", test_score)
if is_overfitted:
print("Overfitted")
return test_score, is_overfitted
Replace the necessery elements to fit the model mentioned in the first place.
|
5025d99922d1fbeba651f6d5b175ceb5
|
{
"intermediate": 0.2934998869895935,
"beginner": 0.34571635723114014,
"expert": 0.36078372597694397
}
|
10,744
|
write me a code to add a custom table to the default dbcontext in asp.net core mvc
|
0bcc4fed0f5c7e29f745590c0afd9b30
|
{
"intermediate": 0.6162623167037964,
"beginner": 0.14298677444458008,
"expert": 0.24075095355510712
}
|
10,745
|
how can i down resolution of video then save it to storage in react native expo
|
c91b58faab3404df33ee340d1bf8f8aa
|
{
"intermediate": 0.5531255006790161,
"beginner": 0.10867872089147568,
"expert": 0.3381957709789276
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.